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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.33.2  1(raebur    4:2): # $Id: lonnet.pm,v 1.1056.4.33 2011/10/19 16:36:02 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.33  raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1056.4.13  raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1056.4.25  raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1056.4.3  raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1056.4.3  raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1056.4.7  raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1056.4.8  raeburn   258:                     $ua->timeout(4);
1.1056.4.3  raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1056.4.7  raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3  raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1056.4.7  raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3  raeburn   274:                 $loncaparev = $1;
                    275:             }
                    276:         }
                    277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    278:     }
                    279: }
                    280: 
                    281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993     raeburn   285:         if (defined($cached)) {
1.1056.4.3  raeburn   286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') {
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
1.993     raeburn   299:         }
1.1056.4.3  raeburn   300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
1.993     raeburn   305:     }
1.1056.4.3  raeburn   306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993     raeburn   307: }
                    308: 
1.1       albertel  309: # -------------------------------------------------- Non-critical communication
                    310: sub subreply {
                    311:     my ($cmd,$server)=@_;
1.838     albertel  312:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      313:     #
                    314:     #  With loncnew process trimming, there's a timing hole between lonc server
                    315:     #  process exit and the master server picking up the listen on the AF_UNIX
                    316:     #  socket.  In that time interval, a lock file will exist:
                    317: 
                    318:     my $lockfile=$peerfile.".lock";
                    319:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    320: 	sleep(1);
                    321:     }
                    322:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      323:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      324:     #
1.550     foxr      325:     #   We'll give the connection a few tries before abandoning it.  If
                    326:     #   connection is not possible, we'll con_lost back to the client.
                    327:     #   
                    328:     my $client;
                    329:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    330: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    331: 				      Type    => SOCK_STREAM,
                    332: 				      Timeout => 10);
1.869     albertel  333: 	if ($client) {
1.550     foxr      334: 	    last;		# Connected!
1.850     albertel  335: 	} else {
1.853     albertel  336: 	    &create_connection(&hostname($server),$server);
1.550     foxr      337: 	}
1.850     albertel  338:         sleep(1);		# Try again later if failed connection.
1.550     foxr      339:     }
                    340:     my $answer;
                    341:     if ($client) {
1.704     albertel  342: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      343: 	$answer=<$client>;
                    344: 	if (!$answer) { $answer="con_lost"; }
                    345: 	chomp($answer);
                    346:     } else {
                    347: 	$answer = 'con_lost';	# Failed connection.
                    348:     }
1.1       albertel  349:     return $answer;
                    350: }
                    351: 
                    352: sub reply {
                    353:     my ($cmd,$server)=@_;
1.838     albertel  354:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  355:     my $answer=subreply($cmd,$server);
1.65      www       356:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  357:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       358:                 " $cmd to $server returned $answer</font>");
                    359:     }
1.1       albertel  360:     return $answer;
                    361: }
                    362: 
                    363: # ----------------------------------------------------------- Send USR1 to lonc
                    364: 
                    365: sub reconlonc {
1.891     albertel  366:     my ($lonid) = @_;
                    367:     my $hostname = &hostname($lonid);
                    368:     if ($lonid) {
                    369: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    370: 	if ($hostname && -e $peerfile) {
                    371: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    372: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    373: 					     Type    => SOCK_STREAM,
                    374: 					     Timeout => 10);
                    375: 	    if ($client) {
                    376: 		print $client ("reset_retries\n");
                    377: 		my $answer=<$client>;
                    378: 		#reset just this one.
                    379: 	    }
                    380: 	}
                    381: 	return;
                    382:     }
                    383: 
1.836     www       384:     &logthis("Trying to reconnect lonc");
1.1       albertel  385:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  386:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  387: 	my $loncpid=<$fh>;
                    388:         chomp($loncpid);
                    389:         if (kill 0 => $loncpid) {
                    390: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    391:             kill USR1 => $loncpid;
                    392:             sleep 1;
1.836     www       393:          } else {
1.12      www       394: 	    &logthis(
1.672     albertel  395:                "<font color=\"blue\">WARNING:".
1.12      www       396:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  397:         }
                    398:     } else {
1.836     www       399: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  400:     }
                    401: }
                    402: 
                    403: # ------------------------------------------------------ Critical communication
1.12      www       404: 
1.1       albertel  405: sub critical {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (&hostname($server)) {
1.672     albertel  408:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       409:                " Critical message to unknown server ($server)</font>");
                    410:         return 'no_such_host';
                    411:     }
1.1       albertel  412:     my $answer=reply($cmd,$server);
                    413:     if ($answer eq 'con_lost') {
                    414: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  415: 	my $answer=reply($cmd,$server);
1.1       albertel  416:         if ($answer eq 'con_lost') {
                    417:             my $now=time;
                    418:             my $middlename=$cmd;
1.5       www       419:             $middlename=substr($middlename,0,16);
1.1       albertel  420:             $middlename=~s/\W//g;
                    421:             my $dfilename=
1.305     www       422:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    423:             $dumpcount++;
1.1       albertel  424:             {
1.448     albertel  425: 		my $dfh;
                    426: 		if (open($dfh,">$dfilename")) {
                    427: 		    print $dfh "$cmd\n"; 
                    428: 		    close($dfh);
                    429: 		}
1.1       albertel  430:             }
                    431:             sleep 2;
                    432:             my $wcmd='';
                    433:             {
1.448     albertel  434: 		my $dfh;
                    435: 		if (open($dfh,"<$dfilename")) {
                    436: 		    $wcmd=<$dfh>; 
                    437: 		    close($dfh);
                    438: 		}
1.1       albertel  439:             }
                    440:             chomp($wcmd);
1.7       www       441:             if ($wcmd eq $cmd) {
1.672     albertel  442: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       443:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  444:                 &logperm("D:$server:$cmd");
                    445: 	        return 'con_delayed';
                    446:             } else {
1.672     albertel  447:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       448:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  449:                 &logperm("F:$server:$cmd");
                    450:                 return 'con_failed';
                    451:             }
                    452:         }
                    453:     }
                    454:     return $answer;
1.405     albertel  455: }
                    456: 
1.755     albertel  457: # ------------------------------------------- check if return value is an error
                    458: 
                    459: sub error {
                    460:     my ($result) = @_;
1.756     albertel  461:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  462: 	if ($2 == 2) { return undef; }
                    463: 	return $1;
                    464:     }
                    465:     return undef;
                    466: }
                    467: 
1.783     albertel  468: sub convert_and_load_session_env {
                    469:     my ($lonidsdir,$handle)=@_;
                    470:     my @profile;
                    471:     {
1.917     albertel  472: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    473: 	if (!$opened) {
1.915     albertel  474: 	    return 0;
                    475: 	}
1.783     albertel  476: 	flock($idf,LOCK_SH);
                    477: 	@profile=<$idf>;
                    478: 	close($idf);
                    479:     }
                    480:     my %temp_env;
                    481:     foreach my $line (@profile) {
1.786     albertel  482: 	if ($line !~ m/=/) {
                    483: 	    return 0;
                    484: 	}
1.783     albertel  485: 	chomp($line);
                    486: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    487: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    488:     }
                    489:     unlink("$lonidsdir/$handle.id");
                    490:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    491: 	    0640)) {
                    492: 	%disk_env = %temp_env;
                    493: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    494: 	untie(%disk_env);
                    495:     }
1.786     albertel  496:     return 1;
1.783     albertel  497: }
                    498: 
1.374     www       499: # ------------------------------------------- Transfer profile into environment
1.780     albertel  500: my $env_loaded;
                    501: sub transfer_profile_to_env {
1.788     albertel  502:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    503:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       504: 
1.720     albertel  505:     if (!defined($lonidsdir)) {
                    506: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    507:     }
                    508:     if (!defined($handle)) {
                    509:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    510:     }
                    511: 
1.786     albertel  512:     my $convert;
                    513:     {
1.917     albertel  514:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    515: 	if (!$opened) {
1.915     albertel  516: 	    return;
                    517: 	}
1.786     albertel  518: 	flock($idf,LOCK_SH);
                    519: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    520: 		&GDBM_READER(),0640)) {
                    521: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    522: 	    untie(%disk_env);
                    523: 	} else {
                    524: 	    $convert = 1;
                    525: 	}
                    526:     }
                    527:     if ($convert) {
                    528: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    529: 	    &logthis("Failed to load session, or convert session.");
                    530: 	}
1.374     www       531:     }
1.783     albertel  532: 
1.786     albertel  533:     my %remove;
1.783     albertel  534:     while ( my $envname = each(%env) ) {
1.433     matthew   535:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    536:             if ($time < time-300) {
1.783     albertel  537:                 $remove{$key}++;
1.433     matthew   538:             }
                    539:         }
                    540:     }
1.783     albertel  541: 
1.619     albertel  542:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  543:     $env_loaded=1;
1.783     albertel  544:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   545:         &delenv($expired_key);
1.374     www       546:     }
1.1       albertel  547: }
                    548: 
1.916     albertel  549: # ---------------------------------------------------- Check for valid session 
                    550: sub check_for_valid_session {
                    551:     my ($r) = @_;
                    552:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    553:     my $lonid=$cookies{'lonID'};
                    554:     return undef if (!$lonid);
                    555: 
                    556:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    557:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    558:     return undef if (!-e "$lonidsdir/$handle.id");
                    559: 
1.917     albertel  560:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561:     return undef if (!$opened);
1.916     albertel  562: 
                    563:     flock($idf,LOCK_SH);
                    564:     my %disk_env;
                    565:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 	    &GDBM_READER(),0640)) {
                    567: 	return undef;	
                    568:     }
                    569: 
                    570:     if (!defined($disk_env{'user.name'})
                    571: 	|| !defined($disk_env{'user.domain'})) {
                    572: 	return undef;
                    573:     }
                    574:     return $handle;
                    575: }
                    576: 
1.830     albertel  577: sub timed_flock {
                    578:     my ($file,$lock_type) = @_;
                    579:     my $failed=0;
                    580:     eval {
                    581: 	local $SIG{__DIE__}='DEFAULT';
                    582: 	local $SIG{ALRM}=sub {
                    583: 	    $failed=1;
                    584: 	    die("failed lock");
                    585: 	};
                    586: 	alarm(13);
                    587: 	flock($file,$lock_type);
                    588: 	alarm(0);
                    589:     };
                    590:     if ($failed) {
                    591: 	return undef;
                    592:     } else {
                    593: 	return 1;
                    594:     }
                    595: }
                    596: 
1.5       www       597: # ---------------------------------------------------------- Append Environment
                    598: 
                    599: sub appenv {
1.949     raeburn   600:     my ($newenv,$roles) = @_;
                    601:     if (ref($newenv) eq 'HASH') {
                    602:         foreach my $key (keys(%{$newenv})) {
                    603:             my $refused = 0;
                    604: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    605:                 $refused = 1;
                    606:                 if (ref($roles) eq 'ARRAY') {
                    607:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    608:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    609:                         $refused = 0;
                    610:                     }
                    611:                 }
                    612:             }
                    613:             if ($refused) {
                    614:                 &logthis("<font color=\"blue\">WARNING: ".
                    615:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    616:                          .'</font>');
                    617: 	        delete($newenv->{$key});
                    618:             } else {
                    619:                 $env{$key}=$newenv->{$key};
                    620:             }
                    621:         }
                    622:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    623:         if ($opened
                    624: 	    && &timed_flock($env_file,LOCK_EX)
                    625: 	    &&
                    626: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    627: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    628: 	    while (my ($key,$value) = each(%{$newenv})) {
                    629: 	        $disk_env{$key} = $value;
                    630: 	    }
                    631: 	    untie(%disk_env);
1.35      www       632:         }
1.191     harris41  633:     }
1.56      www       634:     return 'ok';
                    635: }
                    636: # ----------------------------------------------------- Delete from Environment
                    637: 
                    638: sub delenv {
1.987     raeburn   639:     my ($delthis,$regexp) = @_;
1.56      www       640:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  641:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       642:                 "Attempt to delete from environment ".$delthis);
                    643:         return 'error';
                    644:     }
1.917     albertel  645:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    646:     if ($opened
1.915     albertel  647: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  648: 	&&
                    649: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    650: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  651: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   652: 	    if ($regexp) {
                    653:                 if ($key=~/^$delthis/) {
                    654:                     delete($env{$key});
                    655:                     delete($disk_env{$key});
                    656:                 } 
                    657:             } else {
                    658:                 if ($key=~/^\Q$delthis\E/) {
                    659: 		    delete($env{$key});
                    660: 		    delete($disk_env{$key});
                    661: 	        }
                    662:             }
1.448     albertel  663: 	}
1.783     albertel  664: 	untie(%disk_env);
1.5       www       665:     }
                    666:     return 'ok';
1.369     albertel  667: }
                    668: 
1.790     albertel  669: sub get_env_multiple {
                    670:     my ($name) = @_;
                    671:     my @values;
                    672:     if (defined($env{$name})) {
                    673:         # exists is it an array
                    674:         if (ref($env{$name})) {
                    675:             @values=@{ $env{$name} };
                    676:         } else {
                    677:             $values[0]=$env{$name};
                    678:         }
                    679:     }
                    680:     return(@values);
                    681: }
                    682: 
1.958     www       683: # ------------------------------------------------------------------- Locking
                    684: 
                    685: sub set_lock {
                    686:     my ($text)=@_;
                    687:     $locknum++;
                    688:     my $id=$$.'-'.$locknum;
                    689:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    690:              'session.lock.'.$id => $text});
                    691:     return $id;
                    692: }
                    693: 
                    694: sub get_locks {
                    695:     my $num=0;
                    696:     my %texts=();
                    697:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    698:        if ($lock=~/\w/) {
                    699:           $num++;
                    700:           $texts{$lock}=$env{'session.lock.'.$lock};
                    701:        }
                    702:    }
                    703:    return ($num,%texts);
                    704: }
                    705: 
                    706: sub remove_lock {
                    707:     my ($id)=@_;
                    708:     my $newlocks='';
                    709:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    710:        if (($lock=~/\w/) && ($lock ne $id)) {
                    711:           $newlocks.=','.$lock;
                    712:        }
                    713:     }
                    714:     &appenv({'session.locks' => $newlocks});
                    715:     &delenv('session.lock.'.$id);
                    716: }
                    717: 
                    718: sub remove_all_locks {
                    719:     my $activelocks=$env{'session.locks'};
                    720:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    721:        if ($lock=~/\w/) {
                    722:           &remove_lock($lock);
                    723:        }
                    724:     }
                    725: }
                    726: 
                    727: 
1.369     albertel  728: # ------------------------------------------ Find out current server userload
                    729: sub userload {
                    730:     my $numusers=0;
                    731:     {
                    732: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    733: 	my $filename;
                    734: 	my $curtime=time;
                    735: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  736: 	    next if ($filename eq '.' || $filename eq '..');
                    737: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  738: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  739: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  740: 	}
                    741: 	closedir(LONIDS);
                    742:     }
                    743:     my $userloadpercent=0;
                    744:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    745:     if ($maxuserload) {
1.371     albertel  746: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  747:     }
1.372     albertel  748:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  749:     return $userloadpercent;
1.283     www       750: }
                    751: 
                    752: # ------------------------------------------ Fight off request when overloaded
                    753: 
                    754: sub overloaderror {
                    755:     my ($r,$checkserver)=@_;
                    756:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    757:     my $loadavg;
                    758:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  759:        open(my $loadfile,'/proc/loadavg');
1.283     www       760:        $loadavg=<$loadfile>;
                    761:        $loadavg =~ s/\s.*//g;
1.285     matthew   762:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  763:        close($loadfile);
1.283     www       764:     } else {
                    765:        $loadavg=&reply('load',$checkserver);
                    766:     }
1.285     matthew   767:     my $overload=$loadavg-100;
1.283     www       768:     if ($overload>0) {
1.285     matthew   769: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       770:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       771:         return 413;
1.283     www       772:     }    
                    773:     return '';
1.5       www       774: }
1.1       albertel  775: 
                    776: # ------------------------------ Find server with least workload from spare.tab
1.11      www       777: 
1.1       albertel  778: sub spareserver {
1.1056.4.23  raeburn   779:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  780:     my $spare_server;
1.370     albertel  781:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  782:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    783:                                                      :  $userloadpercent;
1.1056.4.8  raeburn   784:     my ($uint_dom,$remotesessions);
1.1056.4.23  raeburn   785:     if (($udom ne '') && (&domain($udom) ne '')) {
                    786:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1.1056.4.8  raeburn   787:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.23  raeburn   788:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
1.1056.4.8  raeburn   789:         $remotesessions = $udomdefaults{'remotesessions'};
                    790:     }
1.784     albertel  791:     foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8  raeburn   792:         if ($uint_dom) {
1.1056.4.23  raeburn   793:             next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    794:                                          $try_server));
1.1056.4.8  raeburn   795:         }
1.784     albertel  796: 	($spare_server, $lowest_load) =
                    797: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    798:     }
                    799: 
                    800:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    801: 
                    802:     if (!$found_server) {
                    803: 	foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8  raeburn   804:             if ($uint_dom) {
1.1056.4.23  raeburn   805:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    806:                                              $try_server));
1.1056.4.8  raeburn   807:             }
1.784     albertel  808: 	    ($spare_server, $lowest_load) =
                    809: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    810: 	}
                    811:     }
                    812: 
                    813:     if (!$want_server_name) {
1.968     raeburn   814:         my $protocol = 'http';
                    815:         if ($protocol{$spare_server} eq 'https') {
                    816:             $protocol = $protocol{$spare_server};
                    817:         }
1.1001    raeburn   818:         if (defined($spare_server)) {
                    819:             my $hostname = &hostname($spare_server);
1.1056.4.8  raeburn   820:             if (defined($hostname)) {
1.1001    raeburn   821: 	        $spare_server = $protocol.'://'.$hostname;
                    822:             }
                    823:         }
1.784     albertel  824:     }
                    825:     return $spare_server;
                    826: }
                    827: 
                    828: sub compare_server_load {
                    829:     my ($try_server, $spare_server, $lowest_load) = @_;
                    830: 
                    831:     my $loadans     = &reply('load',    $try_server);
                    832:     my $userloadans = &reply('userload',$try_server);
                    833: 
                    834:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.29  raeburn   835:         return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  836:     }
                    837: 
                    838:     my $load;
                    839:     if ($loadans =~ /\d/) {
                    840: 	if ($userloadans =~ /\d/) {
                    841: 	    #both are numbers, pick the bigger one
                    842: 	    $load = ($loadans > $userloadans) ? $loadans 
                    843: 		                              : $userloadans;
1.411     albertel  844: 	} else {
1.784     albertel  845: 	    $load = $loadans;
1.411     albertel  846: 	}
1.784     albertel  847:     } else {
                    848: 	$load = $userloadans;
                    849:     }
                    850: 
                    851:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    852: 	$spare_server = $try_server;
                    853: 	$lowest_load  = $load;
1.370     albertel  854:     }
1.784     albertel  855:     return ($spare_server,$lowest_load);
1.202     matthew   856: }
1.914     albertel  857: 
                    858: # --------------------------- ask offload servers if user already has a session
                    859: sub find_existing_session {
                    860:     my ($udom,$uname) = @_;
                    861:     foreach my $try_server (@{ $spareid{'primary'} },
                    862: 			    @{ $spareid{'default'} }) {
                    863: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    864:     }
                    865:     return;
                    866: }
                    867: 
                    868: # -------------------------------- ask if server already has a session for user
                    869: sub has_user_session {
                    870:     my ($lonid,$udom,$uname) = @_;
                    871:     my $result = &reply(join(':','userhassession',
                    872: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    873:     return 1 if ($result eq 'ok');
                    874: 
                    875:     return 0;
                    876: }
                    877: 
1.1056.4.3  raeburn   878: # --------- determine least loaded server in a user's domain which allows login
                    879: 
                    880: sub choose_server {
1.1056.4.31  raeburn   881:     my ($udom,$checkloginvia) = @_;
1.1056.4.3  raeburn   882:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
                    883:     my %servers = &get_servers($udom);
                    884:     my $lowest_load = 30000;
1.1056.4.33.2  1(raebur  885:2):     my ($login_host,$hostname,$portal_path,$isredirect);
1.1056.4.3  raeburn   886:     foreach my $lonhost (keys(%servers)) {
1.1056.4.31  raeburn   887:         my $loginvia;
                    888:         if ($checkloginvia) {
                    889:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
                    890:             if ($loginvia) {
                    891:                 my ($server,$path) = split(/:/,$loginvia);
                    892:                 ($login_host, $lowest_load) =
                    893:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    894:                 if ($login_host eq $server) {
                    895:                     $portal_path = $path;
1.1056.4.33.2  1(raebur  896:2):                     $isredirect = 1;
1.1056.4.31  raeburn   897:                 }
                    898:             } else {
                    899:                 ($login_host, $lowest_load) =
                    900:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    901:                 if ($login_host eq $lonhost) {
                    902:                     $portal_path = '';
1.1056.4.33.2  1(raebur  903:2):                     $isredirect = '';
1.1056.4.31  raeburn   904:                 }
                    905:             }
                    906:         } else {
1.1056.4.3  raeburn   907:             ($login_host, $lowest_load) =
1.1056.4.31  raeburn   908:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1056.4.3  raeburn   909:         }
                    910:     }
                    911:     if ($login_host ne '') {
1.1056.4.31  raeburn   912:         $hostname = &hostname($login_host);
1.1056.4.3  raeburn   913:     }
1.1056.4.33.2  1(raebur  914:2):     return ($login_host,$hostname,$portal_path,$isredirect);
1.1056.4.3  raeburn   915: }
                    916: 
1.202     matthew   917: # --------------------------------------------- Try to change a user's password
                    918: 
                    919: sub changepass {
1.799     raeburn   920:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   921:     $currentpass = &escape($currentpass);
                    922:     $newpass     = &escape($newpass);
1.1030    raeburn   923:     my $lonhost = $perlvar{'lonHostID'};
                    924:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   925: 		       $server);
                    926:     if (! $answer) {
                    927: 	&logthis("No reply on password change request to $server ".
                    928: 		 "by $uname in domain $udom.");
                    929:     } elsif ($answer =~ "^ok") {
                    930:         &logthis("$uname in $udom successfully changed their password ".
                    931: 		 "on $server.");
                    932:     } elsif ($answer =~ "^pwchange_failure") {
                    933: 	&logthis("$uname in $udom was unable to change their password ".
                    934: 		 "on $server.  The action was blocked by either lcpasswd ".
                    935: 		 "or pwchange");
                    936:     } elsif ($answer =~ "^non_authorized") {
                    937:         &logthis("$uname in $udom did not get their password correct when ".
                    938: 		 "attempting to change it on $server.");
                    939:     } elsif ($answer =~ "^auth_mode_error") {
                    940:         &logthis("$uname in $udom attempted to change their password despite ".
                    941: 		 "not being locally or internally authenticated on $server.");
                    942:     } elsif ($answer =~ "^unknown_user") {
                    943:         &logthis("$uname in $udom attempted to change their password ".
                    944: 		 "on $server but were unable to because $server is not ".
                    945: 		 "their home server.");
                    946:     } elsif ($answer =~ "^refused") {
                    947: 	&logthis("$server refused to change $uname in $udom password because ".
                    948: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   949:     } elsif ($answer =~ "invalid_client") {
                    950:         &logthis("$server refused to change $uname in $udom password because ".
                    951:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   952:     }
                    953:     return $answer;
1.1       albertel  954: }
                    955: 
1.169     harris41  956: # ----------------------- Try to determine user's current authentication scheme
                    957: 
                    958: sub queryauthenticate {
                    959:     my ($uname,$udom)=@_;
1.456     albertel  960:     my $uhome=&homeserver($uname,$udom);
                    961:     if (!$uhome) {
                    962: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    963: 	return 'no_host';
                    964:     }
                    965:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    966:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    967: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  968:     }
1.456     albertel  969:     return $answer;
1.169     harris41  970: }
                    971: 
1.1       albertel  972: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       973: 
1.1       albertel  974: sub authenticate {
1.1056.4.3  raeburn   975:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  976:     $upass=&escape($upass);
                    977:     $uname= &LONCAPA::clean_username($uname);
1.836     www       978:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   979:     my $newhome;
1.836     www       980:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    981: # Maybe the machine was offline and only re-appeared again recently?
                    982:         &reconlonc();
                    983: # One more
1.952     raeburn   984: 	$uhome=&homeserver($uname,$udom,1);
                    985:         if (($uhome eq 'no_host') && $checkdefauth) {
                    986:             if (defined(&domain($udom,'primary'))) {
                    987:                 $newhome=&domain($udom,'primary');
                    988:             }
                    989:             if ($newhome ne '') {
                    990:                 $uhome = $newhome;
                    991:             }
                    992:         }
1.836     www       993: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    994: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   995: 	    return 'no_host';
                    996:         }
1.1       albertel  997:     }
1.1056.4.3  raeburn   998:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  999:     if ($answer eq 'authorized') {
1.952     raeburn  1000:         if ($newhome) {
                   1001:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1002:             return 'no_account_on_host'; 
                   1003:         } else {
                   1004:             &logthis("User $uname at $udom authorized by $uhome");
                   1005:             return $uhome;
                   1006:         }
1.471     albertel 1007:     }
                   1008:     if ($answer eq 'non_authorized') {
                   1009: 	&logthis("User $uname at $udom rejected by $uhome");
                   1010: 	return 'no_host'; 
1.9       www      1011:     }
1.471     albertel 1012:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1013:     return 'no_host';
                   1014: }
                   1015: 
1.1056.4.3  raeburn  1016: sub can_host_session {
                   1017:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                   1018:     my $canhost = 1;
                   1019:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                   1020:     if (ref($remotesessions) eq 'HASH') {
                   1021:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                   1022:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                   1023:                 $canhost = 0;
                   1024:             } else {
                   1025:                 $canhost = 1;
                   1026:             }
                   1027:         }
                   1028:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                   1029:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                   1030:                 $canhost = 1;
                   1031:             } else {
                   1032:                 $canhost = 0;
                   1033:             }
                   1034:         }
                   1035:         if ($canhost) {
                   1036:             if ($remotesessions->{'version'} ne '') {
                   1037:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1038:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1039:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1040:                         my $major = $1;
                   1041:                         my $minor = $2;
                   1042:                         if (($major < $reqmajor ) ||
                   1043:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1044:                             $canhost = 0;
                   1045:                         }
                   1046:                     } else {
                   1047:                         $canhost = 0;
                   1048:                     }
                   1049:                 }
                   1050:             }
                   1051:         }
                   1052:     }
                   1053:     if ($canhost) {
                   1054:         if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28  raeburn  1055:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1056:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3  raeburn  1057:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1058:                 if (($uint_dom ne '') && 
                   1059:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3  raeburn  1060:                     $canhost = 0;
                   1061:                 } else {
                   1062:                     $canhost = 1;
                   1063:                 }
                   1064:             }
                   1065:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1066:                 if (($uint_dom ne '') && 
                   1067:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3  raeburn  1068:                     $canhost = 1;
                   1069:                 } else {
                   1070:                     $canhost = 0;
                   1071:                 }
                   1072:             }
                   1073:         }
                   1074:     }
                   1075:     return $canhost;
                   1076: }
                   1077: 
1.1056.4.8  raeburn  1078: sub spare_can_host {
                   1079:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1080:     my $canhost=1;
                   1081:     my @intdoms;
                   1082:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1083:     if (ref($internet_names) eq 'ARRAY') {
                   1084:         @intdoms = @{$internet_names};
                   1085:     }
                   1086:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1087:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1088:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1089:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1090:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1091:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1092:                                      $remotesessions,
                   1093:                                      $defdomdefaults{'hostedsessions'});
                   1094:     }
                   1095:     return $canhost;
                   1096: }
                   1097: 
1.1       albertel 1098: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1099: 
1.599     albertel 1100: my %homecache;
1.1       albertel 1101: sub homeserver {
1.230     stredwic 1102:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1103:     my $index="$uname:$udom";
1.426     albertel 1104: 
1.599     albertel 1105:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1106: 
                   1107:     my %servers = &get_servers($udom,'library');
                   1108:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1109:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1110: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1111: 
                   1112: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1113: 	if ($answer eq 'found') {
                   1114: 	    delete($badServerCache{$tryserver}); 
                   1115: 	    return $homecache{$index}=$tryserver;
                   1116: 	} elsif ($answer eq 'no_host') {
                   1117: 	    $badServerCache{$tryserver}=1;
                   1118: 	}
1.1       albertel 1119:     }    
                   1120:     return 'no_host';
1.70      www      1121: }
                   1122: 
                   1123: # ------------------------------------- Find the usernames behind a list of IDs
                   1124: 
                   1125: sub idget {
                   1126:     my ($udom,@ids)=@_;
                   1127:     my %returnhash=();
                   1128:     
1.841     albertel 1129:     my %servers = &get_servers($udom,'library');
                   1130:     foreach my $tryserver (keys(%servers)) {
                   1131: 	my $idlist=join('&',@ids);
                   1132: 	$idlist=~tr/A-Z/a-z/; 
                   1133: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1134: 	my @answer=();
                   1135: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1136: 	    @answer=split(/\&/,$reply);
                   1137: 	}                    ;
                   1138: 	my $i;
                   1139: 	for ($i=0;$i<=$#ids;$i++) {
                   1140: 	    if ($answer[$i]) {
                   1141: 		$returnhash{$ids[$i]}=$answer[$i];
                   1142: 	    } 
                   1143: 	}
                   1144:     } 
1.70      www      1145:     return %returnhash;
                   1146: }
                   1147: 
                   1148: # ------------------------------------- Find the IDs behind a list of usernames
                   1149: 
                   1150: sub idrget {
                   1151:     my ($udom,@unames)=@_;
                   1152:     my %returnhash=();
1.800     albertel 1153:     foreach my $uname (@unames) {
                   1154:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1155:     }
1.70      www      1156:     return %returnhash;
                   1157: }
                   1158: 
                   1159: # ------------------------------- Store away a list of names and associated IDs
                   1160: 
                   1161: sub idput {
                   1162:     my ($udom,%ids)=@_;
                   1163:     my %servers=();
1.800     albertel 1164:     foreach my $uname (keys(%ids)) {
                   1165: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1166:         my $uhom=&homeserver($uname,$udom);
1.70      www      1167:         if ($uhom ne 'no_host') {
1.800     albertel 1168:             my $id=&escape($ids{$uname});
1.70      www      1169:             $id=~tr/A-Z/a-z/;
1.800     albertel 1170:             my $esc_unam=&escape($uname);
1.70      www      1171: 	    if ($servers{$uhom}) {
1.800     albertel 1172: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1173:             } else {
1.800     albertel 1174:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1175:             }
                   1176:         }
1.191     harris41 1177:     }
1.800     albertel 1178:     foreach my $server (keys(%servers)) {
                   1179:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1180:     }
1.344     www      1181: }
                   1182: 
1.1023    raeburn  1183: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1184: sub dump_dom {
1.1023    raeburn  1185:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1186:     if (!$udom) {
                   1187:         $udom=$env{'user.domain'};
                   1188:     }
                   1189:     my %returnhash;
1.1023    raeburn  1190:     if ($udom) {
                   1191:         my $uname = &get_domainconfiguser($udom);
                   1192:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1193:     }
                   1194:     return %returnhash;
                   1195: }
                   1196: 
1.1023    raeburn  1197: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1198: 
                   1199: sub get_dom {
1.860     raeburn  1200:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1201:     my $items='';
                   1202:     foreach my $item (@$storearr) {
                   1203:         $items.=&escape($item).'&';
                   1204:     }
                   1205:     $items=~s/\&$//;
1.860     raeburn  1206:     if (!$udom) {
                   1207:         $udom=$env{'user.domain'};
                   1208:         if (defined(&domain($udom,'primary'))) {
                   1209:             $uhome=&domain($udom,'primary');
                   1210:         } else {
1.874     albertel 1211:             undef($uhome);
1.860     raeburn  1212:         }
                   1213:     } else {
                   1214:         if (!$uhome) {
                   1215:             if (defined(&domain($udom,'primary'))) {
                   1216:                 $uhome=&domain($udom,'primary');
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1221:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1222:         my %returnhash;
1.875     albertel 1223:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1224:             return %returnhash;
                   1225:         }
1.806     raeburn  1226:         my @pairs=split(/\&/,$rep);
                   1227:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1228:             return @pairs;
                   1229:         }
                   1230:         my $i=0;
                   1231:         foreach my $item (@$storearr) {
                   1232:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1233:             $i++;
                   1234:         }
                   1235:         return %returnhash;
                   1236:     } else {
1.880     banghart 1237:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1238:     }
                   1239: }
                   1240: 
                   1241: # -------------------------------------------- put items in domain db files 
                   1242: 
                   1243: sub put_dom {
1.860     raeburn  1244:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1245:     if (!$udom) {
                   1246:         $udom=$env{'user.domain'};
                   1247:         if (defined(&domain($udom,'primary'))) {
                   1248:             $uhome=&domain($udom,'primary');
                   1249:         } else {
1.874     albertel 1250:             undef($uhome);
1.860     raeburn  1251:         }
                   1252:     } else {
                   1253:         if (!$uhome) {
                   1254:             if (defined(&domain($udom,'primary'))) {
                   1255:                 $uhome=&domain($udom,'primary');
                   1256:             }
                   1257:         }
                   1258:     } 
                   1259:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1260:         my $items='';
                   1261:         foreach my $item (keys(%$storehash)) {
                   1262:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1263:         }
                   1264:         $items=~s/\&$//;
                   1265:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1266:     } else {
1.860     raeburn  1267:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1268:     }
                   1269: }
                   1270: 
1.1023    raeburn  1271: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1272: sub newput_dom {
1.1023    raeburn  1273:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1274:     my $result;
                   1275:     if (!$udom) {
                   1276:         $udom=$env{'user.domain'};
                   1277:     }
1.1023    raeburn  1278:     if ($udom) {
                   1279:         my $uname = &get_domainconfiguser($udom);
                   1280:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1281:     }
                   1282:     return $result;
                   1283: }
                   1284: 
1.1023    raeburn  1285: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1286: sub del_dom {
1.1023    raeburn  1287:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1288:     if (ref($storearr) eq 'ARRAY') {
                   1289:         if (!$udom) {
                   1290:             $udom=$env{'user.domain'};
                   1291:         }
1.1023    raeburn  1292:         if ($udom) {
                   1293:             my $uname = &get_domainconfiguser($udom); 
                   1294:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1295:         }
                   1296:     }
                   1297: }
                   1298: 
1.1023    raeburn  1299: # ----------------------------------construct domainconfig user for a domain 
                   1300: sub get_domainconfiguser {
                   1301:     my ($udom) = @_;
                   1302:     return $udom.'-domainconfig';
                   1303: }
                   1304: 
1.837     raeburn  1305: sub retrieve_inst_usertypes {
                   1306:     my ($udom) = @_;
                   1307:     my (%returnhash,@order);
1.989     raeburn  1308:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1309:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1310:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1311:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1312:         @order = @{$domdefs{'inststatusorder'}};
                   1313:     } else {
                   1314:         if (defined(&domain($udom,'primary'))) {
                   1315:             my $uhome=&domain($udom,'primary');
                   1316:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1317:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1318:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1319:                 return (\%returnhash,\@order);
                   1320:             }
                   1321:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1322:             my @pairs=split(/\&/,$hashitems);
                   1323:             foreach my $item (@pairs) {
                   1324:                 my ($key,$value)=split(/=/,$item,2);
                   1325:                 $key = &unescape($key);
                   1326:                 next if ($key =~ /^error: 2 /);
                   1327:                 $returnhash{$key}=&thaw_unescape($value);
                   1328:             }
                   1329:             my @esc_order = split(/\&/,$orderitems);
                   1330:             foreach my $item (@esc_order) {
                   1331:                 push(@order,&unescape($item));
                   1332:             }
                   1333:         } else {
                   1334:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1335:         }
                   1336:     }
                   1337:     return (\%returnhash,\@order);
                   1338: }
                   1339: 
1.868     raeburn  1340: sub is_domainimage {
                   1341:     my ($url) = @_;
                   1342:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1343:         if (&domain($1) ne '') {
                   1344:             return '1';
                   1345:         }
                   1346:     }
                   1347:     return;
                   1348: }
                   1349: 
1.899     raeburn  1350: sub inst_directory_query {
                   1351:     my ($srch) = @_;
                   1352:     my $udom = $srch->{'srchdomain'};
                   1353:     my %results;
                   1354:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1355:     my $outcome;
1.899     raeburn  1356:     if ($homeserver ne '') {
1.904     albertel 1357: 	my $queryid=&reply("querysend:instdirsearch:".
                   1358: 			   &escape($srch->{'srchby'}).':'.
                   1359: 			   &escape($srch->{'srchterm'}).':'.
                   1360: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1361: 	my $host=&hostname($homeserver);
                   1362: 	if ($queryid !~/^\Q$host\E\_/) {
                   1363: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1364: 	    return;
                   1365: 	}
                   1366: 	my $response = &get_query_reply($queryid);
                   1367: 	my $maxtries = 5;
                   1368: 	my $tries = 1;
                   1369: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1370: 	    $response = &get_query_reply($queryid);
                   1371: 	    $tries ++;
                   1372: 	}
                   1373: 
                   1374:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1375:             if ($response eq 'unavailable') {
                   1376:                 $outcome = $response;
                   1377:             } else {
                   1378:                 $outcome = 'ok';
                   1379:                 my @matches = split(/\n/,$response);
                   1380:                 foreach my $match (@matches) {
                   1381:                     my ($key,$value) = split(/=/,$match);
                   1382:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1383:                 }
1.899     raeburn  1384:             }
                   1385:         }
                   1386:     }
1.909     raeburn  1387:     return ($outcome,%results);
1.899     raeburn  1388: }
                   1389: 
                   1390: sub usersearch {
                   1391:     my ($srch) = @_;
                   1392:     my $dom = $srch->{'srchdomain'};
                   1393:     my %results;
                   1394:     my %libserv = &all_library();
                   1395:     my $query = 'usersearch';
                   1396:     foreach my $tryserver (keys(%libserv)) {
                   1397:         if (&host_domain($tryserver) eq $dom) {
                   1398:             my $host=&hostname($tryserver);
                   1399:             my $queryid=
1.911     raeburn  1400:                 &reply("querysend:".&escape($query).':'.
                   1401:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1402:                        &escape($srch->{'srchtype'}).':'.
                   1403:                        &escape($srch->{'srchterm'}),$tryserver);
                   1404:             if ($queryid !~/^\Q$host\E\_/) {
                   1405:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1406:                 next;
1.899     raeburn  1407:             }
                   1408:             my $reply = &get_query_reply($queryid);
                   1409:             my $maxtries = 1;
                   1410:             my $tries = 1;
                   1411:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1412:                 $reply = &get_query_reply($queryid);
                   1413:                 $tries ++;
                   1414:             }
                   1415:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1416:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1417:             } else {
1.911     raeburn  1418:                 my @matches;
                   1419:                 if ($reply =~ /\n/) {
                   1420:                     @matches = split(/\n/,$reply);
                   1421:                 } else {
                   1422:                     @matches = split(/\&/,$reply);
                   1423:                 }
1.899     raeburn  1424:                 foreach my $match (@matches) {
                   1425:                     my ($uname,$udom,%userhash);
1.911     raeburn  1426:                     foreach my $entry (split(/:/,$match)) {
                   1427:                         my ($key,$value) =
                   1428:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1429:                         $userhash{$key} = $value;
                   1430:                         if ($key eq 'username') {
                   1431:                             $uname = $value;
                   1432:                         } elsif ($key eq 'domain') {
                   1433:                             $udom = $value;
1.911     raeburn  1434:                         }
1.899     raeburn  1435:                     }
                   1436:                     $results{$uname.':'.$udom} = \%userhash;
                   1437:                 }
                   1438:             }
                   1439:         }
                   1440:     }
                   1441:     return %results;
                   1442: }
                   1443: 
1.912     raeburn  1444: sub get_instuser {
                   1445:     my ($udom,$uname,$id) = @_;
                   1446:     my $homeserver = &domain($udom,'primary');
                   1447:     my ($outcome,%results);
                   1448:     if ($homeserver ne '') {
                   1449:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1450:                            &escape($id).':'.&escape($udom),$homeserver);
                   1451:         my $host=&hostname($homeserver);
                   1452:         if ($queryid !~/^\Q$host\E\_/) {
                   1453:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1454:             return;
                   1455:         }
                   1456:         my $response = &get_query_reply($queryid);
                   1457:         my $maxtries = 5;
                   1458:         my $tries = 1;
                   1459:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1460:             $response = &get_query_reply($queryid);
                   1461:             $tries ++;
                   1462:         }
                   1463:         if (!&error($response) && $response ne 'refused') {
                   1464:             if ($response eq 'unavailable') {
                   1465:                 $outcome = $response;
                   1466:             } else {
                   1467:                 $outcome = 'ok';
                   1468:                 my @matches = split(/\n/,$response);
                   1469:                 foreach my $match (@matches) {
                   1470:                     my ($key,$value) = split(/=/,$match);
                   1471:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1472:                 }
                   1473:             }
                   1474:         }
                   1475:     }
                   1476:     my %userinfo;
                   1477:     if (ref($results{$uname}) eq 'HASH') {
                   1478:         %userinfo = %{$results{$uname}};
                   1479:     } 
                   1480:     return ($outcome,%userinfo);
                   1481: }
                   1482: 
                   1483: sub inst_rulecheck {
1.923     raeburn  1484:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1485:     my %returnhash;
                   1486:     if ($udom ne '') {
                   1487:         if (ref($rules) eq 'ARRAY') {
                   1488:             @{$rules} = map {&escape($_);} (@{$rules});
                   1489:             my $rulestr = join(':',@{$rules});
                   1490:             my $homeserver=&domain($udom,'primary');
                   1491:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1492:                 my $response;
                   1493:                 if ($item eq 'username') {                
                   1494:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1495:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1496:                                               $homeserver));
1.923     raeburn  1497:                 } elsif ($item eq 'id') {
                   1498:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1499:                                               ':'.&escape($id).':'.$rulestr,
                   1500:                                               $homeserver));
1.945     raeburn  1501:                 } elsif ($item eq 'selfcreate') {
                   1502:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1503:                                                &escape($udom).':'.&escape($uname).
                   1504:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1505:                 }
1.912     raeburn  1506:                 if ($response ne 'refused') {
                   1507:                     my @pairs=split(/\&/,$response);
                   1508:                     foreach my $item (@pairs) {
                   1509:                         my ($key,$value)=split(/=/,$item,2);
                   1510:                         $key = &unescape($key);
                   1511:                         next if ($key =~ /^error: 2 /);
                   1512:                         $returnhash{$key}=&thaw_unescape($value);
                   1513:                     }
                   1514:                 }
                   1515:             }
                   1516:         }
                   1517:     }
                   1518:     return %returnhash;
                   1519: }
                   1520: 
                   1521: sub inst_userrules {
1.923     raeburn  1522:     my ($udom,$check) = @_;
1.912     raeburn  1523:     my (%ruleshash,@ruleorder);
                   1524:     if ($udom ne '') {
                   1525:         my $homeserver=&domain($udom,'primary');
                   1526:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1527:             my $response;
                   1528:             if ($check eq 'id') {
                   1529:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1530:                                  $homeserver);
1.943     raeburn  1531:             } elsif ($check eq 'email') {
                   1532:                 $response=&reply('instemailrules:'.&escape($udom),
                   1533:                                  $homeserver);
1.923     raeburn  1534:             } else {
                   1535:                 $response=&reply('instuserrules:'.&escape($udom),
                   1536:                                  $homeserver);
                   1537:             }
1.912     raeburn  1538:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1539:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1540:                 ($response ne 'no_such_host')) {
                   1541:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1542:                 my @pairs=split(/\&/,$hashitems);
                   1543:                 foreach my $item (@pairs) {
                   1544:                     my ($key,$value)=split(/=/,$item,2);
                   1545:                     $key = &unescape($key);
                   1546:                     next if ($key =~ /^error: 2 /);
                   1547:                     $ruleshash{$key}=&thaw_unescape($value);
                   1548:                 }
                   1549:                 my @esc_order = split(/\&/,$orderitems);
                   1550:                 foreach my $item (@esc_order) {
                   1551:                     push(@ruleorder,&unescape($item));
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return (\%ruleshash,\@ruleorder);
                   1557: }
                   1558: 
1.976     raeburn  1559: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1560: 
                   1561: sub get_domain_defaults {
                   1562:     my ($domain) = @_;
                   1563:     my $cachetime = 60*60*24;
                   1564:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1565:     if (defined($cached)) {
                   1566:         if (ref($result) eq 'HASH') {
                   1567:             return %{$result};
                   1568:         }
                   1569:     }
                   1570:     my %domdefaults;
                   1571:     my %domconfig =
1.989     raeburn  1572:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1573:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1574:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1575:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1576:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1577:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1578:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1579:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1580:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1056.4.33.2  1(raebur 1581:2):         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1582:     } else {
                   1583:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1584:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1585:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1586:     }
1.976     raeburn  1587:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1588:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1589:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1590:         } else {
                   1591:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1592:         } 
                   1593:         my @usertools = ('aboutme','blog','portfolio');
                   1594:         foreach my $item (@usertools) {
                   1595:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1596:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1597:             }
                   1598:         }
                   1599:     }
1.985     raeburn  1600:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1601:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1602:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1603:         }
                   1604:     }
1.989     raeburn  1605:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1606:         foreach my $item ('inststatustypes','inststatusorder') {
                   1607:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1608:         }
                   1609:     }
1.1047    raeburn  1610:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1611:         foreach my $item ('canuse_pdfforms') {
                   1612:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1613:         }
                   1614:     }
1.1056.4.3  raeburn  1615:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1616:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1617:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1618:         }
                   1619:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1620:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1621:         }
                   1622:     }
1.943     raeburn  1623:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1624:                                   $cachetime);
                   1625:     return %domdefaults;
                   1626: }
                   1627: 
1.344     www      1628: # --------------------------------------------------- Assign a key to a student
                   1629: 
                   1630: sub assign_access_key {
1.364     www      1631: #
                   1632: # a valid key looks like uname:udom#comments
                   1633: # comments are being appended
                   1634: #
1.498     www      1635:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1636:     $kdom=
1.620     albertel 1637:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1638:     $knum=
1.620     albertel 1639:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1640:     $cdom=
1.620     albertel 1641:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1642:     $cnum=
1.620     albertel 1643:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1644:     $udom=$env{'user.name'} unless (defined($udom));
                   1645:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1646:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1647:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1648:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1649:                                                   # assigned to this person
                   1650:                                                   # - this should not happen,
1.345     www      1651:                                                   # unless something went wrong
                   1652:                                                   # the first time around
                   1653: # ready to assign
1.364     www      1654:         $logentry=$1.'; '.$logentry;
1.496     www      1655:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1656:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1657: # key now belongs to user
1.346     www      1658: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1659:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1660:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1661:                 return 'ok';
                   1662:             } else {
                   1663:                 return 
                   1664:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1665: 	    }
                   1666:         } else {
                   1667:             return 'error: Could not assign key, try again later.';
                   1668:         }
1.364     www      1669:     } elsif (!$existing{$ckey}) {
1.345     www      1670: # the key does not exist
                   1671: 	return 'error: The key does not exist';
                   1672:     } else {
                   1673: # the key is somebody else's
                   1674: 	return 'error: The key is already in use';
                   1675:     }
1.344     www      1676: }
                   1677: 
1.364     www      1678: # ------------------------------------------ put an additional comment on a key
                   1679: 
                   1680: sub comment_access_key {
                   1681: #
                   1682: # a valid key looks like uname:udom#comments
                   1683: # comments are being appended
                   1684: #
                   1685:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1686:     $cdom=
1.620     albertel 1687:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1688:     $cnum=
1.620     albertel 1689:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1690:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1691:     if ($existing{$ckey}) {
                   1692:         $existing{$ckey}.='; '.$logentry;
                   1693: # ready to assign
1.367     www      1694:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1695:                                                  $cdom,$cnum) eq 'ok') {
                   1696: 	    return 'ok';
                   1697:         } else {
                   1698: 	    return 'error: Count not store comment.';
                   1699:         }
                   1700:     } else {
                   1701: # the key does not exist
                   1702: 	return 'error: The key does not exist';
                   1703:     }
                   1704: }
                   1705: 
1.344     www      1706: # ------------------------------------------------------ Generate a set of keys
                   1707: 
                   1708: sub generate_access_keys {
1.364     www      1709:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1710:     $cdom=
1.620     albertel 1711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1712:     $cnum=
1.620     albertel 1713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1714:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1715:     unless (($cdom) && ($cnum)) { return 0; }
                   1716:     if ($number>10000) { return 0; }
                   1717:     sleep(2); # make sure don't get same seed twice
                   1718:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1719:     my $total=0;
                   1720:     for (my $i=1;$i<=$number;$i++) {
                   1721:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1722:                   sprintf("%lx",int(100000*rand)).'-'.
                   1723:                   sprintf("%lx",int(100000*rand));
                   1724:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1725:        $newkey=~s/0/h/g; # and also 0 and O
                   1726:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1727:        if ($existing{$newkey}) {
                   1728:            $i--;
                   1729:        } else {
1.364     www      1730: 	  if (&put('accesskeys',
                   1731:               { $newkey => '# generated '.localtime().
1.620     albertel 1732:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1733:                            '; '.$logentry },
                   1734: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1735:               $total++;
                   1736: 	  }
                   1737:        }
                   1738:     }
1.620     albertel 1739:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1740:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1741:     return $total;
                   1742: }
                   1743: 
                   1744: # ------------------------------------------------------- Validate an accesskey
                   1745: 
                   1746: sub validate_access_key {
                   1747:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1748:     $cdom=
1.620     albertel 1749:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1750:     $cnum=
1.620     albertel 1751:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1752:     $udom=$env{'user.domain'} unless (defined($udom));
                   1753:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1754:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1755:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1756: }
                   1757: 
                   1758: # ------------------------------------- Find the section of student in a course
1.652     albertel 1759: sub devalidate_getsection_cache {
                   1760:     my ($udom,$unam,$courseid)=@_;
                   1761:     my $hashid="$udom:$unam:$courseid";
                   1762:     &devalidate_cache_new('getsection',$hashid);
                   1763: }
1.298     matthew  1764: 
1.815     albertel 1765: sub courseid_to_courseurl {
                   1766:     my ($courseid) = @_;
                   1767:     #already url style courseid
                   1768:     return $courseid if ($courseid =~ m{^/});
                   1769: 
                   1770:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1771: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1772: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1773: 	return "/$cdom/$cnum";
                   1774:     }
                   1775: 
                   1776:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1777:     if (exists($courseinfo{'num'})) {
                   1778: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1779:     }
                   1780: 
                   1781:     return undef;
                   1782: }
                   1783: 
1.298     matthew  1784: sub getsection {
                   1785:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1786:     my $cachetime=1800;
1.551     albertel 1787: 
                   1788:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1789:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1790:     if (defined($cached)) { return $result; }
                   1791: 
1.298     matthew  1792:     my %Pending; 
                   1793:     my %Expired;
                   1794:     #
                   1795:     # Each role can either have not started yet (pending), be active, 
                   1796:     #    or have expired.
                   1797:     #
                   1798:     # If there is an active role, we are done.
                   1799:     #
                   1800:     # If there is more than one role which has not started yet, 
                   1801:     #     choose the one which will start sooner
                   1802:     # If there is one role which has not started yet, return it.
                   1803:     #
                   1804:     # If there is more than one expired role, choose the one which ended last.
                   1805:     # If there is a role which has expired, return it.
                   1806:     #
1.815     albertel 1807:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  1808:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1809:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1810:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1811:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1812:         my $section=$1;
                   1813:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1814:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1815:         my $now=time;
1.548     albertel 1816:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1817:             $Expired{$end}=$section;
                   1818:             next;
                   1819:         }
1.548     albertel 1820:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1821:             $Pending{$start}=$section;
                   1822:             next;
                   1823:         }
1.599     albertel 1824:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1825:     }
                   1826:     #
                   1827:     # Presumedly there will be few matching roles from the above
                   1828:     # loop and the sorting time will be negligible.
                   1829:     if (scalar(keys(%Pending))) {
                   1830:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1831:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1832:     } 
                   1833:     if (scalar(keys(%Expired))) {
                   1834:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1835:         my $time = pop(@sorted);
1.599     albertel 1836:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1837:     }
1.599     albertel 1838:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1839: }
1.70      www      1840: 
1.599     albertel 1841: sub save_cache {
                   1842:     &purge_remembered();
1.722     albertel 1843:     #&Apache::loncommon::validate_page();
1.620     albertel 1844:     undef(%env);
1.780     albertel 1845:     undef($env_loaded);
1.599     albertel 1846: }
1.452     albertel 1847: 
1.599     albertel 1848: my $to_remember=-1;
                   1849: my %remembered;
                   1850: my %accessed;
                   1851: my $kicks=0;
                   1852: my $hits=0;
1.849     albertel 1853: sub make_key {
                   1854:     my ($name,$id) = @_;
1.872     albertel 1855:     if (length($id) > 65 
                   1856: 	&& length(&escape($id)) > 200) {
                   1857: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1858:     }
1.849     albertel 1859:     return &escape($name.':'.$id);
                   1860: }
                   1861: 
1.599     albertel 1862: sub devalidate_cache_new {
                   1863:     my ($name,$id,$debug) = @_;
                   1864:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1865:     $id=&make_key($name,$id);
1.599     albertel 1866:     $memcache->delete($id);
                   1867:     delete($remembered{$id});
                   1868:     delete($accessed{$id});
                   1869: }
                   1870: 
                   1871: sub is_cached_new {
                   1872:     my ($name,$id,$debug) = @_;
1.849     albertel 1873:     $id=&make_key($name,$id);
1.599     albertel 1874:     if (exists($remembered{$id})) {
                   1875: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1876: 	$accessed{$id}=[&gettimeofday()];
                   1877: 	$hits++;
                   1878: 	return ($remembered{$id},1);
                   1879:     }
                   1880:     my $value = $memcache->get($id);
                   1881:     if (!(defined($value))) {
                   1882: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1883: 	return (undef,undef);
1.416     albertel 1884:     }
1.599     albertel 1885:     if ($value eq '__undef__') {
                   1886: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1887: 	$value=undef;
                   1888:     }
                   1889:     &make_room($id,$value,$debug);
                   1890:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1891:     return ($value,1);
                   1892: }
                   1893: 
                   1894: sub do_cache_new {
                   1895:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1896:     $id=&make_key($name,$id);
1.599     albertel 1897:     my $setvalue=$value;
                   1898:     if (!defined($setvalue)) {
                   1899: 	$setvalue='__undef__';
                   1900:     }
1.623     albertel 1901:     if (!defined($time) ) {
                   1902: 	$time=600;
                   1903:     }
1.599     albertel 1904:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1905:     my $result = $memcache->set($id,$setvalue,$time);
                   1906:     if (! $result) {
1.872     albertel 1907: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1908: 	$memcache->disconnect_all();
1.872     albertel 1909:     }
1.600     albertel 1910:     # need to make a copy of $value
1.919     albertel 1911:     &make_room($id,$value,$debug);
1.599     albertel 1912:     return $value;
                   1913: }
                   1914: 
                   1915: sub make_room {
                   1916:     my ($id,$value,$debug)=@_;
1.919     albertel 1917: 
                   1918:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1919:                                     : $value;
1.599     albertel 1920:     if ($to_remember<0) { return; }
                   1921:     $accessed{$id}=[&gettimeofday()];
                   1922:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1923:     my $to_kick;
                   1924:     my $max_time=0;
                   1925:     foreach my $other (keys(%accessed)) {
                   1926: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1927: 	    $to_kick=$other;
                   1928: 	    $max_time=&tv_interval($accessed{$other});
                   1929: 	}
                   1930:     }
                   1931:     delete($remembered{$to_kick});
                   1932:     delete($accessed{$to_kick});
                   1933:     $kicks++;
                   1934:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1935:     return;
                   1936: }
                   1937: 
1.599     albertel 1938: sub purge_remembered {
1.604     albertel 1939:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1940:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1941:     undef(%remembered);
                   1942:     undef(%accessed);
1.428     albertel 1943: }
1.70      www      1944: # ------------------------------------- Read an entry from a user's environment
                   1945: 
                   1946: sub userenvironment {
                   1947:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1948:     my $items;
                   1949:     foreach my $item (@what) {
                   1950:         $items.=&escape($item).'&';
                   1951:     }
                   1952:     $items=~s/\&$//;
1.70      www      1953:     my %returnhash=();
1.1009    raeburn  1954:     my $uhome = &homeserver($unam,$udom);
                   1955:     unless ($uhome eq 'no_host') {
                   1956:         my @answer=split(/\&/, 
                   1957:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1958:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1959:             return %returnhash;
                   1960:         }
1.1009    raeburn  1961:         my $i;
                   1962:         for ($i=0;$i<=$#what;$i++) {
                   1963: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1964:         }
1.70      www      1965:     }
                   1966:     return %returnhash;
1.1       albertel 1967: }
                   1968: 
1.617     albertel 1969: # ---------------------------------------------------------- Get a studentphoto
                   1970: sub studentphoto {
                   1971:     my ($udom,$unam,$ext) = @_;
                   1972:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1973:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1974:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1975:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1976:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1977:             } else {
                   1978:                 my ($result,$perm_reqd)=
1.707     albertel 1979: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1980:                 if ($result eq 'ok') {
                   1981:                     if (!($perm_reqd eq 'yes')) {
                   1982:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1983:                     }
                   1984:                 }
                   1985:             }
                   1986:         }
                   1987:     } else {
                   1988:         my ($result,$perm_reqd) = 
1.707     albertel 1989: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1990:         if ($result eq 'ok') {
                   1991:             if (!($perm_reqd eq 'yes')) {
                   1992:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1993:             }
                   1994:         }
                   1995:     }
                   1996:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1997: }
                   1998: 
                   1999: sub retrievestudentphoto {
                   2000:     my ($udom,$unam,$ext,$type) = @_;
                   2001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2002:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2003:     if ($ret eq 'ok') {
                   2004:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2005:         if ($type eq 'thumbnail') {
                   2006:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2007:         }
                   2008:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2009:         return $tokenurl;
                   2010:     } else {
                   2011:         if ($type eq 'thumbnail') {
                   2012:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2013:         } else { 
                   2014:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2015:         }
1.617     albertel 2016:     }
                   2017: }
                   2018: 
1.263     www      2019: # -------------------------------------------------------------------- New chat
                   2020: 
                   2021: sub chatsend {
1.724     raeburn  2022:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2023:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2025:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2026:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2027: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2028: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2029: }
                   2030: 
                   2031: # ------------------------------------------ Find current version of a resource
                   2032: 
                   2033: sub getversion {
                   2034:     my $fname=&clutter(shift);
                   2035:     unless ($fname=~/^\/res\//) { return -1; }
                   2036:     return &currentversion(&filelocation('',$fname));
                   2037: }
                   2038: 
                   2039: sub currentversion {
                   2040:     my $fname=shift;
1.599     albertel 2041:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      2042:     if (defined($cached)) { return $result; }
1.292     www      2043:     my $author=$fname;
                   2044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2045:     my ($udom,$uname)=split(/\//,$author);
                   2046:     my $home=homeserver($uname,$udom);
                   2047:     if ($home eq 'no_host') { 
                   2048:         return -1; 
                   2049:     }
                   2050:     my $answer=reply("currentversion:$fname",$home);
                   2051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2052: 	return -1;
                   2053:     }
1.599     albertel 2054:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2055: }
                   2056: 
1.1       albertel 2057: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2058: 
1.1       albertel 2059: sub subscribe {
                   2060:     my $fname=shift;
1.761     raeburn  2061:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2062:     $fname=~s/[\n\r]//g;
1.1       albertel 2063:     my $author=$fname;
                   2064:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2065:     my ($udom,$uname)=split(/\//,$author);
                   2066:     my $home=homeserver($uname,$udom);
1.335     albertel 2067:     if ($home eq 'no_host') {
                   2068:         return 'not_found';
1.1       albertel 2069:     }
                   2070:     my $answer=reply("sub:$fname",$home);
1.64      www      2071:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2072: 	$answer.=' by '.$home;
                   2073:     }
1.1       albertel 2074:     return $answer;
                   2075: }
                   2076:     
1.8       www      2077: # -------------------------------------------------------------- Replicate file
                   2078: 
                   2079: sub repcopy {
                   2080:     my $filename=shift;
1.23      www      2081:     $filename=~s/\/+/\//g;
1.607     raeburn  2082:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2083:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2084:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2085: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2086: 	return &repcopy_userfile($filename);
                   2087:     }
1.532     albertel 2088:     $filename=~s/[\n\r]//g;
1.8       www      2089:     my $transname="$filename.in.transfer";
1.828     www      2090: # FIXME: this should flock
1.607     raeburn  2091:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2092:     my $remoteurl=subscribe($filename);
1.64      www      2093:     if ($remoteurl =~ /^con_lost by/) {
                   2094: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2095:            return 'unavailable';
1.8       www      2096:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2097: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2098: 	   return 'not_found';
1.64      www      2099:     } elsif ($remoteurl =~ /^rejected by/) {
                   2100: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2101:            return 'forbidden';
1.20      www      2102:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2103:            return 'ok';
1.8       www      2104:     } else {
1.290     www      2105:         my $author=$filename;
                   2106:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2107:         my ($udom,$uname)=split(/\//,$author);
                   2108:         my $home=homeserver($uname,$udom);
                   2109:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2110:            my @parts=split(/\//,$filename);
                   2111:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2112:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2113:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2114: 	       return 'bad_request';
1.8       www      2115:            }
                   2116:            my $count;
                   2117:            for ($count=5;$count<$#parts;$count++) {
                   2118:                $path.="/$parts[$count]";
                   2119:                if ((-e $path)!=1) {
                   2120: 		   mkdir($path,0777);
                   2121:                }
                   2122:            }
                   2123:            my $ua=new LWP::UserAgent;
                   2124:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2125:            my $response=$ua->request($request,$transname);
                   2126:            if ($response->is_error()) {
                   2127: 	       unlink($transname);
                   2128:                my $message=$response->status_line;
1.672     albertel 2129:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2130:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2131:                return 'unavailable';
1.8       www      2132:            } else {
1.16      www      2133: 	       if ($remoteurl!~/\.meta$/) {
                   2134:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2135:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2136:                   if ($mresponse->is_error()) {
                   2137: 		      unlink($filename.'.meta');
                   2138:                       &logthis(
1.672     albertel 2139:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2140:                   }
                   2141: 	       }
1.8       www      2142:                rename($transname,$filename);
1.607     raeburn  2143:                return 'ok';
1.8       www      2144:            }
1.290     www      2145:        }
1.8       www      2146:     }
1.330     www      2147: }
                   2148: 
                   2149: # ------------------------------------------------ Get server side include body
                   2150: sub ssi_body {
1.381     albertel 2151:     my ($filelink,%form)=@_;
1.606     matthew  2152:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2153:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2154:     }
1.953     www      2155:     my $output='';
                   2156:     my $response;
1.980     raeburn  2157:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2158:        ($output,$response)=&externalssi($filelink);
1.953     www      2159:     } else {
1.1004    droeschl 2160:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2161:        $filelink .= 'inhibitmenu=yes';
1.953     www      2162:        ($output,$response)=&ssi($filelink,%form);
                   2163:     }
1.778     albertel 2164:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2165:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2166:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2167:     if (wantarray) {
                   2168:         return ($output, $response);
                   2169:     } else {
                   2170:         return $output;
                   2171:     }
1.8       www      2172: }
                   2173: 
1.15      www      2174: # --------------------------------------------------------- Server Side Include
                   2175: 
1.782     albertel 2176: sub absolute_url {
                   2177:     my ($host_name) = @_;
                   2178:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2179:     if ($host_name eq '') {
                   2180: 	$host_name = $ENV{'SERVER_NAME'};
                   2181:     }
                   2182:     return $protocol.$host_name;
                   2183: }
                   2184: 
1.942     foxr     2185: #
                   2186: #   Server side include.
                   2187: # Parameters:
                   2188: #  fn     Possibly encrypted resource name/id.
                   2189: #  form   Hash that describes how the rendering should be done
                   2190: #         and other things.
1.944     foxr     2191: # Returns:
1.950     raeburn  2192: #   Scalar context: The content of the response.
                   2193: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2194: #     
1.15      www      2195: sub ssi {
                   2196: 
1.944     foxr     2197:     my ($fn,%form)=@_;
1.15      www      2198:     my $ua=new LWP::UserAgent;
1.23      www      2199:     my $request;
1.711     albertel 2200: 
                   2201:     $form{'no_update_last_known'}=1;
1.895     albertel 2202:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2203:     if (%form) {
1.782     albertel 2204:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2205:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2206:     } else {
1.782     albertel 2207:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2208:     }
                   2209: 
1.15      www      2210:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2211:     my $response=$ua->request($request);
                   2212: 
1.944     foxr     2213:     if (wantarray) {
                   2214: 	return ($response->content, $response);
                   2215:     } else {
                   2216: 	return $response->content;
1.942     foxr     2217:     }
1.324     www      2218: }
                   2219: 
                   2220: sub externalssi {
                   2221:     my ($url)=@_;
                   2222:     my $ua=new LWP::UserAgent;
                   2223:     my $request=new HTTP::Request('GET',$url);
                   2224:     my $response=$ua->request($request);
1.954     raeburn  2225:     if (wantarray) {
                   2226:         return ($response->content, $response);
                   2227:     } else {
                   2228:         return $response->content;
                   2229:     }
1.15      www      2230: }
1.254     www      2231: 
1.492     albertel 2232: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2233: 
                   2234: sub allowuploaded {
                   2235:     my ($srcurl,$url)=@_;
                   2236:     $url=&clutter(&declutter($url));
                   2237:     my $dir=$url;
                   2238:     $dir=~s/\/[^\/]+$//;
                   2239:     my %httpref=();
                   2240:     my $httpurl=&hreflocation('',$url);
                   2241:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2242:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2243: }
1.477     raeburn  2244: 
1.478     albertel 2245: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2246: # input: action, courseID, current domain, intended
1.637     raeburn  2247: #        path to file, source of file, instruction to parse file for objects,
                   2248: #        ref to hash for embedded objects,
                   2249: #        ref to hash for codebase of java objects.
1.1056.4.16  raeburn  2250: #        reference to scalar to accommodate mime type determined
                   2251: #          from File::MMagic if $parser = parse.
1.637     raeburn  2252: #
1.485     raeburn  2253: # output: url to file (if action was uploaddoc), 
                   2254: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2255: #
1.478     albertel 2256: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2257: # course.
1.477     raeburn  2258: #
1.478     albertel 2259: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2260: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2261: #          course's home server.
1.477     raeburn  2262: #
1.478     albertel 2263: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2264: #          be copied from $source (current location) to 
                   2265: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2266: #         and will then be copied to
                   2267: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2268: #         course's home server.
1.485     raeburn  2269: #
1.481     raeburn  2270: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2271: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2272: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2273: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2274: #         in course's home server.
1.637     raeburn  2275: #
1.477     raeburn  2276: 
                   2277: sub process_coursefile {
1.1056.4.16  raeburn  2278:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2279:         $mimetype)=@_;
1.477     raeburn  2280:     my $fetchresult;
1.638     albertel 2281:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2282:     if ($action eq 'propagate') {
1.638     albertel 2283:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2284: 			     $home);
1.481     raeburn  2285:     } else {
1.477     raeburn  2286:         my $fpath = '';
                   2287:         my $fname = $file;
1.478     albertel 2288:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2289:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2290:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2291:         if ($action eq 'copy') {
                   2292:             if ($source eq '') {
                   2293:                 $fetchresult = 'no source file';
                   2294:                 return $fetchresult;
                   2295:             } else {
                   2296:                 my $destination = $filepath.'/'.$fname;
                   2297:                 rename($source,$destination);
                   2298:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2299:                                  $home);
1.481     raeburn  2300:             }
                   2301:         } elsif ($action eq 'uploaddoc') {
                   2302:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2303:             print $fh $env{'form.'.$source};
1.481     raeburn  2304:             close($fh);
1.637     raeburn  2305:             if ($parser eq 'parse') {
1.1024    raeburn  2306:                 my $mm = new File::MMagic;
1.1056.4.16  raeburn  2307:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2308:                 if ($type eq 'text/html') {
1.1024    raeburn  2309:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2310:                     unless ($parse_result eq 'ok') {
                   2311:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2312:                     }
1.637     raeburn  2313:                 }
1.1056.4.16  raeburn  2314:                 if (ref($mimetype)) {
                   2315:                     $$mimetype = $type;
                   2316:                 }
1.637     raeburn  2317:             }
1.477     raeburn  2318:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2319:                                  $home);
1.481     raeburn  2320:             if ($fetchresult eq 'ok') {
                   2321:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2322:             } else {
                   2323:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2324:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2325:                 return '/adm/notfound.html';
                   2326:             }
1.477     raeburn  2327:         }
                   2328:     }
1.485     raeburn  2329:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2330:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2331:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2332:     }
                   2333:     return $fetchresult;
                   2334: }
                   2335: 
1.637     raeburn  2336: sub build_filepath {
                   2337:     my ($fpath) = @_;
                   2338:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2339:     unless ($fpath eq '') {
                   2340:         my @parts=split('/',$fpath);
                   2341:         foreach my $part (@parts) {
                   2342:             $filepath.= '/'.$part;
                   2343:             if ((-e $filepath)!=1) {
                   2344:                 mkdir($filepath,0777);
                   2345:             }
                   2346:         }
                   2347:     }
                   2348:     return $filepath;
                   2349: }
                   2350: 
                   2351: sub store_edited_file {
1.638     albertel 2352:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2353:     my $file = $primary_url;
                   2354:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2355:     my $fpath = '';
                   2356:     my $fname = $file;
                   2357:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2358:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2359:     my $filepath = &build_filepath($fpath);
                   2360:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2361:     print $fh $content;
                   2362:     close($fh);
1.638     albertel 2363:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2364:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2365: 			  $home);
1.637     raeburn  2366:     if ($$fetchresult eq 'ok') {
                   2367:         return '/uploaded/'.$fpath.'/'.$fname;
                   2368:     } else {
1.638     albertel 2369:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2370: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2371:         return '/adm/notfound.html';
                   2372:     }
                   2373: }
                   2374: 
1.531     albertel 2375: sub clean_filename {
1.831     albertel 2376:     my ($fname,$args)=@_;
1.315     www      2377: # Replace Windows backslashes by forward slashes
1.257     www      2378:     $fname=~s/\\/\//g;
1.831     albertel 2379:     if (!$args->{'keep_path'}) {
                   2380:         # Get rid of everything but the actual filename
                   2381: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2382:     }
1.315     www      2383: # Replace spaces by underscores
                   2384:     $fname=~s/\s+/\_/g;
                   2385: # Replace all other weird characters by nothing
1.831     albertel 2386:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2387: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2388: # numbers
                   2389:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2390:     return $fname;
                   2391: }
1.1051    raeburn  2392: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2393: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2394: # image with the same aspect ratio as the original, but with dimensions which do 
                   2395: # not exceed $resizewidth and $resizeheight.
                   2396:  
1.984     neumanie 2397: sub resizeImage {
1.1051    raeburn  2398:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2399:     my $ima = Image::Magick->new;
                   2400:     my $resized;
                   2401:     if (-e $img_path) {
                   2402:         $ima->Read($img_path);
                   2403:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2404:             my $width = $ima->Get('width');
                   2405:             my $height = $ima->Get('height');
                   2406:             if ($width > $resizewidth) {
                   2407: 	        my $factor = $width/$resizewidth;
                   2408:                 my $newheight = $height/$factor;
                   2409:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2410:                 $resized = 1;
                   2411:             }
                   2412:         }
                   2413:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2414:             my $width = $ima->Get('width');
                   2415:             my $height = $ima->Get('height');
                   2416:             if ($height > $resizeheight) {
                   2417:                 my $factor = $height/$resizeheight;
                   2418:                 my $newwidth = $width/$factor;
                   2419:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2420:                 $resized = 1;
                   2421:             }
                   2422:         }
                   2423:         if ($resized) {
                   2424:             $ima->Write($img_path);
                   2425:         }
                   2426:     }
                   2427:     return;
1.977     amueller 2428: }
                   2429: 
1.608     albertel 2430: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2431: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2432: #                    the desired filename is in $env{"form.$formname.filename"}
                   2433: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2434: #                                    canceloverwrite, or ''.
                   2435: #                   if 'coursedoc': upload to the current course
                   2436: #                   if 'existingfile': write file to tmp/overwrites directory
                   2437: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2438: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2439: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2440: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2441: #        $allfiles - reference to hash for embedded objects
                   2442: #        $codebase - reference to hash for codebase of java objects
                   2443: #        $desuname - username for permanent storage of uploaded file
                   2444: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2445: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2446: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2447: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2448: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16  raeburn  2449: #        $mimetype - reference to scalar to accommodate mime type determined
                   2450: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2451: # 
1.686     albertel 2452: # output: url of file in userspace, or error: <message> 
                   2453: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2454: 
1.531     albertel 2455: sub userfileupload {
1.1056.4.13  raeburn  2456:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16  raeburn  2457:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2458:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2459:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2460:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2461:     # See if there is anything left
1.257     www      2462:     unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13  raeburn  2463:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2464:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2465:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2466:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2467:         my $now = time;
1.1056.4.13  raeburn  2468:         my $filepath;
                   2469:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2470:              $filepath = 'tmp/helprequests/'.$now;
                   2471:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2472:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2473:                          '_'.$env{'user.domain'}.'/pending';
                   2474:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2475:             my ($docuname,$docudom);
                   2476:             if ($destudom) {
                   2477:                 $docudom = $destudom;
                   2478:             } else {
                   2479:                 $docudom = $env{'user.domain'};
                   2480:             }
                   2481:             if ($destuname) {
                   2482:                 $docuname = $destuname;
                   2483:             } else {
                   2484:                 $docuname = $env{'user.name'};
                   2485:             }
                   2486:             if (exists($env{'form.group'})) {
                   2487:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2488:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2489:             }
                   2490:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2491:             if ($context eq 'canceloverwrite') {
                   2492:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2493:                 if (-e  $tempfile) {
                   2494:                     my @info = stat($tempfile);
                   2495:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2496:                         unlink($tempfile);
                   2497:                     }
                   2498:                 }
                   2499:                 return;
1.523     raeburn  2500:             }
                   2501:         }
1.1056.4.13  raeburn  2502:         # Create the directory if not present
1.741     raeburn  2503:         my @parts=split(/\//,$filepath);
                   2504:         my $fullpath = $perlvar{'lonDaemons'};
                   2505:         for (my $i=0;$i<@parts;$i++) {
                   2506:             $fullpath .= '/'.$parts[$i];
                   2507:             if ((-e $fullpath)!=1) {
                   2508:                 mkdir($fullpath,0777);
                   2509:             }
                   2510:         }
                   2511:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2512:         print $fh $env{'form.'.$formname};
                   2513:         close($fh);
1.1056.4.13  raeburn  2514:         if ($context eq 'existingfile') {
                   2515:             my @info = stat($fullpath.'/'.$fname);
                   2516:             return ($fullpath.'/'.$fname,$info[9]);
                   2517:         } else {
                   2518:             return $fullpath.'/'.$fname;
                   2519:         }
1.523     raeburn  2520:     }
1.995     raeburn  2521:     if ($subdir eq 'scantron') {
                   2522:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14  raeburn  2523:     } else {
1.995     raeburn  2524:         $fname="$subdir/$fname";
                   2525:     }
1.1056.4.13  raeburn  2526:     if ($context eq 'coursedoc') {
1.638     albertel 2527: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2528: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2529:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2530:             return &finishuserfileupload($docuname,$docudom,
                   2531: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2532: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2533:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2534:         } else {
1.620     albertel 2535:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2536:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2537: 				       $fname,$formname,$parser,
1.1056.4.16  raeburn  2538: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2539:         }
1.719     banghart 2540:     } elsif (defined($destuname)) {
                   2541:         my $docuname=$destuname;
                   2542:         my $docudom=$destudom;
1.860     raeburn  2543: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2544: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2545:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2546:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2547:     } else {
1.638     albertel 2548:         my $docuname=$env{'user.name'};
                   2549:         my $docudom=$env{'user.domain'};
1.714     raeburn  2550:         if (exists($env{'form.group'})) {
                   2551:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2552:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2553:         }
1.860     raeburn  2554: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2555: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2556:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2557:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2558:     }
1.271     www      2559: }
                   2560: 
                   2561: sub finishuserfileupload {
1.860     raeburn  2562:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16  raeburn  2563:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2564:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2565:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2566:   
1.860     raeburn  2567:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2568:     $file=$fname;
                   2569:     if ($fname=~m|/|) {
                   2570:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2571: 	$path.=$fnamepath.'/';
                   2572:     }
1.259     www      2573:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2574:     my $count;
                   2575:     for ($count=4;$count<=$#parts;$count++) {
                   2576:         $filepath.="/$parts[$count]";
                   2577:         if ((-e $filepath)!=1) {
                   2578: 	    mkdir($filepath,0777);
                   2579:         }
                   2580:     }
1.984     neumanie 2581: 
1.258     www      2582: # Save the file
                   2583:     {
1.701     albertel 2584: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2585: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2586: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2587: 	    return '/adm/notfound.html';
                   2588: 	}
1.1056.4.13  raeburn  2589:         if ($context eq 'overwrite') {
                   2590:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2591:             my $target = $filepath.'/'.$file;
                   2592:             if (-e $source) {
                   2593:                 my @info = stat($source);
                   2594:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2595:                     unless (&File::Copy::move($source,$target)) {
                   2596:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2597:                         return "Moving from $source failed";
                   2598:                     }
                   2599:                 } else {
                   2600:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2601:                 }
                   2602:             } else {
                   2603:                 return "Temporary file: $source missing";
                   2604:             }
                   2605: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2606: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2607: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2608: 	    return '/adm/notfound.html';
                   2609: 	}
1.570     albertel 2610: 	close(FH);
1.1051    raeburn  2611:         if ($resizewidth && $resizeheight) {
                   2612:             my $mm = new File::MMagic;
                   2613:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2614:             if ($mime_type =~ m{^image/}) {
                   2615: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2616:             }  
1.977     amueller 2617: 	}
1.258     www      2618:     }
1.637     raeburn  2619:     if ($parser eq 'parse') {
1.1024    raeburn  2620:         my $mm = new File::MMagic;
1.1056.4.16  raeburn  2621:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2622:         if ($type eq 'text/html') {
1.1024    raeburn  2623:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2624:                                                        $allfiles,$codebase);
                   2625:             unless ($parse_result eq 'ok') {
                   2626:                 &logthis('Failed to parse '.$filepath.$file.
                   2627: 	   	         ' for embedded media: '.$parse_result); 
                   2628:             }
1.637     raeburn  2629:         }
1.1056.4.16  raeburn  2630:         if (ref($mimetype)) {
                   2631:             $$mimetype = $type;
                   2632:         }
1.637     raeburn  2633:     }
1.860     raeburn  2634:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2635:         my $input = $filepath.'/'.$file;
                   2636:         my $output = $filepath.'/'.'tn-'.$file;
                   2637:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2638:         system("convert -sample $thumbsize $input $output");
                   2639:         if (-e $filepath.'/'.'tn-'.$file) {
                   2640:             $fetchthumb  = 1; 
                   2641:         }
                   2642:     }
1.858     raeburn  2643:  
1.259     www      2644: # Notify homeserver to grep it
                   2645: #
1.984     neumanie 2646:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2647:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2648:     if ($fetchresult eq 'ok') {
1.860     raeburn  2649:         if ($fetchthumb) {
                   2650:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2651:             if ($thumbresult ne 'ok') {
                   2652:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2653:                          $docuhome.': '.$thumbresult);
                   2654:             }
                   2655:         }
1.259     www      2656: #
1.258     www      2657: # Return the URL to it
1.494     albertel 2658:         return '/uploaded/'.$path.$file;
1.263     www      2659:     } else {
1.494     albertel 2660:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2661: 		 ': '.$fetchresult);
1.263     www      2662:         return '/adm/notfound.html';
1.858     raeburn  2663:     }
1.493     albertel 2664: }
                   2665: 
1.637     raeburn  2666: sub extract_embedded_items {
1.961     raeburn  2667:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2668:     my @state = ();
                   2669:     my %javafiles = (
                   2670:                       codebase => '',
                   2671:                       code => '',
                   2672:                       archive => ''
                   2673:                     );
                   2674:     my %mediafiles = (
                   2675:                       src => '',
                   2676:                       movie => '',
                   2677:                      );
1.648     raeburn  2678:     my $p;
                   2679:     if ($content) {
                   2680:         $p = HTML::LCParser->new($content);
                   2681:     } else {
1.961     raeburn  2682:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2683:     }
1.641     albertel 2684:     while (my $t=$p->get_token()) {
1.640     albertel 2685: 	if ($t->[0] eq 'S') {
                   2686: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2687: 	    push(@state, $tagname);
1.648     raeburn  2688:             if (lc($tagname) eq 'allow') {
                   2689:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2690:             }
1.640     albertel 2691: 	    if (lc($tagname) eq 'img') {
                   2692: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2693: 	    }
1.886     albertel 2694: 	    if (lc($tagname) eq 'a') {
                   2695: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2696: 	    }
1.645     raeburn  2697:             if (lc($tagname) eq 'script') {
                   2698:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2699:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2700:                 } else {
                   2701:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2702:                 }
                   2703:             }
                   2704:             if (lc($tagname) eq 'link') {
                   2705:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2706:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2707:                 }
                   2708:             }
1.640     albertel 2709: 	    if (lc($tagname) eq 'object' ||
                   2710: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2711: 		foreach my $item (keys(%javafiles)) {
                   2712: 		    $javafiles{$item} = '';
                   2713: 		}
                   2714: 	    }
                   2715: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2716: 		my $name = lc($attr->{'name'});
                   2717: 		foreach my $item (keys(%javafiles)) {
                   2718: 		    if ($name eq $item) {
                   2719: 			$javafiles{$item} = $attr->{'value'};
                   2720: 			last;
                   2721: 		    }
                   2722: 		}
                   2723: 		foreach my $item (keys(%mediafiles)) {
                   2724: 		    if ($name eq $item) {
                   2725: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2726: 			last;
                   2727: 		    }
                   2728: 		}
                   2729: 	    }
                   2730: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2731: 		foreach my $item (keys(%javafiles)) {
                   2732: 		    if ($attr->{$item}) {
                   2733: 			$javafiles{$item} = $attr->{$item};
                   2734: 			last;
                   2735: 		    }
                   2736: 		}
                   2737: 		foreach my $item (keys(%mediafiles)) {
                   2738: 		    if ($attr->{$item}) {
                   2739: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2740: 			last;
                   2741: 		    }
                   2742: 		}
                   2743: 	    }
                   2744: 	} elsif ($t->[0] eq 'E') {
                   2745: 	    my ($tagname) = ($t->[1]);
                   2746: 	    if ($javafiles{'codebase'} ne '') {
                   2747: 		$javafiles{'codebase'} .= '/';
                   2748: 	    }  
                   2749: 	    if (lc($tagname) eq 'applet' ||
                   2750: 		lc($tagname) eq 'object' ||
                   2751: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2752: 		) {
                   2753: 		foreach my $item (keys(%javafiles)) {
                   2754: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2755: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2756: 			&add_filetype($allfiles,$file,$item);
                   2757: 		    }
                   2758: 		}
                   2759: 	    } 
                   2760: 	    pop @state;
                   2761: 	}
                   2762:     }
1.637     raeburn  2763:     return 'ok';
                   2764: }
                   2765: 
1.639     albertel 2766: sub add_filetype {
                   2767:     my ($allfiles,$file,$type)=@_;
                   2768:     if (exists($allfiles->{$file})) {
                   2769: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2770: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2771: 	}
                   2772:     } else {
                   2773: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2774:     }
                   2775: }
                   2776: 
1.493     albertel 2777: sub removeuploadedurl {
1.984     neumanie 2778:     my ($url)=@_;	
                   2779:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2780:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2781: }
                   2782: 
                   2783: sub removeuserfile {
                   2784:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2785:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2786:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2787:     if ($result eq 'ok') {	
1.798     raeburn  2788:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2789:             my $metafile = $fname.'.meta';
                   2790:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2791: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2792:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2793:             my $sqlresult = 
1.823     albertel 2794:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2795:                                         'portfolio_metadata',$group,
                   2796:                                         'delete');
1.798     raeburn  2797:         }
                   2798:     }
                   2799:     return $result;
1.257     www      2800: }
1.15      www      2801: 
1.530     albertel 2802: sub mkdiruserfile {
                   2803:     my ($docuname,$docudom,$dir)=@_;
                   2804:     my $home=&homeserver($docuname,$docudom);
                   2805:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2806: }
                   2807: 
1.531     albertel 2808: sub renameuserfile {
                   2809:     my ($docuname,$docudom,$old,$new)=@_;
                   2810:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2811:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2812:                         &escape("$old").':'.&escape("$new"),$home);
                   2813:     if ($result eq 'ok') {
                   2814:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2815:             my $oldmeta = $old.'.meta';
                   2816:             my $newmeta = $new.'.meta';
                   2817:             my $metaresult = 
                   2818:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2819: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2820:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2821:             my $sqlresult = 
1.823     albertel 2822:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2823:                                         'portfolio_metadata',$group,
                   2824:                                         'delete');
1.798     raeburn  2825:         }
                   2826:     }
                   2827:     return $result;
1.531     albertel 2828: }
                   2829: 
1.14      www      2830: # ------------------------------------------------------------------------- Log
                   2831: 
                   2832: sub log {
                   2833:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2834:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2835: }
                   2836: 
                   2837: # ------------------------------------------------------------------ Course Log
1.352     www      2838: #
                   2839: # This routine flushes several buffers of non-mission-critical nature
                   2840: #
1.157     www      2841: 
                   2842: sub flushcourselogs {
1.352     www      2843:     &logthis('Flushing log buffers');
                   2844: #
                   2845: # course logs
                   2846: # This is a log of all transactions in a course, which can be used
                   2847: # for data mining purposes
                   2848: #
                   2849: # It also collects the courseid database, which lists last transaction
                   2850: # times and course titles for all courseids
                   2851: #
                   2852:     my %courseidbuffer=();
1.921     raeburn  2853:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2854:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2855: 		          &escape($courselogs{$crsid}),
                   2856: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2857: 	    delete $courselogs{$crsid};
                   2858:         } else {
                   2859:             &logthis('Failed to flush log buffer for '.$crsid);
                   2860:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2861:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2862:                         " exceeded maximum size, deleting.</font>");
                   2863:                delete $courselogs{$crsid};
                   2864:             }
1.352     www      2865:         }
1.920     raeburn  2866:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2867:             'description' => $coursedescrbuf{$crsid},
                   2868:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2869:             'type'        => $coursetypebuf{$crsid},
                   2870:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2871:         };
1.191     harris41 2872:     }
1.352     www      2873: #
                   2874: # Write course id database (reverse lookup) to homeserver of courses 
                   2875: # Is used in pickcourse
                   2876: #
1.840     albertel 2877:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2878:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2879:                                     $courseidbuffer{$crs_home},
                   2880:                                     $crs_home,'timeonly');
1.352     www      2881:     }
                   2882: #
                   2883: # File accesses
                   2884: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2885: #
1.449     matthew  2886:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2887:         if ($entry =~ /___count$/) {
                   2888:             my ($dom,$name);
1.807     albertel 2889:             ($dom,$name,undef)=
1.811     albertel 2890: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2891:             if (! defined($dom) || $dom eq '' || 
                   2892:                 ! defined($name) || $name eq '') {
1.620     albertel 2893:                 my $cid = $env{'request.course.id'};
                   2894:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2895:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2896:             }
1.450     matthew  2897:             my $value = $accesshash{$entry};
                   2898:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2899:             my %temphash=($url => $value);
1.449     matthew  2900:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2901:             if ($result eq 'ok') {
                   2902:                 delete $accesshash{$entry};
                   2903:             } elsif ($result eq 'unknown_cmd') {
                   2904:                 # Target server has old code running on it.
1.450     matthew  2905:                 my %temphash=($entry => $value);
1.449     matthew  2906:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2907:                     delete $accesshash{$entry};
                   2908:                 }
                   2909:             }
                   2910:         } else {
1.811     albertel 2911:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2912:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2913:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2914:                 delete $accesshash{$entry};
                   2915:             }
1.185     www      2916:         }
1.191     harris41 2917:     }
1.352     www      2918: #
                   2919: # Roles
                   2920: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2921: #
1.800     albertel 2922:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2923:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2924: 	    split(/\:/,$entry);
                   2925:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2926:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2927:                 $rudom,$runame) eq 'ok') {
                   2928: 	    delete $userrolehash{$entry};
                   2929:         }
                   2930:     }
1.662     raeburn  2931: #
                   2932: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2933: #
                   2934:     my %domrolebuffer = ();
1.1000    raeburn  2935:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2936:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2937:         if ($domrolebuffer{$rudom}) {
                   2938:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2939:                       '='.&escape($domainrolehash{$entry});
                   2940:         } else {
                   2941:             $domrolebuffer{$rudom}.=&escape($entry).
                   2942:                       '='.&escape($domainrolehash{$entry});
                   2943:         }
                   2944:         delete $domainrolehash{$entry};
                   2945:     }
                   2946:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2947: 	my %servers = &get_servers($dom,'library');
                   2948: 	foreach my $tryserver (keys(%servers)) {
                   2949: 	    unless (&reply('domroleput:'.$dom.':'.
                   2950: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2951: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2952: 	    }
1.662     raeburn  2953:         }
                   2954:     }
1.186     www      2955:     $dumpcount++;
1.157     www      2956: }
                   2957: 
                   2958: sub courselog {
                   2959:     my $what=shift;
1.158     www      2960:     $what=time.':'.$what;
1.620     albertel 2961:     unless ($env{'request.course.id'}) { return ''; }
                   2962:     $coursedombuf{$env{'request.course.id'}}=
                   2963:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2964:     $coursenumbuf{$env{'request.course.id'}}=
                   2965:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2966:     $coursehombuf{$env{'request.course.id'}}=
                   2967:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2968:     $coursedescrbuf{$env{'request.course.id'}}=
                   2969:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2970:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2971:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2972:     $courseownerbuf{$env{'request.course.id'}}=
                   2973:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2974:     $coursetypebuf{$env{'request.course.id'}}=
                   2975:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2976:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2977: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2978:     } else {
1.620     albertel 2979: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2980:     }
1.620     albertel 2981:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2982: 	&flushcourselogs();
                   2983:     }
1.158     www      2984: }
                   2985: 
                   2986: sub courseacclog {
                   2987:     my $fnsymb=shift;
1.620     albertel 2988:     unless ($env{'request.course.id'}) { return ''; }
                   2989:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2990:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2991:         $what.=':POST';
1.583     matthew  2992:         # FIXME: Probably ought to escape things....
1.800     albertel 2993: 	foreach my $key (keys(%env)) {
                   2994:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2995:                 my $formitem = $1;
                   2996:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2997:                     $what.=':'.$formitem.'='.$env{$key};
                   2998:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2999:                     $what.=':'.$formitem.'='.$env{$key};
                   3000:                 }
1.158     www      3001:             }
1.191     harris41 3002:         }
1.583     matthew  3003:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3004:         # FIXME: We should not be depending on a form parameter that someone
                   3005:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3006:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3007:             $what.= ':POST';
                   3008:             # FIXME: Probably ought to escape things....
                   3009:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3010:                                  'crsdiscuss') {
1.620     albertel 3011:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3012:             }
                   3013:         }
1.158     www      3014:     }
                   3015:     &courselog($what);
1.149     www      3016: }
                   3017: 
1.185     www      3018: sub countacc {
                   3019:     my $url=&declutter(shift);
1.458     matthew  3020:     return if (! defined($url) || $url eq '');
1.620     albertel 3021:     unless ($env{'request.course.id'}) { return ''; }
                   3022:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3023:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3024:     $accesshash{$key}++;
1.185     www      3025: }
1.349     www      3026: 
1.361     www      3027: sub linklog {
                   3028:     my ($from,$to)=@_;
                   3029:     $from=&declutter($from);
                   3030:     $to=&declutter($to);
                   3031:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3032:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3033: }
                   3034:   
1.349     www      3035: sub userrolelog {
                   3036:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3037:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3038:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3039:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3040:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3041:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3042:        $userrolehash
                   3043:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3044:                     =$tend.':'.$tstart;
1.662     raeburn  3045:     }
1.898     albertel 3046:     if (($env{'request.role'} =~ /dc\./) &&
                   3047: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3048: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3049: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3050:          ($trole=~/^co/))) {
1.898     albertel 3051:        $userrolehash
                   3052:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3053:                     =$tend.':'.$tstart;
                   3054:     }
1.662     raeburn  3055:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3056:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3057:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3058:         ($trole=~/^sc/)) {
                   3059:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3060:        $domainrolehash
                   3061:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3062:                     = $tend.':'.$tstart;
                   3063:     }
1.351     www      3064: }
                   3065: 
1.957     raeburn  3066: sub courserolelog {
                   3067:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3068:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3069:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3070:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3071:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3072:         ($trole eq 'co')) {
1.957     raeburn  3073:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3074:             my $cdom = $1;
                   3075:             my $cnum = $2;
                   3076:             my $sec = $3;
                   3077:             my $namespace = 'rolelog';
                   3078:             my %storehash = (
                   3079:                                role    => $trole,
                   3080:                                start   => $tstart,
                   3081:                                end     => $tend,
                   3082:                                selfenroll => $selfenroll,
                   3083:                                context    => $context,
                   3084:                             );
                   3085:             if ($trole eq 'gr') {
                   3086:                 $namespace = 'groupslog';
                   3087:                 $storehash{'group'} = $sec;
                   3088:             } else {
                   3089:                 $storehash{'section'} = $sec;
                   3090:             }
                   3091:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3092:             if (($trole ne 'st') || ($sec ne '')) {
                   3093:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3094:             }
1.957     raeburn  3095:         }
                   3096:     }
                   3097:     return;
                   3098: }
                   3099: 
1.351     www      3100: sub get_course_adv_roles {
1.948     raeburn  3101:     my ($cid,$codes) = @_;
1.620     albertel 3102:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3103:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3104:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3105:     my %nothide=();
1.800     albertel 3106:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3107:         if ($user !~ /:/) {
                   3108: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3109:         } else {
                   3110:             $nothide{$user}=1;
                   3111:         }
1.470     www      3112:     }
1.351     www      3113:     my %returnhash=();
                   3114:     my %dumphash=
                   3115:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3116:     my $now=time;
1.997     raeburn  3117:     my %privileged;
1.1000    raeburn  3118:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3119: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3120:         if (($tstart) && ($tstart<0)) { next; }
                   3121:         if (($tend) && ($tend<$now)) { next; }
                   3122:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3123:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3124: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3125:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3126:             my %dompersonnel =
1.998     raeburn  3127:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3128:             $privileged{$domain} = {};
                   3129:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3130:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3131:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3132:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3133:                         $privileged{$udom}{$uname} = 1;
                   3134:                     }
                   3135:                 }
                   3136:             }
                   3137:         }
                   3138:         if ((exists($privileged{$domain}{$username})) && 
                   3139:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3140: 	if ($role eq 'cr') { next; }
1.948     raeburn  3141:         if ($codes) {
                   3142:             if ($section) { $role .= ':'.$section; }
                   3143:             if ($returnhash{$role}) {
                   3144:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3145:             } else {
                   3146:                 $returnhash{$role}=$username.':'.$domain;
                   3147:             }
1.351     www      3148:         } else {
1.988     raeburn  3149:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3150:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3151:             if ($returnhash{$key}) {
                   3152: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3153:             } else {
                   3154:                 $returnhash{$key}=$username.':'.$domain;
                   3155:             }
1.351     www      3156:         }
1.948     raeburn  3157:     }
1.400     www      3158:     return %returnhash;
                   3159: }
                   3160: 
                   3161: sub get_my_roles {
1.937     raeburn  3162:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3163:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3164:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3165:     my (%dumphash,%nothide);
1.858     raeburn  3166:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3167:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3168:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3169:     } else {
                   3170:         %dumphash=
1.400     www      3171:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3172:         if ($hidepriv) {
                   3173:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3174:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3175:                 if ($user !~ /:/) {
                   3176:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3177:                 } else {
                   3178:                     $nothide{$user} = 1;
                   3179:                 }
                   3180:             }
                   3181:         }
1.858     raeburn  3182:     }
1.400     www      3183:     my %returnhash=();
                   3184:     my $now=time;
1.999     raeburn  3185:     my %privileged;
1.800     albertel 3186:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3187:         my ($role,$tend,$tstart);
                   3188:         if ($context eq 'userroles') {
                   3189: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3190:         } else {
                   3191:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3192:         }
1.400     www      3193:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3194:         my $status = 'active';
1.939     raeburn  3195:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3196:             $status = 'previous';
                   3197:         } 
                   3198:         if (($tstart) && ($now<$tstart)) {
                   3199:             $status = 'future';
                   3200:         }
                   3201:         if (ref($types) eq 'ARRAY') {
                   3202:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3203:                 next;
                   3204:             } 
                   3205:         } else {
                   3206:             if ($status ne 'active') {
                   3207:                 next;
                   3208:             }
                   3209:         }
1.867     raeburn  3210:         my ($rolecode,$username,$domain,$section,$area);
                   3211:         if ($context eq 'userroles') {
                   3212:             ($area,$rolecode) = split(/_/,$entry);
                   3213:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3214:         } else {
                   3215:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3216:         }
1.832     raeburn  3217:         if (ref($roledoms) eq 'ARRAY') {
                   3218:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3219:                 next;
                   3220:             }
                   3221:         }
                   3222:         if (ref($roles) eq 'ARRAY') {
                   3223:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3224:                 if ($role =~ /^cr\//) {
                   3225:                     if (!grep(/^cr$/,@{$roles})) {
                   3226:                         next;
                   3227:                     }
                   3228:                 } else {
                   3229:                     next;
                   3230:                 }
1.832     raeburn  3231:             }
1.867     raeburn  3232:         }
1.937     raeburn  3233:         if ($hidepriv) {
1.999     raeburn  3234:             if ($context eq 'userroles') {
                   3235:                 if ((&privileged($username,$domain)) &&
                   3236:                     (!$nothide{$username.':'.$domain})) {
                   3237:                     next;
                   3238:                 }
                   3239:             } else {
                   3240:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3241:                     my %dompersonnel =
                   3242:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3243:                     $privileged{$domain} = {};
                   3244:                     if (keys(%dompersonnel)) {
                   3245:                         foreach my $server (keys(%dompersonnel)) {
                   3246:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3247:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3248:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3249:                                     $privileged{$udom}{$uname} = $trole;
                   3250:                                 }
                   3251:                             }
                   3252:                         }
                   3253:                     }
                   3254:                 }
                   3255:                 if (exists($privileged{$domain}{$username})) {
                   3256:                     if (!$nothide{$username.':'.$domain}) {
                   3257:                         next;
                   3258:                     }
                   3259:                 }
1.937     raeburn  3260:             }
                   3261:         }
1.933     raeburn  3262:         if ($withsec) {
                   3263:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3264:                 $tstart.':'.$tend;
                   3265:         } else {
                   3266:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3267:         }
1.832     raeburn  3268:     }
1.373     www      3269:     return %returnhash;
1.399     www      3270: }
                   3271: 
                   3272: # ----------------------------------------------------- Frontpage Announcements
                   3273: #
                   3274: #
                   3275: 
                   3276: sub postannounce {
                   3277:     my ($server,$text)=@_;
1.844     albertel 3278:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3279:     unless ($text=~/\w/) { $text=''; }
                   3280:     return &reply('setannounce:'.&escape($text),$server);
                   3281: }
                   3282: 
                   3283: sub getannounce {
1.448     albertel 3284: 
                   3285:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3286: 	my $announcement='';
1.800     albertel 3287: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3288: 	close($fh);
1.399     www      3289: 	if ($announcement=~/\w/) { 
                   3290: 	    return 
                   3291:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3292:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3293: 	} else {
                   3294: 	    return '';
                   3295: 	}
                   3296:     } else {
                   3297: 	return '';
                   3298:     }
1.351     www      3299: }
1.353     www      3300: 
                   3301: # ---------------------------------------------------------- Course ID routines
                   3302: # Deal with domain's nohist_courseid.db files
                   3303: #
                   3304: 
                   3305: sub courseidput {
1.921     raeburn  3306:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3307:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3308:     my $outcome;
                   3309:     if ($caller eq 'timeonly') {
                   3310:         my $cids = '';
                   3311:         foreach my $item (keys(%$storehash)) {
                   3312:             $cids.=&escape($item).'&';
                   3313:         }
                   3314:         $cids=~s/\&$//;
                   3315:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3316:                           $coursehome);       
                   3317:     } else {
                   3318:         my $items = '';
                   3319:         foreach my $item (keys(%$storehash)) {
                   3320:             $items.= &escape($item).'='.
                   3321:                      &freeze_escape($$storehash{$item}).'&';
                   3322:         }
                   3323:         $items=~s/\&$//;
                   3324:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3325:                           $coursehome);
1.918     raeburn  3326:     }
                   3327:     if ($outcome eq 'unknown_cmd') {
                   3328:         my $what;
                   3329:         foreach my $cid (keys(%$storehash)) {
                   3330:             $what .= &escape($cid).'=';
1.921     raeburn  3331:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3332:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3333:             }
                   3334:             $what =~ s/\:$/&/;
                   3335:         }
                   3336:         $what =~ s/\&$//;  
                   3337:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3338:     } else {
                   3339:         return $outcome;
                   3340:     }
1.353     www      3341: }
                   3342: 
                   3343: sub courseiddump {
1.921     raeburn  3344:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3345:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3346:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3347:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3348:     my $as_hash = 1;
                   3349:     my %returnhash;
                   3350:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3351:     my %libserv = &all_library();
                   3352:     foreach my $tryserver (keys(%libserv)) {
                   3353:         if ( (  $hostidflag == 1 
                   3354: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3355: 	     || (!defined($hostidflag)) ) {
                   3356: 
1.918     raeburn  3357: 	    if (($domfilter eq '') ||
                   3358: 		(&host_domain($tryserver) eq $domfilter)) {
                   3359:                 my $rep = 
                   3360:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3361:                          $sincefilter.':'.&escape($descfilter).':'.
                   3362:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3363:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3364:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3365:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3366:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3367:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3368:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3369:                          &escape($creationcontext).':'.$domcloner,
                   3370:                          $tryserver);
1.918     raeburn  3371:                 my @pairs=split(/\&/,$rep);
                   3372:                 foreach my $item (@pairs) {
                   3373:                     my ($key,$value)=split(/\=/,$item,2);
                   3374:                     $key = &unescape($key);
                   3375:                     next if ($key =~ /^error: 2 /);
                   3376:                     my $result = &thaw_unescape($value);
                   3377:                     if (ref($result) eq 'HASH') {
                   3378:                         $returnhash{$key}=$result;
                   3379:                     } else {
1.921     raeburn  3380:                         my @responses = split(/:/,$value);
                   3381:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3382:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3383:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3384:                         }
1.1008    raeburn  3385:                     }
1.353     www      3386:                 }
                   3387:             }
                   3388:         }
                   3389:     }
                   3390:     return %returnhash;
                   3391: }
                   3392: 
1.1055    raeburn  3393: sub courselastaccess {
                   3394:     my ($cdom,$cnum,$hostidref) = @_;
                   3395:     my %returnhash;
                   3396:     if ($cdom && $cnum) {
                   3397:         my $chome = &homeserver($cnum,$cdom);
                   3398:         if ($chome ne 'no_host') {
                   3399:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3400:             &extract_lastaccess(\%returnhash,$rep);
                   3401:         }
                   3402:     } else {
                   3403:         if (!$cdom) { $cdom=''; }
                   3404:         my %libserv = &all_library();
                   3405:         foreach my $tryserver (keys(%libserv)) {
                   3406:             if (ref($hostidref) eq 'ARRAY') {
                   3407:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3408:             } 
                   3409:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3410:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3411:                 &extract_lastaccess(\%returnhash,$rep);
                   3412:             }
                   3413:         }
                   3414:     }
                   3415:     return %returnhash;
                   3416: }
                   3417: 
                   3418: sub extract_lastaccess {
                   3419:     my ($returnhash,$rep) = @_;
                   3420:     if (ref($returnhash) eq 'HASH') {
                   3421:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3422:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3423:                  $rep eq '') {
                   3424:             my @pairs=split(/\&/,$rep);
                   3425:             foreach my $item (@pairs) {
                   3426:                 my ($key,$value)=split(/\=/,$item,2);
                   3427:                 $key = &unescape($key);
                   3428:                 next if ($key =~ /^error: 2 /);
                   3429:                 $returnhash->{$key} = &thaw_unescape($value);
                   3430:             }
                   3431:         }
                   3432:     }
                   3433:     return;
                   3434: }
                   3435: 
1.658     raeburn  3436: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3437: 
                   3438: sub dcmailput {
1.685     raeburn  3439:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3440:     my $status = &Apache::lonnet::critical(
1.740     www      3441:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3442:        &escape($message),$server);
1.662     raeburn  3443:     return $status;
                   3444: }
                   3445: 
1.658     raeburn  3446: sub dcmaildump {
                   3447:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3448:     my %returnhash=();
1.846     albertel 3449: 
                   3450:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3451:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3452:                                                          &escape($enddate).':';
                   3453: 	my @esc_senders=map { &escape($_)} @$senders;
                   3454: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3455: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3456:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3457:             if (($key) && ($value)) {
                   3458:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3459:             }
                   3460:         }
                   3461:     }
                   3462:     return %returnhash;
                   3463: }
1.662     raeburn  3464: # ---------------------------------------------------------- Domain roles
                   3465: 
                   3466: sub get_domain_roles {
                   3467:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3468:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3469:         $startdate = '.';
                   3470:     }
1.1018    raeburn  3471:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3472:         $enddate = '.';
                   3473:     }
1.922     raeburn  3474:     my $rolelist;
                   3475:     if (ref($roles) eq 'ARRAY') {
                   3476:         $rolelist = join(':',@{$roles});
                   3477:     }
1.662     raeburn  3478:     my %personnel = ();
1.841     albertel 3479: 
                   3480:     my %servers = &get_servers($dom,'library');
                   3481:     foreach my $tryserver (keys(%servers)) {
                   3482: 	%{$personnel{$tryserver}}=();
                   3483: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3484: 					    &escape($startdate).':'.
                   3485: 					    &escape($enddate).':'.
                   3486: 					    &escape($rolelist), $tryserver))) {
                   3487: 	    my ($key,$value) = split(/\=/,$line,2);
                   3488: 	    if (($key) && ($value)) {
                   3489: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3490: 	    }
                   3491: 	}
1.662     raeburn  3492:     }
                   3493:     return %personnel;
                   3494: }
1.658     raeburn  3495: 
1.149     www      3496: # ----------------------------------------------------------- Check out an item
                   3497: 
1.504     albertel 3498: sub get_first_access {
                   3499:     my ($type,$argsymb)=@_;
1.790     albertel 3500:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3501:     if ($argsymb) { $symb=$argsymb; }
                   3502:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3503:     if ($type eq 'course') {
                   3504: 	$res='course';
                   3505:     } elsif ($type eq 'map') {
1.588     albertel 3506: 	$res=&symbread($map);
                   3507:     } else {
                   3508: 	$res=$symb;
                   3509:     }
                   3510:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3511:     return $times{"$courseid\0$res"};
1.504     albertel 3512: }
                   3513: 
                   3514: sub set_first_access {
                   3515:     my ($type)=@_;
1.790     albertel 3516:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3517:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3518:     if ($type eq 'course') {
                   3519: 	$res='course';
                   3520:     } elsif ($type eq 'map') {
1.588     albertel 3521: 	$res=&symbread($map);
                   3522:     } else {
                   3523: 	$res=$symb;
                   3524:     }
                   3525:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3526:     if (!$firstaccess) {
1.588     albertel 3527: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3528:     }
                   3529:     return 'already_set';
1.504     albertel 3530: }
                   3531: 
1.149     www      3532: sub checkout {
                   3533:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3534:     my $now=time;
                   3535:     my $lonhost=$perlvar{'lonHostID'};
                   3536:     my $infostr=&escape(
1.234     www      3537:                  'CHECKOUTTOKEN&'.
1.149     www      3538:                  $tuname.'&'.
                   3539:                  $tudom.'&'.
                   3540:                  $tcrsid.'&'.
                   3541:                  $symb.'&'.
                   3542: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3543:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3544:     if ($token=~/^error\:/) { 
1.672     albertel 3545:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3546:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3547:                  "</font>");
                   3548:         return ''; 
                   3549:     }
                   3550: 
1.149     www      3551:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3552:     $token=~tr/a-z/A-Z/;
                   3553: 
1.153     www      3554:     my %infohash=('resource.0.outtoken' => $token,
                   3555:                   'resource.0.checkouttime' => $now,
                   3556:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3557: 
                   3558:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3559:        return '';
1.151     www      3560:     } else {
1.672     albertel 3561:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3562:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3563:                  "</font>");
1.149     www      3564:     }    
                   3565: 
                   3566:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3567:                          &escape('Checkout '.$infostr.' - '.
                   3568:                                                  $token)) ne 'ok') {
                   3569: 	return '';
1.151     www      3570:     } else {
1.672     albertel 3571:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3572:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3573:                  "</font>");
1.149     www      3574:     }
1.151     www      3575:     return $token;
1.149     www      3576: }
                   3577: 
                   3578: # ------------------------------------------------------------ Check in an item
                   3579: 
                   3580: sub checkin {
                   3581:     my $token=shift;
1.150     www      3582:     my $now=time;
                   3583:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3584:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3585:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3586:     $dtoken=~s/\W/\_/g;
1.234     www      3587:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3588:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3589: 
1.154     www      3590:     unless (($tuname) && ($tudom)) {
                   3591:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3592:         return '';
                   3593:     }
                   3594:     
                   3595:     unless (&allowed('mgr',$tcrsid)) {
                   3596:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3597:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3598:         return '';
                   3599:     }
                   3600: 
1.153     www      3601:     my %infohash=('resource.0.intoken' => $token,
                   3602:                   'resource.0.checkintime' => $now,
                   3603:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3604: 
                   3605:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3606:        return '';
                   3607:     }    
                   3608: 
                   3609:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3610:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3611: 	return '';
                   3612:     }
                   3613: 
                   3614:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3615: }
                   3616: 
                   3617: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3618: 
                   3619: sub expirespread {
                   3620:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3621:     my $cid=$env{'request.course.id'}; 
1.110     www      3622:     if ($cid) {
                   3623:        my $now=time;
                   3624:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3625:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3626:                             $env{'course.'.$cid.'.num'}.
1.110     www      3627: 	        	    ':nohist_expirationdates:'.
                   3628:                             &escape($key).'='.$now,
1.620     albertel 3629:                             $env{'course.'.$cid.'.home'})
1.110     www      3630:     }
                   3631:     return 'ok';
1.14      www      3632: }
                   3633: 
1.109     www      3634: # ----------------------------------------------------- Devalidate Spreadsheets
                   3635: 
                   3636: sub devalidate {
1.325     www      3637:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3638:     my $cid=$env{'request.course.id'}; 
1.109     www      3639:     if ($cid) {
1.391     matthew  3640:         # delete the stored spreadsheets for
                   3641:         # - the student level sheet of this user in course's homespace
                   3642:         # - the assessment level sheet for this resource 
                   3643:         #   for this user in user's homespace
1.553     albertel 3644: 	# - current conditional state info
1.325     www      3645: 	my $key=$uname.':'.$udom.':';
1.109     www      3646:         my $status=
1.299     matthew  3647: 	    &del('nohist_calculatedsheets',
1.391     matthew  3648: 		 [$key.'studentcalc:'],
1.620     albertel 3649: 		 $env{'course.'.$cid.'.domain'},
                   3650: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3651: 		.' '.
                   3652: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3653: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3654:         unless ($status eq 'ok ok') {
                   3655:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3656:                     $uname.' at '.$udom.' for '.
1.109     www      3657: 		    $symb.': '.$status);
1.133     albertel 3658:         }
1.553     albertel 3659: 	&delenv('user.state.'.$cid);
1.109     www      3660:     }
                   3661: }
                   3662: 
1.265     albertel 3663: sub get_scalar {
                   3664:     my ($string,$end) = @_;
                   3665:     my $value;
                   3666:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3667: 	$value = $1;
                   3668:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3669: 	$value = $1;
                   3670:     }
                   3671:     return &unescape($value);
                   3672: }
                   3673: 
                   3674: sub array2str {
                   3675:   my (@array) = @_;
                   3676:   my $result=&arrayref2str(\@array);
                   3677:   $result=~s/^__ARRAY_REF__//;
                   3678:   $result=~s/__END_ARRAY_REF__$//;
                   3679:   return $result;
                   3680: }
                   3681: 
1.204     albertel 3682: sub arrayref2str {
                   3683:   my ($arrayref) = @_;
1.265     albertel 3684:   my $result='__ARRAY_REF__';
1.204     albertel 3685:   foreach my $elem (@$arrayref) {
1.265     albertel 3686:     if(ref($elem) eq 'ARRAY') {
                   3687:       $result.=&arrayref2str($elem).'&';
                   3688:     } elsif(ref($elem) eq 'HASH') {
                   3689:       $result.=&hashref2str($elem).'&';
                   3690:     } elsif(ref($elem)) {
                   3691:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3692:     } else {
                   3693:       $result.=&escape($elem).'&';
                   3694:     }
                   3695:   }
                   3696:   $result=~s/\&$//;
1.265     albertel 3697:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3698:   return $result;
                   3699: }
                   3700: 
1.168     albertel 3701: sub hash2str {
1.204     albertel 3702:   my (%hash) = @_;
                   3703:   my $result=&hashref2str(\%hash);
1.265     albertel 3704:   $result=~s/^__HASH_REF__//;
                   3705:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3706:   return $result;
                   3707: }
                   3708: 
                   3709: sub hashref2str {
                   3710:   my ($hashref)=@_;
1.265     albertel 3711:   my $result='__HASH_REF__';
1.800     albertel 3712:   foreach my $key (sort(keys(%$hashref))) {
                   3713:     if (ref($key) eq 'ARRAY') {
                   3714:       $result.=&arrayref2str($key).'=';
                   3715:     } elsif (ref($key) eq 'HASH') {
                   3716:       $result.=&hashref2str($key).'=';
                   3717:     } elsif (ref($key)) {
1.265     albertel 3718:       $result.='=';
1.800     albertel 3719:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3720:     } else {
1.1056.4.32  raeburn  3721:         if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3722:     }
                   3723: 
1.800     albertel 3724:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3725:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3726:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3727:       $result.=&hashref2str($hashref->{$key}).'&';
                   3728:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3729:        $result.='&';
1.800     albertel 3730:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3731:     } else {
1.800     albertel 3732:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3733:     }
                   3734:   }
1.168     albertel 3735:   $result=~s/\&$//;
1.265     albertel 3736:   $result .= '__END_HASH_REF__';
1.168     albertel 3737:   return $result;
                   3738: }
                   3739: 
                   3740: sub str2hash {
1.265     albertel 3741:     my ($string)=@_;
                   3742:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3743:     return %$hash;
                   3744: }
                   3745: 
                   3746: sub str2hashref {
1.168     albertel 3747:   my ($string) = @_;
1.265     albertel 3748: 
                   3749:   my %hash;
                   3750: 
                   3751:   if($string !~ /^__HASH_REF__/) {
                   3752:       if (! ($string eq '' || !defined($string))) {
                   3753: 	  $hash{'error'}='Not hash reference';
                   3754:       }
                   3755:       return (\%hash, $string);
                   3756:   }
                   3757: 
                   3758:   $string =~ s/^__HASH_REF__//;
                   3759: 
                   3760:   while($string !~ /^__END_HASH_REF__/) {
                   3761:       #key
                   3762:       my $key='';
                   3763:       if($string =~ /^__HASH_REF__/) {
                   3764:           ($key, $string)=&str2hashref($string);
                   3765:           if(defined($key->{'error'})) {
                   3766:               $hash{'error'}='Bad data';
                   3767:               return (\%hash, $string);
                   3768:           }
                   3769:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3770:           ($key, $string)=&str2arrayref($string);
                   3771:           if($key->[0] eq 'Array reference error') {
                   3772:               $hash{'error'}='Bad data';
                   3773:               return (\%hash, $string);
                   3774:           }
                   3775:       } else {
                   3776:           $string =~ s/^(.*?)=//;
1.267     albertel 3777: 	  $key=&unescape($1);
1.265     albertel 3778:       }
                   3779:       $string =~ s/^=//;
                   3780: 
                   3781:       #value
                   3782:       my $value='';
                   3783:       if($string =~ /^__HASH_REF__/) {
                   3784:           ($value, $string)=&str2hashref($string);
                   3785:           if(defined($value->{'error'})) {
                   3786:               $hash{'error'}='Bad data';
                   3787:               return (\%hash, $string);
                   3788:           }
                   3789:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3790:           ($value, $string)=&str2arrayref($string);
                   3791:           if($value->[0] eq 'Array reference error') {
                   3792:               $hash{'error'}='Bad data';
                   3793:               return (\%hash, $string);
                   3794:           }
                   3795:       } else {
                   3796: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3797:       }
                   3798:       $string =~ s/^&//;
                   3799: 
                   3800:       $hash{$key}=$value;
1.204     albertel 3801:   }
1.265     albertel 3802: 
                   3803:   $string =~ s/^__END_HASH_REF__//;
                   3804: 
                   3805:   return (\%hash, $string);
1.204     albertel 3806: }
                   3807: 
                   3808: sub str2array {
1.265     albertel 3809:     my ($string)=@_;
                   3810:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3811:     return @$array;
                   3812: }
                   3813: 
                   3814: sub str2arrayref {
1.204     albertel 3815:   my ($string) = @_;
1.265     albertel 3816:   my @array;
                   3817: 
                   3818:   if($string !~ /^__ARRAY_REF__/) {
                   3819:       if (! ($string eq '' || !defined($string))) {
                   3820: 	  $array[0]='Array reference error';
                   3821:       }
                   3822:       return (\@array, $string);
                   3823:   }
                   3824: 
                   3825:   $string =~ s/^__ARRAY_REF__//;
                   3826: 
                   3827:   while($string !~ /^__END_ARRAY_REF__/) {
                   3828:       my $value='';
                   3829:       if($string =~ /^__HASH_REF__/) {
                   3830:           ($value, $string)=&str2hashref($string);
                   3831:           if(defined($value->{'error'})) {
                   3832:               $array[0] ='Array reference error';
                   3833:               return (\@array, $string);
                   3834:           }
                   3835:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3836:           ($value, $string)=&str2arrayref($string);
                   3837:           if($value->[0] eq 'Array reference error') {
                   3838:               $array[0] ='Array reference error';
                   3839:               return (\@array, $string);
                   3840:           }
                   3841:       } else {
                   3842: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3843:       }
                   3844:       $string =~ s/^&//;
                   3845: 
                   3846:       push(@array, $value);
1.191     harris41 3847:   }
1.265     albertel 3848: 
                   3849:   $string =~ s/^__END_ARRAY_REF__//;
                   3850: 
                   3851:   return (\@array, $string);
1.168     albertel 3852: }
                   3853: 
1.167     albertel 3854: # -------------------------------------------------------------------Temp Store
                   3855: 
1.168     albertel 3856: sub tmpreset {
                   3857:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3858:   if (!$symb) {
                   3859:     $symb=&symbread();
1.620     albertel 3860:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3861:   }
                   3862:   $symb=escape($symb);
                   3863: 
1.620     albertel 3864:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3865:   $namespace=~s/\//\_/g;
                   3866:   $namespace=~s/\W//g;
                   3867: 
1.620     albertel 3868:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3869:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3870:   if ($domain eq 'public' && $stuname eq 'public') {
                   3871:       $stuname=$ENV{'REMOTE_ADDR'};
                   3872:   }
1.168     albertel 3873:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3874:   my %hash;
                   3875:   if (tie(%hash,'GDBM_File',
                   3876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3877: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3878:     foreach my $key (keys(%hash)) {
1.180     albertel 3879:       if ($key=~ /:$symb/) {
1.168     albertel 3880: 	delete($hash{$key});
                   3881:       }
                   3882:     }
                   3883:   }
                   3884: }
                   3885: 
1.167     albertel 3886: sub tmpstore {
1.168     albertel 3887:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3888: 
                   3889:   if (!$symb) {
                   3890:     $symb=&symbread();
1.620     albertel 3891:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3892:   }
                   3893:   $symb=escape($symb);
                   3894: 
                   3895:   if (!$namespace) {
                   3896:     # I don't think we would ever want to store this for a course.
                   3897:     # it seems this will only be used if we don't have a course.
1.620     albertel 3898:     #$namespace=$env{'request.course.id'};
1.168     albertel 3899:     #if (!$namespace) {
1.620     albertel 3900:       $namespace=$env{'request.state'};
1.168     albertel 3901:     #}
                   3902:   }
                   3903:   $namespace=~s/\//\_/g;
                   3904:   $namespace=~s/\W//g;
1.620     albertel 3905:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3906:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3907:   if ($domain eq 'public' && $stuname eq 'public') {
                   3908:       $stuname=$ENV{'REMOTE_ADDR'};
                   3909:   }
1.168     albertel 3910:   my $now=time;
                   3911:   my %hash;
                   3912:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3913:   if (tie(%hash,'GDBM_File',
                   3914: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3915: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3916:     $hash{"version:$symb"}++;
                   3917:     my $version=$hash{"version:$symb"};
                   3918:     my $allkeys=''; 
                   3919:     foreach my $key (keys(%$storehash)) {
                   3920:       $allkeys.=$key.':';
1.591     albertel 3921:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3922:     }
                   3923:     $hash{"$version:$symb:timestamp"}=$now;
                   3924:     $allkeys.='timestamp';
                   3925:     $hash{"$version:keys:$symb"}=$allkeys;
                   3926:     if (untie(%hash)) {
                   3927:       return 'ok';
                   3928:     } else {
                   3929:       return "error:$!";
                   3930:     }
                   3931:   } else {
                   3932:     return "error:$!";
                   3933:   }
                   3934: }
1.167     albertel 3935: 
1.168     albertel 3936: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3937: 
1.168     albertel 3938: sub tmprestore {
                   3939:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3940: 
1.168     albertel 3941:   if (!$symb) {
                   3942:     $symb=&symbread();
1.620     albertel 3943:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3944:   }
                   3945:   $symb=escape($symb);
                   3946: 
1.620     albertel 3947:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3948: 
1.620     albertel 3949:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3950:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3951:   if ($domain eq 'public' && $stuname eq 'public') {
                   3952:       $stuname=$ENV{'REMOTE_ADDR'};
                   3953:   }
1.168     albertel 3954:   my %returnhash;
                   3955:   $namespace=~s/\//\_/g;
                   3956:   $namespace=~s/\W//g;
                   3957:   my %hash;
                   3958:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3959:   if (tie(%hash,'GDBM_File',
                   3960: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3961: 	  &GDBM_READER(),0640)) {
1.168     albertel 3962:     my $version=$hash{"version:$symb"};
                   3963:     $returnhash{'version'}=$version;
                   3964:     my $scope;
                   3965:     for ($scope=1;$scope<=$version;$scope++) {
                   3966:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3967:       my @keys=split(/:/,$vkeys);
                   3968:       my $key;
                   3969:       $returnhash{"$scope:keys"}=$vkeys;
                   3970:       foreach $key (@keys) {
1.591     albertel 3971: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3972: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3973:       }
                   3974:     }
1.168     albertel 3975:     if (!(untie(%hash))) {
                   3976:       return "error:$!";
                   3977:     }
                   3978:   } else {
                   3979:     return "error:$!";
                   3980:   }
                   3981:   return %returnhash;
1.167     albertel 3982: }
                   3983: 
1.9       www      3984: # ----------------------------------------------------------------------- Store
                   3985: 
                   3986: sub store {
1.124     www      3987:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3988:     my $home='';
                   3989: 
1.168     albertel 3990:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3991: 
1.213     www      3992:     $symb=&symbclean($symb);
1.122     albertel 3993:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3994: 
1.620     albertel 3995:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3996:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3997: 
                   3998:     &devalidate($symb,$stuname,$domain);
1.109     www      3999: 
                   4000:     $symb=escape($symb);
1.187     www      4001:     if (!$namespace) { 
1.620     albertel 4002:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4003:           return ''; 
                   4004:        } 
                   4005:     }
1.620     albertel 4006:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4007: 
                   4008:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4009:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4010: 
1.12      www      4011:     my $namevalue='';
1.800     albertel 4012:     foreach my $key (keys(%$storehash)) {
                   4013:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4014:     }
1.12      www      4015:     $namevalue=~s/\&$//;
1.187     www      4016:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4017:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4018: }
                   4019: 
1.47      www      4020: # -------------------------------------------------------------- Critical Store
                   4021: 
                   4022: sub cstore {
1.124     www      4023:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4024:     my $home='';
                   4025: 
1.168     albertel 4026:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4027: 
1.213     www      4028:     $symb=&symbclean($symb);
1.122     albertel 4029:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4030: 
1.620     albertel 4031:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4032:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4033: 
                   4034:     &devalidate($symb,$stuname,$domain);
1.109     www      4035: 
                   4036:     $symb=escape($symb);
1.187     www      4037:     if (!$namespace) { 
1.620     albertel 4038:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4039:           return ''; 
                   4040:        } 
                   4041:     }
1.620     albertel 4042:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4043: 
                   4044:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4045:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4046: 
1.47      www      4047:     my $namevalue='';
1.800     albertel 4048:     foreach my $key (keys(%$storehash)) {
                   4049:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4050:     }
1.47      www      4051:     $namevalue=~s/\&$//;
1.187     www      4052:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4053:     return critical
                   4054:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4055: }
                   4056: 
1.9       www      4057: # --------------------------------------------------------------------- Restore
                   4058: 
                   4059: sub restore {
1.124     www      4060:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4061:     my $home='';
                   4062: 
1.168     albertel 4063:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4064: 
1.122     albertel 4065:     if (!$symb) {
                   4066:       unless ($symb=escape(&symbread())) { return ''; }
                   4067:     } else {
1.213     www      4068:       $symb=&escape(&symbclean($symb));
1.122     albertel 4069:     }
1.188     www      4070:     if (!$namespace) { 
1.620     albertel 4071:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4072:           return ''; 
                   4073:        } 
                   4074:     }
1.620     albertel 4075:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4076:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4077:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4078:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4079: 
1.12      www      4080:     my %returnhash=();
1.800     albertel 4081:     foreach my $line (split(/\&/,$answer)) {
                   4082: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4083:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4084:     }
1.75      www      4085:     my $version;
                   4086:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4087:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4088:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4089:        }
1.75      www      4090:     }
1.13      www      4091:     return %returnhash;
1.34      www      4092: }
                   4093: 
                   4094: # ---------------------------------------------------------- Course Description
                   4095: 
                   4096: sub coursedescription {
1.731     albertel 4097:     my ($courseid,$args)=@_;
1.34      www      4098:     $courseid=~s/^\///;
1.49      www      4099:     $courseid=~s/\_/\//g;
1.34      www      4100:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4101:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4102:     my $normalid=$cdomain.'_'.$cnum;
                   4103:     # need to always cache even if we get errors otherwise we keep 
                   4104:     # trying and trying and trying to get the course description.
                   4105:     my %envhash=();
                   4106:     my %returnhash=();
1.731     albertel 4107:     
                   4108:     my $expiretime=600;
                   4109:     if ($env{'request.course.id'} eq $normalid) {
                   4110: 	$expiretime=120;
                   4111:     }
                   4112: 
                   4113:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4114:     if (!$args->{'freshen_cache'}
                   4115: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4116: 	foreach my $key (keys(%env)) {
                   4117: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4118: 	    my ($setting) = $1;
                   4119: 	    $returnhash{$setting} = $env{$key};
                   4120: 	}
                   4121: 	return %returnhash;
                   4122:     }
                   4123: 
                   4124:     # get the data agin
                   4125:     if (!$args->{'one_time'}) {
                   4126: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4127:     }
1.811     albertel 4128: 
1.34      www      4129:     if ($chome ne 'no_host') {
1.302     albertel 4130:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4131:        if (!exists($returnhash{'con_lost'})) {
                   4132:            $returnhash{'home'}= $chome;
                   4133: 	   $returnhash{'domain'} = $cdomain;
                   4134: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4135:            if (!defined($returnhash{'type'})) {
                   4136:                $returnhash{'type'} = 'Course';
                   4137:            }
1.130     albertel 4138:            while (my ($name,$value) = each %returnhash) {
1.53      www      4139:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4140:            }
1.270     www      4141:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4142:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4143: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4144:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4145:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4146:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4147:        }
                   4148:     }
1.731     albertel 4149:     if (!$args->{'one_time'}) {
1.949     raeburn  4150: 	&appenv(\%envhash);
1.731     albertel 4151:     }
1.302     albertel 4152:     return %returnhash;
1.461     www      4153: }
                   4154: 
1.1056.4.5  raeburn  4155: sub update_released_required {
                   4156:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4157:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4158:         $cid = $env{'request.course.id'};
                   4159:         $cdom = $env{'course.'.$cid.'.domain'};
                   4160:         $cnum = $env{'course.'.$cid.'.num'};
                   4161:         $chome = $env{'course.'.$cid.'.home'};
                   4162:     }
                   4163:     if ($needsrelease) {
                   4164:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4165:         my $needsupdate;
                   4166:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4167:             $needsupdate = 1;
                   4168:         } else {
                   4169:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4170:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4171:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4172:                 $needsupdate = 1;
                   4173:             }
                   4174:         }
                   4175:         if ($needsupdate) {
                   4176:             my %needshash = (
                   4177:                              'internal.releaserequired' => $needsrelease,
                   4178:                             );
                   4179:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4180:             if ($putresult eq 'ok') {
                   4181:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4182:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4183:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4184:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4185:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4186:                 }
                   4187:             }
                   4188:         }
                   4189:     }
                   4190:     return;
                   4191: }
                   4192: 
1.461     www      4193: # -------------------------------------------------See if a user is privileged
                   4194: 
                   4195: sub privileged {
                   4196:     my ($username,$domain)=@_;
                   4197:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4198: 			&homeserver($username,$domain));
1.1033    raeburn  4199:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4200:         ($rolesdump =~ /^error:/)) {
                   4201:         return 0;
                   4202:     }
1.461     www      4203:     my $now=time;
                   4204:     if ($rolesdump ne '') {
1.800     albertel 4205:         foreach my $entry (split(/&/,$rolesdump)) {
                   4206: 	    if ($entry!~/^rolesdef_/) {
                   4207: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4208: 		$area=~s/\_\w\w$//;
                   4209: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4210: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4211: 		    my $active=1;
                   4212: 		    if ($tend) {
                   4213: 			if ($tend<$now) { $active=0; }
                   4214: 		    }
                   4215: 		    if ($tstart) {
                   4216: 			if ($tstart>$now) { $active=0; }
                   4217: 		    }
                   4218: 		    if ($active) { return 1; }
                   4219: 		}
                   4220: 	    }
                   4221: 	}
                   4222:     }
                   4223:     return 0;
1.9       www      4224: }
1.1       albertel 4225: 
1.103     harris41 4226: # -------------------------------------------------------- Get user privileges
1.11      www      4227: 
                   4228: sub rolesinit {
                   4229:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4230:     my $now=time;
                   4231:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4232:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4233:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4234:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4235:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4236:         return \%userroles;
                   4237:     }
1.11      www      4238:     my %allroles=();
1.678     raeburn  4239:     my %allgroups=();   
                   4240:     my $group_privs;
1.11      www      4241: 
                   4242:     if ($rolesdump ne '') {
1.800     albertel 4243:         foreach my $entry (split(/&/,$rolesdump)) {
                   4244: 	  if ($entry!~/^rolesdef_/) {
                   4245:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4246: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4247:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4248: 	    if ($role=~/^cr/) { 
1.807     albertel 4249: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4250: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4251: 		    ($tend,$tstart)=split('_',$trest);
                   4252: 		} else {
                   4253: 		    $trole=$role;
                   4254: 		}
1.678     raeburn  4255:             } elsif ($role =~ m|^gr/|) {
                   4256:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4257:                 ($trole,$group_privs) = split(/\//,$trole);
                   4258:                 $group_privs = &unescape($group_privs);
1.587     albertel 4259: 	    } else {
                   4260: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4261: 	    }
1.743     albertel 4262: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4263: 					 $username);
                   4264: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4265:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4266:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4267:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4268: 		my $spec=$trole.'.'.$area;
                   4269: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4270: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4271:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4272:                 } elsif ($trole eq 'gr') {
                   4273:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4274: 		} else {
1.567     raeburn  4275:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4276: 		}
1.12      www      4277:             }
1.662     raeburn  4278:           }
1.191     harris41 4279:         }
1.743     albertel 4280:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4281:         $userroles{'user.adv'}    = $adv;
                   4282: 	$userroles{'user.author'} = $author;
1.620     albertel 4283:         $env{'user.adv'}=$adv;
1.11      www      4284:     }
1.743     albertel 4285:     return \%userroles;  
1.11      www      4286: }
                   4287: 
1.567     raeburn  4288: sub set_arearole {
                   4289:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4290: # log the associated role with the area
                   4291:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4292:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4293: }
                   4294: 
                   4295: sub custom_roleprivs {
                   4296:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4297:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4298:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4299:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4300:         my ($rdummy,$roledef)=
                   4301:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4302:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4303:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4304:             if (defined($syspriv)) {
1.1043    raeburn  4305:                 if ($trest =~ /^$match_community$/) {
                   4306:                     $syspriv =~ s/bre\&S//; 
                   4307:                 }
1.567     raeburn  4308:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4309:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4310:             }
                   4311:             if ($tdomain ne '') {
                   4312:                 if (defined($dompriv)) {
                   4313:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4314:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4315:                 }
                   4316:                 if (($trest ne '') && (defined($coursepriv))) {
                   4317:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4318:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4319:                 }
                   4320:             }
                   4321:         }
                   4322:     }
                   4323: }
                   4324: 
1.678     raeburn  4325: sub group_roleprivs {
                   4326:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4327:     my $access = 1;
                   4328:     my $now = time;
                   4329:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4330:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4331:     if ($access) {
1.811     albertel 4332:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4333:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4334:     }
                   4335: }
1.567     raeburn  4336: 
                   4337: sub standard_roleprivs {
                   4338:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4339:     if (defined($pr{$trole.':s'})) {
                   4340:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4341:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4342:     }
                   4343:     if ($tdomain ne '') {
                   4344:         if (defined($pr{$trole.':d'})) {
                   4345:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4346:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4347:         }
                   4348:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4349:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4350:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4351:         }
                   4352:     }
                   4353: }
                   4354: 
                   4355: sub set_userprivs {
1.1056.4.2  raeburn  4356:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4357:     my $author=0;
                   4358:     my $adv=0;
1.678     raeburn  4359:     my %grouproles = ();
                   4360:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4361:         my @groupkeys;
1.1000    raeburn  4362:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4363:             push(@groupkeys,$role);
                   4364:         }
                   4365:         if (ref($groups_roles) eq 'HASH') {
                   4366:             foreach my $key (keys(%{$groups_roles})) {
                   4367:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4368:                     push(@groupkeys,$key);
                   4369:                 }
                   4370:             }
                   4371:         }
                   4372:         if (@groupkeys > 0) {
                   4373:             foreach my $role (@groupkeys) {
                   4374:                 my ($trole,$area,$sec,$extendedarea);
                   4375:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4376:                     $trole = $1;
                   4377:                     $area = $2;
                   4378:                     $sec = $3;
                   4379:                     $extendedarea = $area.$sec;
                   4380:                     if (exists($$allgroups{$area})) {
                   4381:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4382:                             my $spec = $trole.'.'.$extendedarea;
                   4383:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4384:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4385:                         }
1.678     raeburn  4386:                     }
                   4387:                 }
                   4388:             }
                   4389:         }
                   4390:     }
1.800     albertel 4391:     foreach my $group (keys(%grouproles)) {
                   4392:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4393:     }
1.800     albertel 4394:     foreach my $role (keys(%{$allroles})) {
                   4395:         my %thesepriv;
1.941     raeburn  4396:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4397:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4398:             if ($item ne '') {
                   4399:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4400:                 if ($restrictions eq '') {
                   4401:                     $thesepriv{$privilege}='F';
                   4402:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4403:                     $thesepriv{$privilege}.=$restrictions;
                   4404:                 }
                   4405:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4406:             }
                   4407:         }
                   4408:         my $thesestr='';
1.800     albertel 4409:         foreach my $priv (keys(%thesepriv)) {
                   4410: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4411: 	}
                   4412:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4413:     }
                   4414:     return ($author,$adv);
                   4415: }
                   4416: 
1.994     raeburn  4417: sub role_status {
1.1002    raeburn  4418:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4419:     my @pwhere = ();
                   4420:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4421:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4422:         unless (!defined($$role) || $$role eq '') {
                   4423:             $$where=join('.',@pwhere);
                   4424:             $$trolecode=$$role.'.'.$$where;
                   4425:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4426:             $$tstatus='is';
                   4427:             if ($$tstart && $$tstart>$then) {
                   4428:                 $$tstatus='future';
1.1034    raeburn  4429:                 if ($$tstart<$now) {
                   4430:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4431:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4432:                             my (%allroles,%allgroups,$group_privs,
                   4433:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4434:                             my %userroles = (
                   4435:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4436:                             );
1.1056.4.2  raeburn  4437:                             @rolecodes = ('cm');
1.1002    raeburn  4438:                             my $spec=$$role.'.'.$$where;
                   4439:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4440:                             if ($$role =~ /^cr\//) {
                   4441:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4442:                                 push(@rolecodes,'cr');
1.1002    raeburn  4443:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4444:                                 push(@rolecodes,$$role);
1.1002    raeburn  4445:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4446:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4447:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4448:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4449:                                 $group_privs = &unescape($group_privs);
                   4450:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4451:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4452:                                 if (keys(%course_roles) > 0) {
                   4453:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4454:                                     if ($tdomain ne '' && $tnum ne '') {
                   4455:                                         foreach my $key (keys(%course_roles)) {
                   4456:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4457:                                                 my $crsrole = $1;
                   4458:                                                 my $crssec = $2;
                   4459:                                                 if ($crsrole =~ /^cr/) {
                   4460:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4461:                                                         push(@rolecodes,'cr');
                   4462:                                                     }
                   4463:                                                 } else {
                   4464:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4465:                                                         push(@rolecodes,$crsrole);
                   4466:                                                     }
                   4467:                                                 }
                   4468:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4469:                                                 if ($crssec ne '') {
                   4470:                                                     $rolekey .= '/'.$crssec;
                   4471:                                                 }
                   4472:                                                 $rolekey .= './';
                   4473:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4474:                                             }
                   4475:                                         }
                   4476:                                     }
                   4477:                                 }
1.1002    raeburn  4478:                             } else {
1.1056.4.2  raeburn  4479:                                 push(@rolecodes,$$role);
1.1002    raeburn  4480:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4481:                             }
1.1056.4.2  raeburn  4482:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4483:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4484:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4485:                         }
                   4486:                     }
1.1034    raeburn  4487:                     $$tstatus = 'is';
1.1002    raeburn  4488:                 }
1.994     raeburn  4489:             }
                   4490:             if ($$tend) {
                   4491:                 if ($$tend<$then) {
                   4492:                     $$tstatus='expired';
                   4493:                 } elsif ($$tend<$now) {
                   4494:                     $$tstatus='will_not';
                   4495:                 }
                   4496:             }
                   4497:         }
                   4498:     }
                   4499: }
                   4500: 
                   4501: sub check_adhoc_privs {
1.1056.4.12  raeburn  4502:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4503:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4504:     if ($env{$cckey}) {
                   4505:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4506:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4507:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4508:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4509:         }
                   4510:     } else {
1.1056.4.12  raeburn  4511:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4512:     }
                   4513: }
                   4514: 
                   4515: sub set_adhoc_privileges {
                   4516: # role can be cc or ca
1.1056.4.12  raeburn  4517:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4518:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4519:     my $spec = $role.'.'.$area;
                   4520:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4521:                                   $env{'user.name'});
                   4522:     my %ccrole = ();
                   4523:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4524:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4525:     &appenv(\%userroles,[$role,'cm']);
                   4526:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4527:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4528:         &appenv( {'request.role'        => $spec,
                   4529:                   'request.role.domain' => $dcdom,
                   4530:                   'request.course.sec'  => ''
                   4531:                  }
                   4532:                );
                   4533:         my $tadv=0;
                   4534:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4535:         &appenv({'request.role.adv'    => $tadv});
                   4536:     }
1.994     raeburn  4537: }
                   4538: 
1.12      www      4539: # --------------------------------------------------------------- get interface
                   4540: 
                   4541: sub get {
1.131     albertel 4542:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4543:    my $items='';
1.800     albertel 4544:    foreach my $item (@$storearr) {
                   4545:        $items.=&escape($item).'&';
1.191     harris41 4546:    }
1.12      www      4547:    $items=~s/\&$//;
1.620     albertel 4548:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4549:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4550:    my $uhome=&homeserver($uname,$udomain);
                   4551: 
1.133     albertel 4552:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4553:    my @pairs=split(/\&/,$rep);
1.273     albertel 4554:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4555:      return @pairs;
                   4556:    }
1.15      www      4557:    my %returnhash=();
1.42      www      4558:    my $i=0;
1.800     albertel 4559:    foreach my $item (@$storearr) {
                   4560:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4561:       $i++;
1.191     harris41 4562:    }
1.15      www      4563:    return %returnhash;
1.27      www      4564: }
                   4565: 
                   4566: # --------------------------------------------------------------- del interface
                   4567: 
                   4568: sub del {
1.133     albertel 4569:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4570:    my $items='';
1.800     albertel 4571:    foreach my $item (@$storearr) {
                   4572:        $items.=&escape($item).'&';
1.191     harris41 4573:    }
1.984     neumanie 4574: 
1.27      www      4575:    $items=~s/\&$//;
1.620     albertel 4576:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4577:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4578:    my $uhome=&homeserver($uname,$udomain);
                   4579:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4580: }
                   4581: 
                   4582: # -------------------------------------------------------------- dump interface
                   4583: 
                   4584: sub dump {
1.1056.4.10  raeburn  4585:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4586:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4587:     if (!$uname) { $uname=$env{'user.name'}; }
                   4588:     my $uhome=&homeserver($uname,$udomain);
                   4589:     if ($regexp) {
                   4590: 	$regexp=&escape($regexp);
                   4591:     } else {
                   4592: 	$regexp='.';
                   4593:     }
1.1056.4.10  raeburn  4594:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4595:     my @pairs=split(/\&/,$rep);
                   4596:     my %returnhash=();
                   4597:     foreach my $item (@pairs) {
                   4598: 	my ($key,$value)=split(/=/,$item,2);
                   4599: 	$key = &unescape($key);
                   4600: 	next if ($key =~ /^error: 2 /);
                   4601: 	$returnhash{$key}=&thaw_unescape($value);
                   4602:     }
                   4603:     return %returnhash;
1.407     www      4604: }
                   4605: 
1.717     albertel 4606: # --------------------------------------------------------- dumpstore interface
                   4607: 
                   4608: sub dumpstore {
                   4609:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4610:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4611:    if (!$uname) { $uname=$env{'user.name'}; }
                   4612:    my $uhome=&homeserver($uname,$udomain);
                   4613:    if ($regexp) {
                   4614:        $regexp=&escape($regexp);
                   4615:    } else {
                   4616:        $regexp='.';
                   4617:    }
                   4618:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4619:    my @pairs=split(/\&/,$rep);
                   4620:    my %returnhash=();
                   4621:    foreach my $item (@pairs) {
                   4622:        my ($key,$value)=split(/=/,$item,2);
                   4623:        next if ($key =~ /^error: 2 /);
                   4624:        $returnhash{$key}=&thaw_unescape($value);
                   4625:    }
                   4626:    return %returnhash;
1.717     albertel 4627: }
                   4628: 
1.407     www      4629: # -------------------------------------------------------------- keys interface
                   4630: 
                   4631: sub getkeys {
                   4632:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4633:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4634:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4635:    my $uhome=&homeserver($uname,$udomain);
                   4636:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4637:    my @keyarray=();
1.800     albertel 4638:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4639:       next if ($key =~ /^error: 2 /);
1.800     albertel 4640:       push(@keyarray,&unescape($key));
1.407     www      4641:    }
                   4642:    return @keyarray;
1.318     matthew  4643: }
                   4644: 
1.319     matthew  4645: # --------------------------------------------------------------- currentdump
                   4646: sub currentdump {
1.328     matthew  4647:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4648:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4649:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4650:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4651:    my $uhome = &homeserver($sname,$sdom);
                   4652:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4653:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4654:    #
1.318     matthew  4655:    my %returnhash=();
1.319     matthew  4656:    #
                   4657:    if ($rep eq "unknown_cmd") { 
                   4658:        # an old lond will not know currentdump
                   4659:        # Do a dump and make it look like a currentdump
1.822     albertel 4660:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4661:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4662:        my %hash = @tmp;
                   4663:        @tmp=();
1.424     matthew  4664:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4665:    } else {
                   4666:        my @pairs=split(/\&/,$rep);
1.800     albertel 4667:        foreach my $pair (@pairs) {
                   4668:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4669:            my ($symb,$param) = split(/:/,$key);
                   4670:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4671:                                                         &thaw_unescape($value);
1.319     matthew  4672:        }
1.191     harris41 4673:    }
1.12      www      4674:    return %returnhash;
1.424     matthew  4675: }
                   4676: 
                   4677: sub convert_dump_to_currentdump{
                   4678:     my %hash = %{shift()};
                   4679:     my %returnhash;
                   4680:     # Code ripped from lond, essentially.  The only difference
                   4681:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4682:     # we might run in to problems with parameter names =~ /^v\./
                   4683:     while (my ($key,$value) = each(%hash)) {
                   4684:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4685: 	$symb  = &unescape($symb);
                   4686: 	$param = &unescape($param);
1.424     matthew  4687:         next if ($v eq 'version' || $symb eq 'keys');
                   4688:         next if (exists($returnhash{$symb}) &&
                   4689:                  exists($returnhash{$symb}->{$param}) &&
                   4690:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4691:         $returnhash{$symb}->{$param}=$value;
                   4692:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4693:     }
                   4694:     #
                   4695:     # Remove all of the keys in the hashes which keep track of
                   4696:     # the version of the parameter.
                   4697:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4698:         # use a foreach because we are going to delete from the hash.
                   4699:         foreach my $key (keys(%$param_hash)) {
                   4700:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4701:         }
                   4702:     }
                   4703:     return \%returnhash;
1.12      www      4704: }
                   4705: 
1.627     albertel 4706: # ------------------------------------------------------ critical inc interface
                   4707: 
                   4708: sub cinc {
                   4709:     return &inc(@_,'critical');
                   4710: }
                   4711: 
1.449     matthew  4712: # --------------------------------------------------------------- inc interface
                   4713: 
                   4714: sub inc {
1.627     albertel 4715:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4716:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4717:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4718:     my $uhome=&homeserver($uname,$udomain);
                   4719:     my $items='';
                   4720:     if (! ref($store)) {
                   4721:         # got a single value, so use that instead
                   4722:         $items = &escape($store).'=&';
                   4723:     } elsif (ref($store) eq 'SCALAR') {
                   4724:         $items = &escape($$store).'=&';        
                   4725:     } elsif (ref($store) eq 'ARRAY') {
                   4726:         $items = join('=&',map {&escape($_);} @{$store});
                   4727:     } elsif (ref($store) eq 'HASH') {
                   4728:         while (my($key,$value) = each(%{$store})) {
                   4729:             $items.= &escape($key).'='.&escape($value).'&';
                   4730:         }
                   4731:     }
                   4732:     $items=~s/\&$//;
1.627     albertel 4733:     if ($critical) {
                   4734: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4735:     } else {
                   4736: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4737:     }
1.449     matthew  4738: }
                   4739: 
1.12      www      4740: # --------------------------------------------------------------- put interface
                   4741: 
                   4742: sub put {
1.134     albertel 4743:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4744:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4745:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4746:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4747:    my $items='';
1.800     albertel 4748:    foreach my $item (keys(%$storehash)) {
                   4749:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4750:    }
1.12      www      4751:    $items=~s/\&$//;
1.134     albertel 4752:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4753: }
                   4754: 
1.631     albertel 4755: # ------------------------------------------------------------ newput interface
                   4756: 
                   4757: sub newput {
                   4758:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4760:    if (!$uname) { $uname=$env{'user.name'}; }
                   4761:    my $uhome=&homeserver($uname,$udomain);
                   4762:    my $items='';
                   4763:    foreach my $key (keys(%$storehash)) {
                   4764:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4765:    }
                   4766:    $items=~s/\&$//;
                   4767:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4768: }
                   4769: 
                   4770: # ---------------------------------------------------------  putstore interface
                   4771: 
1.524     raeburn  4772: sub putstore {
1.715     albertel 4773:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4775:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4776:    my $uhome=&homeserver($uname,$udomain);
                   4777:    my $items='';
1.715     albertel 4778:    foreach my $key (keys(%$storehash)) {
                   4779:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4780:    }
1.715     albertel 4781:    $items=~s/\&$//;
1.716     albertel 4782:    my $esc_symb=&escape($symb);
                   4783:    my $esc_v=&escape($version);
1.715     albertel 4784:    my $reply =
1.716     albertel 4785:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4786: 	      $uhome);
                   4787:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4788:        # gfall back to way things use to be done
1.715     albertel 4789:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4790: 			    $uname);
1.524     raeburn  4791:    }
1.715     albertel 4792:    return $reply;
                   4793: }
                   4794: 
                   4795: sub old_putstore {
1.716     albertel 4796:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4797:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4798:     if (!$uname) { $uname=$env{'user.name'}; }
                   4799:     my $uhome=&homeserver($uname,$udomain);
                   4800:     my %newstorehash;
1.800     albertel 4801:     foreach my $item (keys(%$storehash)) {
                   4802: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4803: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4804:     }
                   4805:     my $items='';
                   4806:     my %allitems = ();
1.800     albertel 4807:     foreach my $item (keys(%newstorehash)) {
                   4808: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4809: 	    my $key = $1.':keys:'.$2;
                   4810: 	    $allitems{$key} .= $3.':';
                   4811: 	}
1.800     albertel 4812: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4813:     }
1.800     albertel 4814:     foreach my $item (keys(%allitems)) {
                   4815: 	$allitems{$item} =~ s/\:$//;
                   4816: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4817:     }
                   4818:     $items=~s/\&$//;
                   4819:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4820: }
                   4821: 
1.47      www      4822: # ------------------------------------------------------ critical put interface
                   4823: 
                   4824: sub cput {
1.134     albertel 4825:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4827:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4828:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4829:    my $items='';
1.800     albertel 4830:    foreach my $item (keys(%$storehash)) {
                   4831:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4832:    }
1.47      www      4833:    $items=~s/\&$//;
1.134     albertel 4834:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4835: }
                   4836: 
                   4837: # -------------------------------------------------------------- eget interface
                   4838: 
                   4839: sub eget {
1.133     albertel 4840:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4841:    my $items='';
1.800     albertel 4842:    foreach my $item (@$storearr) {
                   4843:        $items.=&escape($item).'&';
1.191     harris41 4844:    }
1.12      www      4845:    $items=~s/\&$//;
1.620     albertel 4846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4847:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4848:    my $uhome=&homeserver($uname,$udomain);
                   4849:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4850:    my @pairs=split(/\&/,$rep);
                   4851:    my %returnhash=();
1.42      www      4852:    my $i=0;
1.800     albertel 4853:    foreach my $item (@$storearr) {
                   4854:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4855:       $i++;
1.191     harris41 4856:    }
1.12      www      4857:    return %returnhash;
                   4858: }
                   4859: 
1.667     albertel 4860: # ------------------------------------------------------------ tmpput interface
                   4861: sub tmpput {
1.802     raeburn  4862:     my ($storehash,$server,$context)=@_;
1.667     albertel 4863:     my $items='';
1.800     albertel 4864:     foreach my $item (keys(%$storehash)) {
                   4865: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4866:     }
                   4867:     $items=~s/\&$//;
1.802     raeburn  4868:     if (defined($context)) {
                   4869:         $items .= ':'.&escape($context);
                   4870:     }
1.667     albertel 4871:     return &reply("tmpput:$items",$server);
                   4872: }
                   4873: 
                   4874: # ------------------------------------------------------------ tmpget interface
                   4875: sub tmpget {
1.688     albertel 4876:     my ($token,$server)=@_;
                   4877:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4878:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4879:     my %returnhash;
                   4880:     foreach my $item (split(/\&/,$rep)) {
                   4881: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4882:         next if ($key =~ /^error: 2 /);
1.667     albertel 4883: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4884:     }
                   4885:     return %returnhash;
                   4886: }
                   4887: 
1.688     albertel 4888: # ------------------------------------------------------------ tmpget interface
                   4889: sub tmpdel {
                   4890:     my ($token,$server)=@_;
                   4891:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4892:     return &reply("tmpdel:$token",$server);
                   4893: }
                   4894: 
1.765     albertel 4895: # -------------------------------------------------- portfolio access checking
                   4896: 
                   4897: sub portfolio_access {
1.766     albertel 4898:     my ($requrl) = @_;
1.765     albertel 4899:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4900:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4901:     if ($result) {
                   4902:         my %setters;
                   4903:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4904:             my ($startblock,$endblock) =
                   4905:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4906:             if ($startblock && $endblock) {
                   4907:                 return 'B';
                   4908:             }
                   4909:         } else {
                   4910:             my ($startblock,$endblock) =
                   4911:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4912:             if ($startblock && $endblock) {
                   4913:                 return 'B';
                   4914:             }
                   4915:         }
                   4916:     }
1.765     albertel 4917:     if ($result eq 'ok') {
1.766     albertel 4918:        return 'F';
1.765     albertel 4919:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4920:        return 'A';
1.765     albertel 4921:     }
1.766     albertel 4922:     return '';
1.765     albertel 4923: }
                   4924: 
                   4925: sub get_portfolio_access {
1.767     albertel 4926:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4927: 
                   4928:     if (!ref($access_hash)) {
                   4929: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4930: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4931: 						   $file_name);
                   4932: 	$access_hash = $access_controls{$file_name};
                   4933:     }
                   4934: 
1.765     albertel 4935:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4936:     my $now = time;
                   4937:     if (ref($access_hash) eq 'HASH') {
                   4938:         foreach my $key (keys(%{$access_hash})) {
                   4939:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4940:             if ($start > $now) {
                   4941:                 next;
                   4942:             }
                   4943:             if ($end && $end<$now) {
                   4944:                 next;
                   4945:             }
                   4946:             if ($scope eq 'public') {
                   4947:                 $public = $key;
                   4948:                 last;
                   4949:             } elsif ($scope eq 'guest') {
                   4950:                 $guest = $key;
                   4951:             } elsif ($scope eq 'domains') {
                   4952:                 push(@domains,$key);
                   4953:             } elsif ($scope eq 'users') {
                   4954:                 push(@users,$key);
                   4955:             } elsif ($scope eq 'course') {
                   4956:                 push(@courses,$key);
                   4957:             } elsif ($scope eq 'group') {
                   4958:                 push(@groups,$key);
                   4959:             }
                   4960:         }
                   4961:         if ($public) {
                   4962:             return 'ok';
                   4963:         }
                   4964:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4965:             if ($guest) {
                   4966:                 return $guest;
                   4967:             }
                   4968:         } else {
                   4969:             if (@domains > 0) {
                   4970:                 foreach my $domkey (@domains) {
                   4971:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4972:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4973:                             return 'ok';
                   4974:                         }
                   4975:                     }
                   4976:                 }
                   4977:             }
                   4978:             if (@users > 0) {
                   4979:                 foreach my $userkey (@users) {
1.865     raeburn  4980:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4981:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4982:                             if (ref($item) eq 'HASH') {
                   4983:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4984:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4985:                                     return 'ok';
                   4986:                                 }
                   4987:                             }
                   4988:                         }
                   4989:                     } 
1.765     albertel 4990:                 }
                   4991:             }
                   4992:             my %roleshash;
                   4993:             my @courses_and_groups = @courses;
                   4994:             push(@courses_and_groups,@groups); 
                   4995:             if (@courses_and_groups > 0) {
                   4996:                 my (%allgroups,%allroles); 
                   4997:                 my ($start,$end,$role,$sec,$group);
                   4998:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4999:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5000:                         my $cid = $2.'_'.$3; 
                   5001:                         if ($1 eq 'gr') {
                   5002:                             $group = $4;
                   5003:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5004:                         } else {
                   5005:                             if ($4 eq '') {
                   5006:                                 $sec = 'none';
                   5007:                             } else {
                   5008:                                 $sec = $4;
                   5009:                             }
                   5010:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5011:                         }
1.811     albertel 5012:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5013:                         my $cid = $2.'_'.$3;
                   5014:                         if ($4 eq '') {
                   5015:                             $sec = 'none';
                   5016:                         } else {
                   5017:                             $sec = $4;
                   5018:                         }
                   5019:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5020:                     }
                   5021:                 }
                   5022:                 if (keys(%allroles) == 0) {
                   5023:                     return;
                   5024:                 }
                   5025:                 foreach my $key (@courses_and_groups) {
                   5026:                     my %content = %{$$access_hash{$key}};
                   5027:                     my $cnum = $content{'number'};
                   5028:                     my $cdom = $content{'domain'};
                   5029:                     my $cid = $cdom.'_'.$cnum;
                   5030:                     if (!exists($allroles{$cid})) {
                   5031:                         next;
                   5032:                     }    
                   5033:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5034:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5035:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5036:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5037:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5038:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5039:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5040:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5041:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5042:                                         if (grep/^all$/,@sections) {
                   5043:                                             return 'ok';
                   5044:                                         } else {
                   5045:                                             if (grep/^$sec$/,@sections) {
                   5046:                                                 return 'ok';
                   5047:                                             }
                   5048:                                         }
                   5049:                                     }
                   5050:                                 }
                   5051:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5052:                                     if (grep/^none$/,@groups) {
                   5053:                                         return 'ok';
                   5054:                                     }
                   5055:                                 } else {
                   5056:                                     if (grep/^all$/,@groups) {
                   5057:                                         return 'ok';
                   5058:                                     } 
                   5059:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5060:                                         if (grep/^$group$/,@groups) {
                   5061:                                             return 'ok';
                   5062:                                         }
                   5063:                                     }
                   5064:                                 } 
                   5065:                             }
                   5066:                         }
                   5067:                     }
                   5068:                 }
                   5069:             }
                   5070:             if ($guest) {
                   5071:                 return $guest;
                   5072:             }
                   5073:         }
                   5074:     }
                   5075:     return;
                   5076: }
                   5077: 
                   5078: sub course_group_datechecker {
                   5079:     my ($dates,$now,$status) = @_;
                   5080:     my ($start,$end) = split(/\./,$dates);
                   5081:     if (!$start && !$end) {
                   5082:         return 'ok';
                   5083:     }
                   5084:     if (grep/^active$/,@{$status}) {
                   5085:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5086:             return 'ok';
                   5087:         }
                   5088:     }
                   5089:     if (grep/^previous$/,@{$status}) {
                   5090:         if ($end > $now ) {
                   5091:             return 'ok';
                   5092:         }
                   5093:     }
                   5094:     if (grep/^future$/,@{$status}) {
                   5095:         if ($start > $now) {
                   5096:             return 'ok';
                   5097:         }
                   5098:     }
                   5099:     return; 
                   5100: }
                   5101: 
                   5102: sub parse_portfolio_url {
                   5103:     my ($url) = @_;
                   5104: 
                   5105:     my ($type,$udom,$unum,$group,$file_name);
                   5106:     
1.823     albertel 5107:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5108: 	$type = 1;
                   5109:         $udom = $1;
                   5110:         $unum = $2;
                   5111:         $file_name = $3;
1.823     albertel 5112:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5113: 	$type = 2;
                   5114:         $udom = $1;
                   5115:         $unum = $2;
                   5116:         $group = $3;
                   5117:         $file_name = $3.'/'.$4;
                   5118:     }
                   5119:     if (wantarray) {
                   5120: 	return ($type,$udom,$unum,$file_name,$group);
                   5121:     }
                   5122:     return $type;
                   5123: }
                   5124: 
                   5125: sub is_portfolio_url {
                   5126:     my ($url) = @_;
                   5127:     return scalar(&parse_portfolio_url($url));
                   5128: }
                   5129: 
1.798     raeburn  5130: sub is_portfolio_file {
                   5131:     my ($file) = @_;
1.820     raeburn  5132:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5133:         return 1;
                   5134:     }
                   5135:     return;
                   5136: }
                   5137: 
1.976     raeburn  5138: sub usertools_access {
1.1056.4.9  raeburn  5139:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5140:     my ($access,%tools);
                   5141:     if ($context eq '') {
                   5142:         $context = 'tools';
                   5143:     }
                   5144:     if ($context eq 'requestcourses') {
                   5145:         %tools = (
                   5146:                       official   => 1,
                   5147:                       unofficial => 1,
1.1006    raeburn  5148:                       community  => 1,
1.985     raeburn  5149:                  );
                   5150:     } else {
                   5151:         %tools = (
                   5152:                       aboutme   => 1,
                   5153:                       blog      => 1,
                   5154:                       portfolio => 1,
                   5155:                  );
                   5156:     }
1.976     raeburn  5157:     return if (!defined($tools{$tool}));
                   5158: 
                   5159:     if ((!defined($udom)) || (!defined($uname))) {
                   5160:         $udom = $env{'user.domain'};
                   5161:         $uname = $env{'user.name'};
                   5162:     }
                   5163: 
1.978     raeburn  5164:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5165:         if ($action ne 'reload') {
1.985     raeburn  5166:             if ($context eq 'requestcourses') {
                   5167:                 return $env{'environment.canrequest.'.$tool};
                   5168:             } else {
                   5169:                 return $env{'environment.availabletools.'.$tool};
                   5170:             }
                   5171:         }
1.976     raeburn  5172:     }
                   5173: 
                   5174:     my ($toolstatus,$inststatus);
                   5175: 
1.985     raeburn  5176:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5177:          ($action ne 'reload')) {
                   5178:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5179:         $inststatus = $env{'environment.inststatus'};
                   5180:     } else {
1.1056.4.9  raeburn  5181:         if (ref($userenvref) eq 'HASH') {
                   5182:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5183:             $inststatus = $userenvref->{'inststatus'};
                   5184:         } else {
                   5185:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5186:             $toolstatus = $userenv{$context.'.'.$tool};
                   5187:             $inststatus = $userenv{'inststatus'};
                   5188:         }
1.976     raeburn  5189:     }
                   5190: 
                   5191:     if ($toolstatus ne '') {
                   5192:         if ($toolstatus) {
                   5193:             $access = 1;
                   5194:         } else {
                   5195:             $access = 0;
                   5196:         }
                   5197:         return $access;
                   5198:     }
                   5199: 
1.1056.4.9  raeburn  5200:     my ($is_adv,%domdef);
                   5201:     if (ref($is_advref) eq 'HASH') {
                   5202:         $is_adv = $is_advref->{'is_adv'};
                   5203:     } else {
                   5204:         $is_adv = &is_advanced_user($udom,$uname);
                   5205:     }
                   5206:     if (ref($domdefref) eq 'HASH') {
                   5207:         %domdef = %{$domdefref};
                   5208:     } else {
                   5209:         %domdef = &get_domain_defaults($udom);
                   5210:     }
1.976     raeburn  5211:     if (ref($domdef{$tool}) eq 'HASH') {
                   5212:         if ($is_adv) {
                   5213:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5214:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5215:                     $access = 1;
                   5216:                 } else {
                   5217:                     $access = 0;
                   5218:                 }
                   5219:                 return $access;
                   5220:             }
                   5221:         }
                   5222:         if ($inststatus ne '') {
                   5223:             my ($hasaccess,$hasnoaccess);
                   5224:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5225:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5226:                     if ($domdef{$tool}{$affiliation}) {
                   5227:                         $hasaccess = 1;
                   5228:                     } else {
                   5229:                         $hasnoaccess = 1;
                   5230:                     }
                   5231:                 }
                   5232:             }
                   5233:             if ($hasaccess || $hasnoaccess) {
                   5234:                 if ($hasaccess) {
                   5235:                     $access = 1;
                   5236:                 } elsif ($hasnoaccess) {
                   5237:                     $access = 0; 
                   5238:                 }
                   5239:                 return $access;
                   5240:             }
                   5241:         } else {
                   5242:             if ($domdef{$tool}{'default'} ne '') {
                   5243:                 if ($domdef{$tool}{'default'}) {
                   5244:                     $access = 1;
                   5245:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5246:                     $access = 0;
                   5247:                 }
                   5248:                 return $access;
                   5249:             }
                   5250:         }
                   5251:     } else {
1.985     raeburn  5252:         if ($context eq 'tools') {
                   5253:             $access = 1;
                   5254:         } else {
                   5255:             $access = 0;
                   5256:         }
1.976     raeburn  5257:         return $access;
                   5258:     }
                   5259: }
                   5260: 
1.1050    raeburn  5261: sub is_course_owner {
                   5262:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5263:     if (($udom eq '') || ($uname eq '')) {
                   5264:         $udom = $env{'user.domain'};
                   5265:         $uname = $env{'user.name'};
                   5266:     }
                   5267:     unless (($udom eq '') || ($uname eq '')) {
                   5268:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5269:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5270:                 return 1;
                   5271:             } else {
                   5272:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5273:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5274:                     return 1;
                   5275:                 }
                   5276:             }
                   5277:         }
                   5278:     }
                   5279:     return;
                   5280: }
                   5281: 
1.976     raeburn  5282: sub is_advanced_user {
                   5283:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5284:     if ($udom ne '' && $uname ne '') {
                   5285:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5286:             return $env{'user.adv'};
                   5287:         }
                   5288:     }
1.976     raeburn  5289:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5290:     my %allroles;
                   5291:     my $is_adv;
                   5292:     foreach my $role (keys(%roleshash)) {
                   5293:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5294:         my $area = '/'.$tdomain.'/'.$trest;
                   5295:         if ($sec ne '') {
                   5296:             $area .= '/'.$sec;
                   5297:         }
                   5298:         if (($area ne '') && ($trole ne '')) {
                   5299:             my $spec=$trole.'.'.$area;
                   5300:             if ($trole =~ /^cr\//) {
                   5301:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5302:             } elsif ($trole ne 'gr') {
                   5303:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5304:             }
                   5305:         }
                   5306:     }
                   5307:     foreach my $role (keys(%allroles)) {
                   5308:         last if ($is_adv);
                   5309:         foreach my $item (split(/:/,$allroles{$role})) {
                   5310:             if ($item ne '') {
                   5311:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5312:                 if ($privilege eq 'adv') {
                   5313:                     $is_adv = 1;
                   5314:                     last;
                   5315:                 }
                   5316:             }
                   5317:         }
                   5318:     }
                   5319:     return $is_adv;
                   5320: }
1.798     raeburn  5321: 
1.1035    raeburn  5322: sub check_can_request {
1.1036    raeburn  5323:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5324:     my $canreq = 0;
                   5325:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5326:     my @options = ('approval','validate','autolimit');
                   5327:     my $optregex = join('|',@options);
                   5328:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5329:         foreach my $type (@{$types}) {
                   5330:             if (&usertools_access($env{'user.name'},
                   5331:                                   $env{'user.domain'},
                   5332:                                   $type,undef,'requestcourses')) {
                   5333:                 $canreq ++;
1.1036    raeburn  5334:                 if (ref($request_domains) eq 'HASH') {
                   5335:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5336:                 }
1.1035    raeburn  5337:                 if ($dom eq $env{'user.domain'}) {
                   5338:                     $can_request->{$type} = 1;
                   5339:                 }
                   5340:             }
                   5341:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5342:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5343:                 if (@curr > 0) {
1.1036    raeburn  5344:                     foreach my $item (@curr) {
                   5345:                         if (ref($request_domains) eq 'HASH') {
                   5346:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5347:                             if ($otherdom ne '') {
                   5348:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5349:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5350:                                         push(@{$request_domains->{$type}},$otherdom);
                   5351:                                     }
                   5352:                                 } else {
                   5353:                                     push(@{$request_domains->{$type}},$otherdom);
                   5354:                                 }
                   5355:                             }
                   5356:                         }
                   5357:                     }
                   5358:                     unless($dom eq $env{'user.domain'}) {
                   5359:                         $canreq ++;
1.1035    raeburn  5360:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5361:                             $can_request->{$type} = 1;
                   5362:                         }
                   5363:                     }
                   5364:                 }
                   5365:             }
                   5366:         }
                   5367:     }
                   5368:     return $canreq;
                   5369: }
                   5370: 
1.341     www      5371: # ---------------------------------------------- Custom access rule evaluation
                   5372: 
                   5373: sub customaccess {
                   5374:     my ($priv,$uri)=@_;
1.807     albertel 5375:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5376:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5377:     $udom = &LONCAPA::clean_domain($udom);
                   5378:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5379:     my $access=0;
1.800     albertel 5380:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5381: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5382: 	if ($type eq 'user') {
                   5383: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5384: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5385: 		if ($tdom) {
                   5386: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5387: 		}
1.896     albertel 5388: 		if ($tuname) {
                   5389: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5390: 		}
                   5391: 		$access=($effect eq 'allow');
                   5392: 		last;
                   5393: 	    }
                   5394: 	} else {
                   5395: 	    if ($role) {
                   5396: 		if ($role ne $urole) { next; }
                   5397: 	    }
                   5398: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5399: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5400: 		if ($tdom) {
                   5401: 		    if ($tdom ne $udom) { next; }
                   5402: 		}
                   5403: 		if ($tcrs) {
                   5404: 		    if ($tcrs ne $ucrs) { next; }
                   5405: 		}
                   5406: 		if ($tsec) {
                   5407: 		    if ($tsec ne $usec) { next; }
                   5408: 		}
                   5409: 		$access=($effect eq 'allow');
                   5410: 		last;
                   5411: 	    }
                   5412: 	    if ($realm eq '' && $role eq '') {
                   5413: 		$access=($effect eq 'allow');
                   5414: 	    }
1.402     bowersj2 5415: 	}
1.341     www      5416:     }
                   5417:     return $access;
                   5418: }
                   5419: 
1.103     harris41 5420: # ------------------------------------------------- Check for a user privilege
1.12      www      5421: 
                   5422: sub allowed {
1.810     raeburn  5423:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5424:     my $ver_orguri=$uri;
1.439     www      5425:     $uri=&deversion($uri);
1.152     www      5426:     my $orguri=$uri;
1.52      www      5427:     $uri=&declutter($uri);
1.809     raeburn  5428: 
1.810     raeburn  5429:     if ($priv eq 'evb') {
                   5430: # Evade communication block restrictions for specified role in a course
                   5431:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5432:             return $1;
                   5433:         } else {
                   5434:             return;
                   5435:         }
                   5436:     }
                   5437: 
1.620     albertel 5438:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5439: # Free bre access to adm and meta resources
1.775     albertel 5440:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5441: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5442: 	&& ($priv eq 'bre')) {
1.14      www      5443: 	return 'F';
1.159     www      5444:     }
                   5445: 
1.545     banghart 5446: # Free bre access to user's own portfolio contents
1.714     raeburn  5447:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5448:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5449: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5450:         my %setters;
                   5451:         my ($startblock,$endblock) = 
                   5452:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5453:         if ($startblock && $endblock) {
                   5454:             return 'B';
                   5455:         } else {
                   5456:             return 'F';
                   5457:         }
1.545     banghart 5458:     }
                   5459: 
1.762     raeburn  5460: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5461:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5462:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5463:         if (exists($env{'request.course.id'})) {
                   5464:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5465:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5466:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5467:                 my $courseprivid=$env{'request.course.id'};
                   5468:                 $courseprivid=~s/\_/\//;
                   5469:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5470:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5471:                     return $1; 
1.762     raeburn  5472:                 } else {
                   5473:                     if ($env{'request.course.sec'}) {
                   5474:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5475:                     }
                   5476:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5477:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5478:                         return $2;
                   5479:                     }
1.714     raeburn  5480:                 }
                   5481:             }
                   5482:         }
                   5483:     }
                   5484: 
1.159     www      5485: # Free bre to public access
                   5486: 
                   5487:     if ($priv eq 'bre') {
1.238     www      5488:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5489: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5490:            return 'F'; 
                   5491:         }
1.238     www      5492:         if ($copyright eq 'priv') {
                   5493:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5494: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5495: 		return '';
                   5496:             }
                   5497:         }
                   5498:         if ($copyright eq 'domain') {
                   5499:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5500: 	    unless (($env{'user.domain'} eq $1) ||
                   5501:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5502: 		return '';
                   5503:             }
1.262     matthew  5504:         }
1.620     albertel 5505:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5506:             # Library role, so allow browsing of resources in this domain.
                   5507:             return 'F';
1.238     www      5508:         }
1.341     www      5509:         if ($copyright eq 'custom') {
                   5510: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5511:         }
1.14      www      5512:     }
1.264     matthew  5513:     # Domain coordinator is trying to create a course
1.620     albertel 5514:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5515:         # uri is the requested domain in this case.
                   5516:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5517:         # a role of dc for the domain in question.
1.620     albertel 5518:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5519:     }
1.29      www      5520: 
1.52      www      5521:     my $thisallowed='';
                   5522:     my $statecond=0;
                   5523:     my $courseprivid='';
                   5524: 
1.1039    raeburn  5525:     my $ownaccess;
1.1043    raeburn  5526:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5527:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5528:         if ($uri eq '') {
                   5529:             $ownaccess = 1;
                   5530:         } else {
                   5531:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5532:                 my $udom = $env{'user.domain'};
                   5533:                 my $uname = $env{'user.name'};
                   5534:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5535:                     $ownaccess = 1;
1.1040    raeburn  5536:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5537:                     unless ($uri =~ m{\.\./}) {
                   5538:                         $ownaccess = 1;
                   5539:                     }
                   5540:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5541:                     my $now = time;
                   5542:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5543:                         my $adom = $1;
                   5544:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5545:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5546:                                 my ($start,$end) = split('.',$env{$key});
                   5547:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5548:                                     $ownaccess = 1;
                   5549:                                     last;
                   5550:                                 }
                   5551:                             }
                   5552:                         }
                   5553:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5554:                         my $adom = $1;
                   5555:                         my $aname = $2;
1.1042    raeburn  5556:                         foreach my $role ('ca','aa') { 
                   5557:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5558:                                 my ($start,$end) =
                   5559:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5560:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5561:                                     $ownaccess = 1;
                   5562:                                     last;
                   5563:                                 }
1.1039    raeburn  5564:                             }
                   5565:                         }
                   5566:                     }
                   5567:                 }
                   5568:             }
                   5569:         }
                   5570:     }
                   5571: 
1.52      www      5572: # Course
                   5573: 
1.620     albertel 5574:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5575:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5576:             $thisallowed.=$1;
                   5577:         }
1.52      www      5578:     }
1.29      www      5579: 
1.52      www      5580: # Domain
                   5581: 
1.620     albertel 5582:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5583:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5584:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5585:             $thisallowed.=$1;
                   5586:         }
1.12      www      5587:     }
1.52      www      5588: 
                   5589: # Course: uri itself is a course
1.66      www      5590:     my $courseuri=$uri;
                   5591:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5592:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5593: 
1.620     albertel 5594:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5595:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5596:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5597:             $thisallowed.=$1;
                   5598:         }
1.12      www      5599:     }
1.29      www      5600: 
1.665     albertel 5601: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5602: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5603:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5604: 	$thisallowed='';
1.671     raeburn  5605:         my ($match)=&is_on_map($uri);
                   5606:         if ($match) {
                   5607:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5608:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5609:                 $thisallowed.=$1;
                   5610:             }
                   5611:         } else {
1.705     albertel 5612:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5613:             if ($refuri) {
                   5614:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5615:                     $thisallowed='F';
1.671     raeburn  5616:                 } else {
                   5617:                     $refuri=&declutter($refuri);
                   5618:                     my ($match) = &is_on_map($refuri);
                   5619:                     if ($match) {
                   5620:                         $thisallowed='F';
                   5621:                     }
1.669     raeburn  5622:                 }
1.671     raeburn  5623:             }
                   5624:         }
1.314     www      5625:     }
1.492     albertel 5626: 
1.766     albertel 5627:     if ($priv eq 'bre'
                   5628: 	&& $thisallowed ne 'F' 
                   5629: 	&& $thisallowed ne '2'
                   5630: 	&& &is_portfolio_url($uri)) {
                   5631: 	$thisallowed = &portfolio_access($uri);
                   5632:     }
                   5633:     
1.52      www      5634: # Full access at system, domain or course-wide level? Exit.
1.29      www      5635:     if ($thisallowed=~/F/) {
                   5636: 	return 'F';
                   5637:     }
                   5638: 
1.52      www      5639: # If this is generating or modifying users, exit with special codes
1.29      www      5640: 
1.643     www      5641:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5642: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5643: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5644: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5645: 	    unless ($auname) { return $thisallowed; }
                   5646: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5647: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5648: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5649: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5650: 	}
1.52      www      5651: 	return $thisallowed;
                   5652:     }
                   5653: #
1.103     harris41 5654: # Gathered so far: system, domain and course wide privileges
1.52      www      5655: #
                   5656: # Course: See if uri or referer is an individual resource that is part of 
                   5657: # the course
                   5658: 
1.620     albertel 5659:     if ($env{'request.course.id'}) {
1.232     www      5660: 
1.620     albertel 5661:        $courseprivid=$env{'request.course.id'};
                   5662:        if ($env{'request.course.sec'}) {
                   5663:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5664:        }
                   5665:        $courseprivid=~s/\_/\//;
                   5666:        my $checkreferer=1;
1.232     www      5667:        my ($match,$cond)=&is_on_map($uri);
                   5668:        if ($match) {
                   5669:            $statecond=$cond;
1.620     albertel 5670:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5671:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5672:                $thisallowed.=$1;
                   5673:                $checkreferer=0;
                   5674:            }
1.29      www      5675:        }
1.83      www      5676:        
1.148     www      5677:        if ($checkreferer) {
1.620     albertel 5678: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5679:             unless ($refuri) {
1.800     albertel 5680:                 foreach my $key (keys(%env)) {
                   5681: 		    if ($key=~/^httpref\..*\*/) {
                   5682: 			my $pattern=$key;
1.156     www      5683:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5684:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5685:                         $pattern=~s/\//\\\//g;
1.152     www      5686:                         if ($orguri=~/$pattern/) {
1.800     albertel 5687: 			    $refuri=$env{$key};
1.148     www      5688:                         }
                   5689:                     }
1.191     harris41 5690:                 }
1.148     www      5691:             }
1.232     www      5692: 
1.148     www      5693:          if ($refuri) { 
1.152     www      5694: 	  $refuri=&declutter($refuri);
1.232     www      5695:           my ($match,$cond)=&is_on_map($refuri);
                   5696:             if ($match) {
                   5697:               my $refstatecond=$cond;
1.620     albertel 5698:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5699:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5700:                   $thisallowed.=$1;
1.53      www      5701:                   $uri=$refuri;
                   5702:                   $statecond=$refstatecond;
1.52      www      5703:               }
                   5704:           }
1.148     www      5705:         }
1.29      www      5706:        }
1.52      www      5707:    }
1.29      www      5708: 
1.52      www      5709: #
1.103     harris41 5710: # Gathered now: all privileges that could apply, and condition number
1.52      www      5711: # 
                   5712: #
                   5713: # Full or no access?
                   5714: #
1.29      www      5715: 
1.52      www      5716:     if ($thisallowed=~/F/) {
                   5717: 	return 'F';
                   5718:     }
1.29      www      5719: 
1.52      www      5720:     unless ($thisallowed) {
                   5721:         return '';
                   5722:     }
1.29      www      5723: 
1.52      www      5724: # Restrictions exist, deal with them
                   5725: #
                   5726: #   C:according to course preferences
                   5727: #   R:according to resource settings
                   5728: #   L:unless locked
                   5729: #   X:according to user session state
                   5730: #
                   5731: 
                   5732: # Possibly locked functionality, check all courses
1.54      www      5733: # Locks might take effect only after 10 minutes cache expiration for other
                   5734: # courses, and 2 minutes for current course
1.52      www      5735: 
                   5736:     my $envkey;
                   5737:     if ($thisallowed=~/L/) {
1.1000    raeburn  5738:         foreach $envkey (keys(%env)) {
1.54      www      5739:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5740:                my $courseid=$2;
                   5741:                my $roleid=$1.'.'.$2;
1.92      www      5742:                $courseid=~s/^\///;
1.54      www      5743:                my $expiretime=600;
1.620     albertel 5744:                if ($env{'request.role'} eq $roleid) {
1.54      www      5745: 		  $expiretime=120;
                   5746:                }
                   5747: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5748:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5749:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5750: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5751:                }
1.620     albertel 5752:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5753:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5754: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5755:                        &log($env{'user.domain'},$env{'user.name'},
                   5756:                             $env{'user.home'},
1.57      www      5757:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5758:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5759:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5760: 		       return '';
                   5761:                    }
                   5762:                }
1.620     albertel 5763:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5764:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5765: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5766:                        &log($env{'user.domain'},$env{'user.name'},
                   5767:                             $env{'user.home'},
1.57      www      5768:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5769:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5770:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5771: 		       return '';
                   5772:                    }
                   5773:                }
                   5774: 	   }
1.29      www      5775:        }
1.52      www      5776:     }
                   5777:    
                   5778: #
                   5779: # Rest of the restrictions depend on selected course
                   5780: #
                   5781: 
1.620     albertel 5782:     unless ($env{'request.course.id'}) {
1.766     albertel 5783: 	if ($thisallowed eq 'A') {
                   5784: 	    return 'A';
1.814     raeburn  5785:         } elsif ($thisallowed eq 'B') {
                   5786:             return 'B';
1.766     albertel 5787: 	} else {
                   5788: 	    return '1';
                   5789: 	}
1.52      www      5790:     }
1.29      www      5791: 
1.52      www      5792: #
                   5793: # Now user is definitely in a course
                   5794: #
1.53      www      5795: 
                   5796: 
                   5797: # Course preferences
                   5798: 
                   5799:    if ($thisallowed=~/C/) {
1.620     albertel 5800:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5801:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5802:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5803: 	   =~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5804:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5805: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5806: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5807: 			$env{'request.course.id'});
                   5808: 	   }
1.237     www      5809:            return '';
                   5810:        }
                   5811: 
1.620     albertel 5812:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5813: 	   =~/\Q$unamedom\E/) {
1.1056.4.22  raeburn  5814:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5815: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5816: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5817: 			$env{'request.course.id'});
                   5818: 	   }
1.54      www      5819:            return '';
                   5820:        }
1.53      www      5821:    }
                   5822: 
                   5823: # Resource preferences
                   5824: 
                   5825:    if ($thisallowed=~/R/) {
1.620     albertel 5826:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5827:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5828:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5829: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5830: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5831: 	   }
                   5832: 	   return '';
1.54      www      5833:        }
1.53      www      5834:    }
1.30      www      5835: 
1.246     www      5836: # Restricted by state or randomout?
1.30      www      5837: 
1.52      www      5838:    if ($thisallowed=~/X/) {
1.620     albertel 5839:       if ($env{'acc.randomout'}) {
1.579     albertel 5840: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5841:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5842:             return ''; 
                   5843:          }
1.247     www      5844:       }
                   5845:       if (&condval($statecond)) {
1.52      www      5846: 	 return '2';
                   5847:       } else {
                   5848:          return '';
                   5849:       }
                   5850:    }
1.30      www      5851: 
1.766     albertel 5852:     if ($thisallowed eq 'A') {
                   5853: 	return 'A';
1.814     raeburn  5854:     } elsif ($thisallowed eq 'B') {
                   5855:         return 'B';
1.766     albertel 5856:     }
1.52      www      5857:    return 'F';
1.232     www      5858: }
                   5859: 
1.710     albertel 5860: sub split_uri_for_cond {
                   5861:     my $uri=&deversion(&declutter(shift));
                   5862:     my @uriparts=split(/\//,$uri);
                   5863:     my $filename=pop(@uriparts);
                   5864:     my $pathname=join('/',@uriparts);
                   5865:     return ($pathname,$filename);
                   5866: }
1.232     www      5867: # --------------------------------------------------- Is a resource on the map?
                   5868: 
                   5869: sub is_on_map {
1.710     albertel 5870:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5871:     #Trying to find the conditional for the file
1.620     albertel 5872:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5873: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5874:     if ($match) {
1.289     bowersj2 5875: 	return (1,$1);
                   5876:     } else {
1.434     www      5877: 	return (0,0);
1.289     bowersj2 5878:     }
1.12      www      5879: }
                   5880: 
1.427     www      5881: # --------------------------------------------------------- Get symb from alias
                   5882: 
                   5883: sub get_symb_from_alias {
                   5884:     my $symb=shift;
                   5885:     my ($map,$resid,$url)=&decode_symb($symb);
                   5886: # Already is a symb
                   5887:     if ($url) { return $symb; }
                   5888: # Must be an alias
                   5889:     my $aliassymb='';
                   5890:     my %bighash;
1.620     albertel 5891:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5892:                             &GDBM_READER(),0640)) {
                   5893:         my $rid=$bighash{'mapalias_'.$symb};
                   5894: 	if ($rid) {
                   5895: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5896: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5897: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5898: 	}
                   5899:         untie %bighash;
                   5900:     }
                   5901:     return $aliassymb;
                   5902: }
                   5903: 
1.12      www      5904: # ----------------------------------------------------------------- Define Role
                   5905: 
                   5906: sub definerole {
                   5907:   if (allowed('mcr','/')) {
                   5908:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5909:     foreach my $role (split(':',$sysrole)) {
                   5910: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5911:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5912:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5913: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5914:                return "refused:s:$crole&$cqual"; 
                   5915:             }
                   5916:         }
1.191     harris41 5917:     }
1.800     albertel 5918:     foreach my $role (split(':',$domrole)) {
                   5919: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5920:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5921:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5922: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5923:                return "refused:d:$crole&$cqual"; 
                   5924:             }
                   5925:         }
1.191     harris41 5926:     }
1.800     albertel 5927:     foreach my $role (split(':',$courole)) {
                   5928: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5929:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5930:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5931: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5932:                return "refused:c:$crole&$cqual"; 
                   5933:             }
                   5934:         }
1.191     harris41 5935:     }
1.620     albertel 5936:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5937:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5938: 	        "rolesdef_$rolename=".
                   5939:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5940:     return reply($command,$env{'user.home'});
1.12      www      5941:   } else {
                   5942:     return 'refused';
                   5943:   }
1.105     harris41 5944: }
                   5945: 
                   5946: # ---------------- Make a metadata query against the network of library servers
                   5947: 
                   5948: sub metadata_query {
1.244     matthew  5949:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5950:     my %rhash;
1.845     albertel 5951:     my %libserv = &all_library();
1.244     matthew  5952:     my @server_list = (defined($server_array) ? @$server_array
                   5953:                                               : keys(%libserv) );
                   5954:     for my $server (@server_list) {
1.118     harris41 5955: 	unless ($custom or $customshow) {
                   5956: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5957: 	    $rhash{$server}=$reply;
                   5958: 	}
                   5959: 	else {
                   5960: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5961: 			     &escape($custom).':'.&escape($customshow),
                   5962: 			     $server);
                   5963: 	    $rhash{$server}=$reply;
                   5964: 	}
1.112     harris41 5965:     }
1.118     harris41 5966:     return \%rhash;
1.240     www      5967: }
                   5968: 
                   5969: # ----------------------------------------- Send log queries and wait for reply
                   5970: 
                   5971: sub log_query {
                   5972:     my ($uname,$udom,$query,%filters)=@_;
                   5973:     my $uhome=&homeserver($uname,$udom);
                   5974:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5975:     my $uhost=&hostname($uhome);
1.800     albertel 5976:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5977:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5978:                        $uhome);
1.479     albertel 5979:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5980:     return get_query_reply($queryid);
                   5981: }
                   5982: 
1.818     raeburn  5983: # -------------------------- Update MySQL table for portfolio file
                   5984: 
                   5985: sub update_portfolio_table {
1.821     raeburn  5986:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5987:     if ($group ne '') {
                   5988:         $file_name =~s /^\Q$group\E//;
                   5989:     }
1.818     raeburn  5990:     my $homeserver = &homeserver($uname,$udom);
                   5991:     my $queryid=
1.821     raeburn  5992:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5993:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5994:     my $reply = &get_query_reply($queryid);
                   5995:     return $reply;
                   5996: }
                   5997: 
1.899     raeburn  5998: # -------------------------- Update MySQL allusers table
                   5999: 
                   6000: sub update_allusers_table {
                   6001:     my ($uname,$udom,$names) = @_;
                   6002:     my $homeserver = &homeserver($uname,$udom);
                   6003:     my $queryid=
                   6004:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6005:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6006:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6007:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6008:                'generation='.&escape($names->{'generation'}).'%%'.
                   6009:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6010:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  6011:     return;
1.899     raeburn  6012: }
                   6013: 
1.508     raeburn  6014: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6015: 
                   6016: sub fetch_enrollment_query {
1.511     raeburn  6017:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6018:     my $homeserver;
1.547     raeburn  6019:     my $maxtries = 1;
1.508     raeburn  6020:     if ($context eq 'automated') {
                   6021:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6022:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6023:     } else {
                   6024:         $homeserver = &homeserver($cnum,$dom);
                   6025:     }
1.838     albertel 6026:     my $host=&hostname($homeserver);
1.506     raeburn  6027:     my $cmd = '';
1.1000    raeburn  6028:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6029:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6030:     }
                   6031:     $cmd =~ s/%%$//;
                   6032:     $cmd = &escape($cmd);
                   6033:     my $query = 'fetchenrollment';
1.620     albertel 6034:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6035:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6036:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6037:         return 'error: '.$queryid;
                   6038:     }
1.506     raeburn  6039:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6040:     my $tries = 1;
                   6041:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6042:         $reply = &get_query_reply($queryid);
                   6043:         $tries ++;
                   6044:     }
1.526     raeburn  6045:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6046:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6047:     } else {
1.901     albertel 6048:         my @responses = split(/:/,$reply);
1.515     raeburn  6049:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6050:             foreach my $line (@responses) {
                   6051:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6052:                 $$replyref{$key} = $value;
                   6053:             }
                   6054:         } else {
1.506     raeburn  6055:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 6056:             foreach my $line (@responses) {
                   6057:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6058:                 $$replyref{$key} = $value;
                   6059:                 if ($value > 0) {
1.800     albertel 6060:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6061:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6062:                         my $destname = $pathname.'/'.$filename;
                   6063:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6064:                         if ($xml_classlist =~ /^error/) {
                   6065:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6066:                         } else {
1.506     raeburn  6067:                             if ( open(FILE,">$destname") ) {
                   6068:                                 print FILE &unescape($xml_classlist);
                   6069:                                 close(FILE);
1.526     raeburn  6070:                             } else {
                   6071:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6072:                             }
                   6073:                         }
                   6074:                     }
                   6075:                 }
                   6076:             }
                   6077:         }
                   6078:         return 'ok';
                   6079:     }
                   6080:     return 'error';
                   6081: }
                   6082: 
1.242     www      6083: sub get_query_reply {
                   6084:     my $queryid=shift;
1.240     www      6085:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6086:     my $reply='';
                   6087:     for (1..100) {
                   6088: 	sleep 2;
                   6089:         if (-e $replyfile.'.end') {
1.448     albertel 6090: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6091: 		$reply = join('',<$fh>);
                   6092: 		close($fh);
1.240     www      6093: 	   } else { return 'error: reply_file_error'; }
1.242     www      6094:            return &unescape($reply);
                   6095: 	}
1.240     www      6096:     }
1.242     www      6097:     return 'timeout:'.$queryid;
1.240     www      6098: }
                   6099: 
                   6100: sub courselog_query {
1.241     www      6101: #
                   6102: # possible filters:
                   6103: # url: url or symb
                   6104: # username
                   6105: # domain
                   6106: # action: view, submit, grade
                   6107: # start: timestamp
                   6108: # end: timestamp
                   6109: #
1.240     www      6110:     my (%filters)=@_;
1.620     albertel 6111:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6112:     if ($filters{'url'}) {
                   6113: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6114:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6115:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6116:     }
1.620     albertel 6117:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6118:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6119:     return &log_query($cname,$cdom,'courselog',%filters);
                   6120: }
                   6121: 
                   6122: sub userlog_query {
1.858     raeburn  6123: #
                   6124: # possible filters:
                   6125: # action: log check role
                   6126: # start: timestamp
                   6127: # end: timestamp
                   6128: #
1.240     www      6129:     my ($uname,$udom,%filters)=@_;
                   6130:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6131: }
                   6132: 
1.506     raeburn  6133: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6134: 
                   6135: sub auto_run {
1.508     raeburn  6136:     my ($cnum,$cdom) = @_;
1.876     raeburn  6137:     my $response = 0;
                   6138:     my $settings;
                   6139:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6140:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6141:         $settings = $domconfig{'autoenroll'};
                   6142:         if ($settings->{'run'} eq '1') {
                   6143:             $response = 1;
                   6144:         }
                   6145:     } else {
1.934     raeburn  6146:         my $homeserver;
                   6147:         if (&is_course($cdom,$cnum)) {
                   6148:             $homeserver = &homeserver($cnum,$cdom);
                   6149:         } else {
                   6150:             $homeserver = &domain($cdom,'primary');
                   6151:         }
                   6152:         if ($homeserver ne 'no_host') {
                   6153:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6154:         }
1.876     raeburn  6155:     }
1.506     raeburn  6156:     return $response;
                   6157: }
1.776     albertel 6158: 
1.506     raeburn  6159: sub auto_get_sections {
1.508     raeburn  6160:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6161:     my $homeserver;
                   6162:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6163:         $homeserver = &homeserver($cnum,$cdom);
                   6164:     }
                   6165:     if (!defined($homeserver)) { 
                   6166:         if ($cdom =~ /^$match_domain$/) {
                   6167:             $homeserver = &domain($cdom,'primary');
                   6168:         }
                   6169:     }
                   6170:     my @secs;
                   6171:     if (defined($homeserver)) {
                   6172:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6173:         unless ($response eq 'refused') {
                   6174:             @secs = split(/:/,$response);
                   6175:         }
1.506     raeburn  6176:     }
                   6177:     return @secs;
                   6178: }
1.776     albertel 6179: 
1.506     raeburn  6180: sub auto_new_course {
1.1056.4.19  raeburn  6181:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6182:     my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19  raeburn  6183:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6184:     return $response;
                   6185: }
1.776     albertel 6186: 
1.506     raeburn  6187: sub auto_validate_courseID {
1.508     raeburn  6188:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6189:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6190:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6191:     return $response;
                   6192: }
1.776     albertel 6193: 
1.1007    raeburn  6194: sub auto_validate_instcode {
1.1020    raeburn  6195:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6196:     my ($homeserver,$response);
                   6197:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6198:         $homeserver = &homeserver($cnum,$cdom);
                   6199:     }
                   6200:     if (!defined($homeserver)) {
                   6201:         if ($cdom =~ /^$match_domain$/) {
                   6202:             $homeserver = &domain($cdom,'primary');
                   6203:         }
                   6204:     }
1.1056.4.2  raeburn  6205:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6206:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6207:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6208:     return ($outcome,$description);
1.1007    raeburn  6209: }
                   6210: 
1.506     raeburn  6211: sub auto_create_password {
1.873     raeburn  6212:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6213:     my ($homeserver,$response);
1.506     raeburn  6214:     my $create_passwd = 0;
                   6215:     my $authchk = '';
1.873     raeburn  6216:     if ($udom =~ /^$match_domain$/) {
                   6217:         $homeserver = &domain($udom,'primary');
                   6218:     }
                   6219:     if ($homeserver eq '') {
                   6220:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6221:             $homeserver = &homeserver($cnum,$cdom);
                   6222:         }
                   6223:     }
                   6224:     if ($homeserver eq '') {
                   6225:         $authchk = 'nodomain';
1.506     raeburn  6226:     } else {
1.873     raeburn  6227:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6228:         if ($response eq 'refused') {
                   6229:             $authchk = 'refused';
                   6230:         } else {
1.901     albertel 6231:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6232:         }
1.506     raeburn  6233:     }
                   6234:     return ($authparam,$create_passwd,$authchk);
                   6235: }
                   6236: 
1.706     raeburn  6237: sub auto_photo_permission {
                   6238:     my ($cnum,$cdom,$students) = @_;
                   6239:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6240:     my ($outcome,$perm_reqd,$conditions) = 
                   6241: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6242:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6243: 	return (undef,undef);
                   6244:     }
1.706     raeburn  6245:     return ($outcome,$perm_reqd,$conditions);
                   6246: }
                   6247: 
                   6248: sub auto_checkphotos {
                   6249:     my ($uname,$udom,$pid) = @_;
                   6250:     my $homeserver = &homeserver($uname,$udom);
                   6251:     my ($result,$resulttype);
                   6252:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6253: 				   &escape($uname).':'.&escape($pid),
                   6254: 				   $homeserver));
1.709     albertel 6255:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6256: 	return (undef,undef);
                   6257:     }
1.706     raeburn  6258:     if ($outcome) {
                   6259:         ($result,$resulttype) = split(/:/,$outcome);
                   6260:     } 
                   6261:     return ($result,$resulttype);
                   6262: }
                   6263: 
                   6264: sub auto_photochoice {
                   6265:     my ($cnum,$cdom) = @_;
                   6266:     my $homeserver = &homeserver($cnum,$cdom);
                   6267:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6268: 						       &escape($cdom),
                   6269: 						       $homeserver)));
1.709     albertel 6270:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6271: 	return (undef,undef);
                   6272:     }
1.706     raeburn  6273:     return ($update,$comment);
                   6274: }
                   6275: 
                   6276: sub auto_photoupdate {
                   6277:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6278:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6279:     my $host=&hostname($homeserver);
1.706     raeburn  6280:     my $cmd = '';
                   6281:     my $maxtries = 1;
1.800     albertel 6282:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6283:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6284:     }
                   6285:     $cmd =~ s/%%$//;
                   6286:     $cmd = &escape($cmd);
                   6287:     my $query = 'institutionalphotos';
                   6288:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6289:     unless ($queryid=~/^\Q$host\E\_/) {
                   6290:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6291:         return 'error: '.$queryid;
                   6292:     }
                   6293:     my $reply = &get_query_reply($queryid);
                   6294:     my $tries = 1;
                   6295:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6296:         $reply = &get_query_reply($queryid);
                   6297:         $tries ++;
                   6298:     }
                   6299:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6300:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6301:     } else {
                   6302:         my @responses = split(/:/,$reply);
                   6303:         my $outcome = shift(@responses); 
                   6304:         foreach my $item (@responses) {
                   6305:             my ($key,$value) = split(/=/,$item);
                   6306:             $$photo{$key} = $value;
                   6307:         }
                   6308:         return $outcome;
                   6309:     }
                   6310:     return 'error';
                   6311: }
                   6312: 
1.521     raeburn  6313: sub auto_instcode_format {
1.793     albertel 6314:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6315: 	$cat_order) = @_;
1.521     raeburn  6316:     my $courses = '';
1.772     raeburn  6317:     my @homeservers;
1.521     raeburn  6318:     if ($caller eq 'global') {
1.841     albertel 6319: 	my %servers = &get_servers($codedom,'library');
                   6320: 	foreach my $tryserver (keys(%servers)) {
                   6321: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6322: 		push(@homeservers,$tryserver);
                   6323: 	    }
1.584     raeburn  6324:         }
1.1022    raeburn  6325:     } elsif ($caller eq 'requests') {
                   6326:         if ($codedom =~ /^$match_domain$/) {
                   6327:             my $chome = &domain($codedom,'primary');
                   6328:             unless ($chome eq 'no_host') {
                   6329:                 push(@homeservers,$chome);
                   6330:             }
                   6331:         }
1.521     raeburn  6332:     } else {
1.772     raeburn  6333:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6334:     }
1.793     albertel 6335:     foreach my $code (keys(%{$instcodes})) {
                   6336:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6337:     }
                   6338:     chop($courses);
1.772     raeburn  6339:     my $ok_response = 0;
                   6340:     my $response;
                   6341:     while (@homeservers > 0 && $ok_response == 0) {
                   6342:         my $server = shift(@homeservers); 
                   6343:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6344:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6345:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6346: 		split(/:/,$response);
1.772     raeburn  6347:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6348:             push(@{$codetitles},&str2array($codetitles_str));
                   6349:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6350:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6351:             $ok_response = 1;
                   6352:         }
                   6353:     }
                   6354:     if ($ok_response) {
1.521     raeburn  6355:         return 'ok';
1.772     raeburn  6356:     } else {
                   6357:         return $response;
1.521     raeburn  6358:     }
                   6359: }
                   6360: 
1.792     raeburn  6361: sub auto_instcode_defaults {
                   6362:     my ($domain,$returnhash,$code_order) = @_;
                   6363:     my @homeservers;
1.841     albertel 6364: 
                   6365:     my %servers = &get_servers($domain,'library');
                   6366:     foreach my $tryserver (keys(%servers)) {
                   6367: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6368: 	    push(@homeservers,$tryserver);
                   6369: 	}
1.792     raeburn  6370:     }
1.841     albertel 6371: 
1.792     raeburn  6372:     my $response;
1.841     albertel 6373:     foreach my $server (@homeservers) {
1.792     raeburn  6374:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6375:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6376: 	
                   6377: 	foreach my $pair (split(/\&/,$response)) {
                   6378: 	    my ($name,$value)=split(/\=/,$pair);
                   6379: 	    if ($name eq 'code_order') {
                   6380: 		@{$code_order} = split(/\&/,&unescape($value));
                   6381: 	    } else {
                   6382: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6383: 	    }
                   6384: 	}
                   6385: 	return 'ok';
1.792     raeburn  6386:     }
1.841     albertel 6387: 
                   6388:     return $response;
1.1003    raeburn  6389: }
                   6390: 
                   6391: sub auto_possible_instcodes {
1.1007    raeburn  6392:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6393:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6394:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6395:         return;
                   6396:     }
1.1003    raeburn  6397:     my (@homeservers,$uhome);
                   6398:     if (defined(&domain($domain,'primary'))) {
                   6399:         $uhome=&domain($domain,'primary');
                   6400:         push(@homeservers,&domain($domain,'primary'));
                   6401:     } else {
                   6402:         my %servers = &get_servers($domain,'library');
                   6403:         foreach my $tryserver (keys(%servers)) {
                   6404:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6405:                 push(@homeservers,$tryserver);
                   6406:             }
                   6407:         }
                   6408:     }
                   6409:     my $response;
                   6410:     foreach my $server (@homeservers) {
                   6411:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6412:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6413:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6414:             split(':',$response);
                   6415:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6416:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6417:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6418:             my ($name,$value)=split('=',$item);
                   6419:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6420:         }
                   6421:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6422:             my ($name,$value)=split('=',$item);
                   6423:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6424:         }
                   6425:         return 'ok';
                   6426:     }
                   6427:     return $response;
                   6428: }
1.792     raeburn  6429: 
1.1010    raeburn  6430: sub auto_courserequest_checks {
                   6431:     my ($dom) = @_;
1.1020    raeburn  6432:     my ($homeserver,%validations);
                   6433:     if ($dom =~ /^$match_domain$/) {
                   6434:         $homeserver = &domain($dom,'primary');
                   6435:     }
                   6436:     unless ($homeserver eq 'no_host') {
                   6437:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6438:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6439:             my @items = split(/&/,$response);
                   6440:             foreach my $item (@items) {
                   6441:                 my ($key,$value) = split('=',$item);
                   6442:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6443:             }
                   6444:         }
                   6445:     }
1.1010    raeburn  6446:     return %validations; 
                   6447: }
                   6448: 
1.1020    raeburn  6449: sub auto_courserequest_validation {
                   6450:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6451:     my ($homeserver,$response);
                   6452:     if ($dom =~ /^$match_domain$/) {
                   6453:         $homeserver = &domain($dom,'primary');
                   6454:     }
                   6455:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6456:           
1.1020    raeburn  6457:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6458:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6459:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6460:                                     $homeserver));
                   6461:     }
                   6462:     return $response;
                   6463: }
                   6464: 
1.777     albertel 6465: sub auto_validate_class_sec {
1.918     raeburn  6466:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6467:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6468:     my $ownerlist;
                   6469:     if (ref($owners) eq 'ARRAY') {
                   6470:         $ownerlist = join(',',@{$owners});
                   6471:     } else {
                   6472:         $ownerlist = $owners;
                   6473:     }
1.773     raeburn  6474:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6475:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6476:     return $response;
                   6477: }
                   6478: 
1.679     raeburn  6479: # ------------------------------------------------------- Course Group routines
                   6480: 
                   6481: sub get_coursegroups {
1.809     raeburn  6482:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6483:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6484: }
                   6485: 
1.679     raeburn  6486: sub modify_coursegroup {
                   6487:     my ($cdom,$cnum,$groupsettings) = @_;
                   6488:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6489: }
                   6490: 
1.809     raeburn  6491: sub toggle_coursegroup_status {
                   6492:     my ($cdom,$cnum,$group,$action) = @_;
                   6493:     my ($from_namespace,$to_namespace);
                   6494:     if ($action eq 'delete') {
                   6495:         $from_namespace = 'coursegroups';
                   6496:         $to_namespace = 'deleted_groups';
                   6497:     } else {
                   6498:         $from_namespace = 'deleted_groups';
                   6499:         $to_namespace = 'coursegroups';
                   6500:     }
                   6501:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6502:     if (my $tmp = &error(%curr_group)) {
                   6503:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6504:         return ('read error',$tmp);
                   6505:     } else {
                   6506:         my %savedsettings = %curr_group; 
1.809     raeburn  6507:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6508:         my $deloutcome;
                   6509:         if ($result eq 'ok') {
1.809     raeburn  6510:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6511:         } else {
                   6512:             return ('write error',$result);
                   6513:         }
                   6514:         if ($deloutcome eq 'ok') {
                   6515:             return 'ok';
                   6516:         } else {
                   6517:             return ('delete error',$deloutcome);
                   6518:         }
                   6519:     }
                   6520: }
                   6521: 
1.679     raeburn  6522: sub modify_group_roles {
1.957     raeburn  6523:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6524:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6525:     my $role = 'gr/'.&escape($userprivs);
                   6526:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6527:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6528:     if ($result eq 'ok') {
                   6529:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6530:     }
1.679     raeburn  6531:     return $result;
                   6532: }
                   6533: 
                   6534: sub modify_coursegroup_membership {
                   6535:     my ($cdom,$cnum,$membership) = @_;
                   6536:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6537:     return $result;
                   6538: }
                   6539: 
1.682     raeburn  6540: sub get_active_groups {
                   6541:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6542:     my $now = time;
                   6543:     my %groups = ();
                   6544:     foreach my $key (keys(%env)) {
1.811     albertel 6545:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6546:             my ($start,$end) = split(/\./,$env{$key});
                   6547:             if (($end!=0) && ($end<$now)) { next; }
                   6548:             if (($start!=0) && ($start>$now)) { next; }
                   6549:             if ($1 eq $cdom && $2 eq $cnum) {
                   6550:                 $groups{$3} = $env{$key} ;
                   6551:             }
                   6552:         }
                   6553:     }
                   6554:     return %groups;
                   6555: }
                   6556: 
1.683     raeburn  6557: sub get_group_membership {
                   6558:     my ($cdom,$cnum,$group) = @_;
                   6559:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6560: }
                   6561: 
                   6562: sub get_users_groups {
                   6563:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6564:     my @usersgroups;
1.683     raeburn  6565:     my $cachetime=1800;
                   6566: 
                   6567:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6568:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6569:     if (defined($cached)) {
1.734     albertel 6570:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6571:     } else {  
                   6572:         $grouplist = '';
1.816     raeburn  6573:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6574:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6575:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6576:         my $access_end = $env{'course.'.$courseid.
                   6577:                               '.default_enrollment_end_date'};
                   6578:         my $now = time;
                   6579:         foreach my $key (keys(%roleshash)) {
                   6580:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6581:                 my $group = $1;
                   6582:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6583:                     my $start = $2;
                   6584:                     my $end = $1;
                   6585:                     if ($start == -1) { next; } # deleted from group
                   6586:                     if (($start!=0) && ($start>$now)) { next; }
                   6587:                     if (($end!=0) && ($end<$now)) {
                   6588:                         if ($access_end && $access_end < $now) {
                   6589:                             if ($access_end - $end < 86400) {
                   6590:                                 push(@usersgroups,$group);
1.733     raeburn  6591:                             }
                   6592:                         }
1.817     raeburn  6593:                         next;
1.733     raeburn  6594:                     }
1.817     raeburn  6595:                     push(@usersgroups,$group);
1.683     raeburn  6596:                 }
                   6597:             }
                   6598:         }
1.817     raeburn  6599:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6600:         $grouplist = join(':',@usersgroups);
                   6601:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6602:     }
1.733     raeburn  6603:     return @usersgroups;
1.683     raeburn  6604: }
                   6605: 
                   6606: sub devalidate_getgroups_cache {
                   6607:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6608:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6609: 
1.683     raeburn  6610:     my $hashid="$udom:$uname:$courseid";
                   6611:     &devalidate_cache_new('getgroups',$hashid);
                   6612: }
                   6613: 
1.12      www      6614: # ------------------------------------------------------------------ Plain Text
                   6615: 
                   6616: sub plaintext {
1.988     raeburn  6617:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6618:     if ($short =~ m{^cr/}) {
1.758     albertel 6619: 	return (split('/',$short))[-1];
                   6620:     }
1.742     raeburn  6621:     if (!defined($cid)) {
                   6622:         $cid = $env{'request.course.id'};
                   6623:     }
                   6624:     my %rolenames = (
1.1008    raeburn  6625:                       Course    => 'std',
                   6626:                       Community => 'alt1',
1.742     raeburn  6627:                     );
1.1037    raeburn  6628:     if ($cid ne '') {
                   6629:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6630:             unless ($forcedefault) {
                   6631:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6632:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6633:                 return &Apache::lonlocal::mt($roletext);
                   6634:             }
                   6635:         }
                   6636:     }
                   6637:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6638:         (defined($rolenames{$type})) && 
                   6639:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6640:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6641:     } elsif ($cid ne '') {
                   6642:         my $crstype = $env{'course.'.$cid.'.type'};
                   6643:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6644:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6645:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6646:         }
1.742     raeburn  6647:     }
1.1037    raeburn  6648:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6649: }
                   6650: 
                   6651: # ----------------------------------------------------------------- Assign Role
                   6652: 
                   6653: sub assignrole {
1.957     raeburn  6654:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6655:         $context)=@_;
1.21      www      6656:     my $mrole;
                   6657:     if ($role =~ /^cr\//) {
1.393     www      6658:         my $cwosec=$url;
1.811     albertel 6659:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6660: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6661:            my $refused = 1;
                   6662:            if ($context eq 'requestcourses') {
                   6663:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6664:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6665:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6666:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6667:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6668:                            if ($crsenv{'internal.courseowner'} eq
                   6669:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6670:                                $refused = '';
                   6671:                            }
                   6672:                        }
                   6673:                    }
                   6674:                }
                   6675:            }
                   6676:            if ($refused) {
                   6677:                &logthis('Refused custom assignrole: '.
                   6678:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6679:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6680:                return 'refused';
                   6681:            }
1.104     www      6682:         }
1.21      www      6683:         $mrole='cr';
1.678     raeburn  6684:     } elsif ($role =~ /^gr\//) {
                   6685:         my $cwogrp=$url;
1.811     albertel 6686:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6687:         unless (&allowed('mdg',$cwogrp)) {
                   6688:             &logthis('Refused group assignrole: '.
                   6689:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6690:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6691:             return 'refused';
                   6692:         }
                   6693:         $mrole='gr';
1.21      www      6694:     } else {
1.82      www      6695:         my $cwosec=$url;
1.811     albertel 6696:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6697:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6698:             my $refused;
                   6699:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6700:                 if (!(&allowed('c'.$role,$url))) {
                   6701:                     $refused = 1;
                   6702:                 }
                   6703:             } else {
                   6704:                 $refused = 1;
                   6705:             }
1.947     raeburn  6706:             if ($refused) {
1.1045    raeburn  6707:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6708:                 if (!$selfenroll && $context eq 'course') {
                   6709:                     my %crsenv;
                   6710:                     if ($role eq 'cc' || $role eq 'co') {
                   6711:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6712:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6713:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6714:                                 if ($crsenv{'internal.courseowner'} eq 
                   6715:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6716:                                     $refused = '';
                   6717:                                 }
                   6718:                             }
                   6719:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6720:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6721:                                 if ($crsenv{'internal.courseowner'} eq 
                   6722:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6723:                                     $refused = '';
                   6724:                                 }
                   6725:                             }
                   6726:                         }
                   6727:                     }
                   6728:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6729:                     $refused = '';
1.1017    raeburn  6730:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6731:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6732:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6733:                         my $wrongcc;
                   6734:                         if ($cnum =~ /^$match_community$/) {
                   6735:                             $wrongcc = 1 if ($role eq 'cc');
                   6736:                         } else {
                   6737:                             $wrongcc = 1 if ($role eq 'co');
                   6738:                         }
                   6739:                         unless ($wrongcc) {
                   6740:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6741:                             if ($crsenv{'internal.courseowner'} eq 
                   6742:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6743:                                 $refused = '';
                   6744:                             }
1.1017    raeburn  6745:                         }
                   6746:                     }
                   6747:                 }
                   6748:                 if ($refused) {
1.947     raeburn  6749:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6750:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6751: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6752:                     return 'refused';
                   6753:                 }
1.932     raeburn  6754:             }
1.1056.4.30  raeburn  6755:         } elsif ($role eq 'au') {
                   6756:             if ($url ne '/'.$udom.'/') {
                   6757:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   6758:                          ' to assign author role for '.$uname.':'.$udom.
                   6759:                          ' in domain: '.$url.' refused (wrong domain).');
                   6760:                 return 'refused';
                   6761:             }
1.104     www      6762:         }
1.21      www      6763:         $mrole=$role;
                   6764:     }
1.620     albertel 6765:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6766:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6767:     if ($end) { $command.='_'.$end; }
1.21      www      6768:     if ($start) {
                   6769: 	if ($end) { 
1.81      www      6770:            $command.='_'.$start; 
1.21      www      6771:         } else {
1.81      www      6772:            $command.='_0_'.$start;
1.21      www      6773:         }
                   6774:     }
1.739     raeburn  6775:     my $origstart = $start;
                   6776:     my $origend = $end;
1.957     raeburn  6777:     my $delflag;
1.357     www      6778: # actually delete
                   6779:     if ($deleteflag) {
1.373     www      6780: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6781: # modify command to delete the role
1.620     albertel 6782:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6783:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6784: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6785: # set start and finish to negative values for userrolelog
                   6786:            $start=-1;
                   6787:            $end=-1;
1.957     raeburn  6788:            $delflag = 1;
1.357     www      6789:         }
                   6790:     }
                   6791: # send command
1.349     www      6792:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6793: # log new user role if status is ok
1.349     www      6794:     if ($answer eq 'ok') {
1.663     raeburn  6795: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6796: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6797:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6798:         unless ($role =~ /^gr/) {
                   6799:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6800:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6801:         }
1.1053    raeburn  6802:         if ($role eq 'cc') {
                   6803:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6804:         }
1.349     www      6805:     }
                   6806:     return $answer;
1.169     harris41 6807: }
                   6808: 
1.1053    raeburn  6809: sub autoupdate_coowners {
                   6810:     my ($url,$end,$start,$uname,$udom) = @_;
                   6811:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6812:     if (($cdom ne '') && ($cnum ne '')) {
                   6813:         my $now = time;
                   6814:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6815:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6816:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6817:             my $instcode = $coursehash{'internal.coursecode'};
                   6818:             if ($instcode ne '') {
1.1056    raeburn  6819:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6820:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6821:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6822:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6823:                         if ($result eq 'valid') {
                   6824:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6825:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6826:                                     push(@newcoowners,$coowner);
                   6827:                                 }
                   6828:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6829:                                     push(@newcoowners,$uname.':'.$udom);
                   6830:                                 }
                   6831:                                 @newcoowners = sort(@newcoowners);
                   6832:                             } else {
                   6833:                                 push(@newcoowners,$uname.':'.$udom);
                   6834:                             }
                   6835:                         } else {
                   6836:                             if ($coursehash{'internal.co-owners'}) {
                   6837:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6838:                                     unless ($coowner eq $uname.':'.$udom) {
                   6839:                                         push(@newcoowners,$coowner);
                   6840:                                     }
                   6841:                                 }
                   6842:                                 unless (@newcoowners > 0) {
                   6843:                                     $delcoowners = 1;
                   6844:                                     $coowners = '';
                   6845:                                 }
                   6846:                             }
                   6847:                         }
                   6848:                         if (@newcoowners || $delcoowners) {
                   6849:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6850:                                             $delcoowners,@newcoowners);
                   6851:                         }
                   6852:                     }
                   6853:                 }
                   6854:             }
                   6855:         }
                   6856:     }
                   6857: }
                   6858: 
                   6859: sub store_coowners {
                   6860:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6861:     my $cid = $cdom.'_'.$cnum;
                   6862:     my ($coowners,$delresult,$putresult);
                   6863:     if (@newcoowners) {
                   6864:         $coowners = join(',',@newcoowners);
                   6865:         my %coownershash = (
                   6866:                             'internal.co-owners' => $coowners,
                   6867:                            );
                   6868:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6869:         if ($putresult eq 'ok') {
                   6870:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6871:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6872:             }
                   6873:         }
                   6874:     }
                   6875:     if ($delcoowners) {
                   6876:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6877:         if ($delresult eq 'ok') {
                   6878:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6879:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6880:             }
                   6881:         }
                   6882:     }
                   6883:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6884:         my %crsinfo =
                   6885:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6886:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6887:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6888:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6889:         }
                   6890:     }
                   6891: }
                   6892: 
1.169     harris41 6893: # -------------------------------------------------- Modify user authentication
1.197     www      6894: # Overrides without validation
                   6895: 
1.169     harris41 6896: sub modifyuserauth {
                   6897:     my ($udom,$uname,$umode,$upass)=@_;
                   6898:     my $uhome=&homeserver($uname,$udom);
1.197     www      6899:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6900:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6901:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6902:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6903:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6904: 		     &escape($upass),$uhome);
1.620     albertel 6905:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6906:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6907:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6908:     &log($udom,,$uname,$uhome,
1.620     albertel 6909:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6910:                                      $env{'user.name'}.', '.$umode.
1.197     www      6911:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6912:     unless ($reply eq 'ok') {
1.197     www      6913:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6914: 	return 'error: '.$reply;
                   6915:     }   
1.170     harris41 6916:     return 'ok';
1.80      www      6917: }
                   6918: 
1.81      www      6919: # --------------------------------------------------------------- Modify a user
1.80      www      6920: 
1.81      www      6921: sub modifyuser {
1.206     matthew  6922:     my ($udom,    $uname, $uid,
                   6923:         $umode,   $upass, $first,
                   6924:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6925:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6926:     $udom= &LONCAPA::clean_domain($udom);
                   6927:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6928:     my $showcandelete = 'none';
                   6929:     if (ref($candelete) eq 'ARRAY') {
                   6930:         if (@{$candelete} > 0) {
                   6931:             $showcandelete = join(', ',@{$candelete});
                   6932:         }
                   6933:     }
1.81      www      6934:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6935:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6936:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6937:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6938:                                      ' desiredhome not specified'). 
1.620     albertel 6939:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6940:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6941:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6942:     my $newuser;
                   6943:     if ($uhome eq 'no_host') {
                   6944:         $newuser = 1;
                   6945:     }
1.80      www      6946: # ----------------------------------------------------------------- Create User
1.406     albertel 6947:     if (($uhome eq 'no_host') && 
                   6948: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6949:         my $unhome='';
1.844     albertel 6950:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6951:             $unhome = $desiredhome;
1.620     albertel 6952: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6953: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6954:         } else { # load balancing routine for determining $unhome
1.81      www      6955:             my $loadm=10000000;
1.841     albertel 6956: 	    my %servers = &get_servers($udom,'library');
                   6957: 	    foreach my $tryserver (keys(%servers)) {
                   6958: 		my $answer=reply('load',$tryserver);
                   6959: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6960: 		    $loadm=$answer;
                   6961: 		    $unhome=$tryserver;
                   6962: 		}
1.80      www      6963: 	    }
                   6964:         }
                   6965:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6966: 	    return 'error: unable to find a home server for '.$uname.
                   6967:                    ' in domain '.$udom;
1.80      www      6968:         }
                   6969:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6970:                          &escape($upass),$unhome);
                   6971: 	unless ($reply eq 'ok') {
                   6972:             return 'error: '.$reply;
                   6973:         }   
1.230     stredwic 6974:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6975:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6976: 	    return 'error: unable verify users home machine.';
1.80      www      6977:         }
1.209     matthew  6978:     }   # End of creation of new user
1.80      www      6979: # ---------------------------------------------------------------------- Add ID
                   6980:     if ($uid) {
                   6981:        $uid=~tr/A-Z/a-z/;
                   6982:        my %uidhash=&idrget($udom,$uname);
1.196     www      6983:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6984:          && (!$forceid)) {
1.80      www      6985: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6986: 	      return 'error: user id "'.$uid.'" does not match '.
                   6987:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6988:           }
                   6989:        } else {
                   6990: 	  &idput($udom,($uname => $uid));
                   6991:        }
                   6992:     }
                   6993: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6994:     my @tmp=&get('environment',
1.899     raeburn  6995: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6996:                     'permanentemail','inststatus'],
1.134     albertel 6997: 		   $udom,$uname);
1.1056.4.4  raeburn  6998:     my (%names,%oldnames);
1.313     matthew  6999:     if ($tmp[0] =~ m/^error:.*/) { 
                   7000:         %names=(); 
                   7001:     } else {
                   7002:         %names = @tmp;
1.1056.4.4  raeburn  7003:         %oldnames = %names;
1.313     matthew  7004:     }
1.1056.4.6  raeburn  7005: #
1.1056.4.1  raeburn  7006: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7007: # of users did not contain them), do not overwrite existing values
                   7008: # unless field is in $candelete array ref.  
                   7009: #
                   7010: 
                   7011:     my @fields = ('firstname','middlename','lastname','generation',
                   7012:                   'permanentemail','id');
                   7013:     my %newvalues;
                   7014:     if (ref($candelete) eq 'ARRAY') {
                   7015:         foreach my $field (@fields) {
                   7016:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7017:                 if ($field eq 'firstname') {
                   7018:                     $names{$field} = $first;
                   7019:                 } elsif ($field eq 'middlename') {
                   7020:                     $names{$field} = $middle;
                   7021:                 } elsif ($field eq 'lastname') {
                   7022:                     $names{$field} = $last;
                   7023:                 } elsif ($field eq 'generation') { 
                   7024:                     $names{$field} = $gene;
                   7025:                 } elsif ($field eq 'permanentemail') {
                   7026:                     $names{$field} = $email;
                   7027:                 } elsif ($field eq 'id') {
                   7028:                     $names{$field}  = $uid;
                   7029:                 }
                   7030:             }
                   7031:         }
                   7032:     }
1.388     www      7033:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7034:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7035:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7036:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7037:     if ($email) {
                   7038:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7039:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7040:     }
1.899     raeburn  7041:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7042:     if (defined($inststatus)) {
                   7043:         $names{'inststatus'} = '';
                   7044:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7045:         if (ref($usertypes) eq 'HASH') {
                   7046:             my @okstatuses; 
                   7047:             foreach my $item (split(/:/,$inststatus)) {
                   7048:                 if (defined($usertypes->{$item})) {
                   7049:                     push(@okstatuses,$item);  
                   7050:                 }
                   7051:             }
                   7052:             if (@okstatuses) {
                   7053:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7054:             }
                   7055:         }
                   7056:     }
1.1056.4.4  raeburn  7057:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7058:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  7059:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7060:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7061:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7062:     } else {
                   7063:         $logmsg .= ' during self creation';
                   7064:     }
1.1056.4.4  raeburn  7065:     my $changed;
                   7066:     if ($newuser) {
                   7067:         $changed = 1;
                   7068:     } else {
                   7069:         foreach my $field (@fields) {
                   7070:             if ($names{$field} ne $oldnames{$field}) {
                   7071:                 $changed = 1;
                   7072:                 last;
                   7073:             }
                   7074:         }
                   7075:     }
                   7076:     unless ($changed) {
                   7077:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7078:         &logthis($logmsg);
                   7079:         return 'ok';
                   7080:     }
                   7081:     my $reply = &put('environment', \%names, $udom,$uname);
                   7082:     if ($reply ne 'ok') {
                   7083:         return 'error: '.$reply;
                   7084:     }
1.1056.4.11  raeburn  7085:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7086:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7087:     }
1.1056.4.4  raeburn  7088:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7089:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7090:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7091:     &logthis($logmsg);
1.134     albertel 7092:     return 'ok';
1.80      www      7093: }
                   7094: 
1.81      www      7095: # -------------------------------------------------------------- Modify student
1.80      www      7096: 
1.81      www      7097: sub modifystudent {
                   7098:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7099:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7100:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7101:     if (!$cid) {
1.620     albertel 7102: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7103: 	    return 'not_in_class';
                   7104: 	}
1.80      www      7105:     }
                   7106: # --------------------------------------------------------------- Make the user
1.81      www      7107:     my $reply=&modifyuser
1.209     matthew  7108: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7109:          $desiredhome,$email,$inststatus);
1.80      www      7110:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7111:     # This will cause &modify_student_enrollment to get the uid from the
                   7112:     # students environment
                   7113:     $uid = undef if (!$forceid);
1.455     albertel 7114:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7115: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7116:     return $reply;
                   7117: }
                   7118: 
                   7119: sub modify_student_enrollment {
1.957     raeburn  7120:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7121:     my ($cdom,$cnum,$chome);
                   7122:     if (!$cid) {
1.620     albertel 7123: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7124: 	    return 'not_in_class';
                   7125: 	}
1.620     albertel 7126: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7127: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7128:     } else {
                   7129: 	($cdom,$cnum)=split(/_/,$cid);
                   7130:     }
1.620     albertel 7131:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7132:     if (!$chome) {
1.457     raeburn  7133: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7134:     }
1.455     albertel 7135:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7136:     # Make sure the user exists
1.81      www      7137:     my $uhome=&homeserver($uname,$udom);
                   7138:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7139: 	return 'error: no such user';
                   7140:     }
1.297     matthew  7141:     # Get student data if we were not given enough information
                   7142:     if (!defined($first)  || $first  eq '' || 
                   7143:         !defined($last)   || $last   eq '' || 
                   7144:         !defined($uid)    || $uid    eq '' || 
                   7145:         !defined($middle) || $middle eq '' || 
                   7146:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7147:         # They did not supply us with enough data to enroll the student, so
                   7148:         # we need to pick up more information.
1.297     matthew  7149:         my %tmp = &get('environment',
1.294     matthew  7150:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7151:                        ,$udom,$uname);
                   7152: 
1.800     albertel 7153:         #foreach my $key (keys(%tmp)) {
                   7154:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7155:         #}
1.294     matthew  7156:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7157:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7158:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7159:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7160:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7161:     }
1.556     albertel 7162:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7163:     my $reply=cput('classlist',
                   7164: 		   {"$uname:$udom" => 
1.515     raeburn  7165: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7166: 		   $cdom,$cnum);
1.81      www      7167:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7168: 	return 'error: '.$reply;
1.652     albertel 7169:     } else {
                   7170: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7171:     }
1.297     matthew  7172:     # Add student role to user
1.83      www      7173:     my $uurl='/'.$cid;
1.81      www      7174:     $uurl=~s/\_/\//g;
                   7175:     if ($usec) {
                   7176: 	$uurl.='/'.$usec;
                   7177:     }
1.957     raeburn  7178:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7179: }
                   7180: 
1.556     albertel 7181: sub format_name {
                   7182:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7183:     my $name;
                   7184:     if ($first ne 'lastname') {
                   7185: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7186:     } else {
                   7187: 	if ($lastname=~/\S/) {
                   7188: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7189: 	    $name=~s/\s+,/,/;
                   7190: 	} else {
                   7191: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7192: 	}
                   7193:     }
                   7194:     $name=~s/^\s+//;
                   7195:     $name=~s/\s+$//;
                   7196:     $name=~s/\s+/ /g;
                   7197:     return $name;
                   7198: }
                   7199: 
1.84      www      7200: # ------------------------------------------------- Write to course preferences
                   7201: 
                   7202: sub writecoursepref {
                   7203:     my ($courseid,%prefs)=@_;
                   7204:     $courseid=~s/^\///;
                   7205:     $courseid=~s/\_/\//g;
                   7206:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7207:     my $chome=homeserver($cnum,$cdomain);
                   7208:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7209: 	return 'error: no such course';
                   7210:     }
                   7211:     my $cstring='';
1.800     albertel 7212:     foreach my $pref (keys(%prefs)) {
                   7213: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7214:     }
1.84      www      7215:     $cstring=~s/\&$//;
                   7216:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7217: }
                   7218: 
                   7219: # ---------------------------------------------------------- Make/modify course
                   7220: 
                   7221: sub createcourse {
1.741     raeburn  7222:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7223:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7224:     $url=&declutter($url);
                   7225:     my $cid='';
1.1028    raeburn  7226:     if ($context eq 'requestcourses') {
                   7227:         my $can_create = 0;
                   7228:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7229:         if ($udom eq $ownerdom) {
                   7230:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7231:                                   $context)) {
                   7232:                 $can_create = 1;
                   7233:             }
                   7234:         } else {
                   7235:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7236:                                            $category);
                   7237:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7238:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7239:                 if (@curr > 0) {
                   7240:                     my @options = qw(approval validate autolimit);
                   7241:                     my $optregex = join('|',@options);
                   7242:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7243:                         $can_create = 1;
                   7244:                     }
                   7245:                 }
                   7246:             }
                   7247:         }
                   7248:         if ($can_create) {
                   7249:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7250:                 unless (&allowed('ccc',$udom)) {
                   7251:                     return 'refused'; 
                   7252:                 }
1.1017    raeburn  7253:             }
                   7254:         } else {
                   7255:             return 'refused';
                   7256:         }
1.1028    raeburn  7257:     } elsif (!&allowed('ccc',$udom)) {
                   7258:         return 'refused';
1.84      www      7259:     }
1.1011    raeburn  7260: # --------------------------------------------------------------- Get Unique ID
                   7261:     my $uname;
                   7262:     if ($cnum =~ /^$match_courseid$/) {
                   7263:         my $chome=&homeserver($cnum,$udom,'true');
                   7264:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7265:             $uname = $cnum;
                   7266:         } else {
1.1038    raeburn  7267:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7268:         }
                   7269:     } else {
1.1038    raeburn  7270:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7271:     }
                   7272:     return $uname if ($uname =~ /^error/);
                   7273: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7274:     if (!defined($course_server)) {
                   7275:         if (defined(&domain($udom,'primary'))) {
                   7276:             $course_server = &domain($udom,'primary');
                   7277:         } else {
                   7278:             $course_server = $env{'user.home'}; 
                   7279:         }
                   7280:     }
                   7281:     my %host_servers =
                   7282:         &Apache::lonnet::get_servers($udom,'library');
                   7283:     unless ($host_servers{$course_server}) {
                   7284:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7285:     }
1.84      www      7286: # ------------------------------------------------------------- Make the course
                   7287:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7288:                       $course_server);
1.84      www      7289:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7290:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7291:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7292: 	return 'error: no such course';
                   7293:     }
1.271     www      7294: # ----------------------------------------------------------------- Course made
1.516     raeburn  7295: # log existence
1.1029    raeburn  7296:     my $now = time;
1.918     raeburn  7297:     my $newcourse = {
                   7298:                     $udom.'_'.$uname => {
1.921     raeburn  7299:                                      description => $description,
                   7300:                                      inst_code   => $inst_code,
                   7301:                                      owner       => $course_owner,
                   7302:                                      type        => $crstype,
1.1029    raeburn  7303:                                      creator     => $env{'user.name'}.':'.
                   7304:                                                     $env{'user.domain'},
                   7305:                                      created     => $now,
                   7306:                                      context     => $context,
1.918     raeburn  7307:                                                 },
                   7308:                     };
1.921     raeburn  7309:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7310: # set toplevel url
1.271     www      7311:     my $topurl=$url;
                   7312:     unless ($nonstandard) {
                   7313: # ------------------------------------------ For standard courses, make top url
                   7314:         my $mapurl=&clutter($url);
1.278     www      7315:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7316:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7317: <map>
                   7318: <resource id="1" type="start"></resource>
                   7319: <resource id="2" src="$mapurl"></resource>
                   7320: <resource id="3" type="finish"></resource>
                   7321: <link index="1" from="1" to="2"></link>
                   7322: <link index="2" from="2" to="3"></link>
                   7323: </map>
                   7324: ENDINITMAP
                   7325:         $topurl=&declutter(
1.638     albertel 7326:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7327:                           );
                   7328:     }
                   7329: # ----------------------------------------------------------- Write preferences
1.84      www      7330:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7331:                      ('description'              => $description,
                   7332:                       'url'                      => $topurl,
                   7333:                       'internal.creator'         => $env{'user.name'}.':'.
                   7334:                                                     $env{'user.domain'},
                   7335:                       'internal.created'         => $now,
                   7336:                       'internal.creationcontext' => $context)
                   7337:                     );
1.84      www      7338:     return '/'.$udom.'/'.$uname;
                   7339: }
                   7340: 
1.1011    raeburn  7341: # ------------------------------------------------------------------- Create ID
                   7342: sub generate_coursenum {
1.1038    raeburn  7343:     my ($udom,$crstype) = @_;
1.1011    raeburn  7344:     my $domdesc = &domain($udom);
                   7345:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7346:     my $first;
                   7347:     if ($crstype eq 'Community') {
                   7348:         $first = '0';
                   7349:     } else {
                   7350:         $first = int(1+rand(9)); 
                   7351:     } 
                   7352:     my $uname=$first.
1.1011    raeburn  7353:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7354:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7355:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7356: # ----------------------------------------------- Make sure that does not exist
                   7357:     my $uhome=&homeserver($uname,$udom,'true');
                   7358:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7359:         if ($crstype eq 'Community') {
                   7360:             $first = '0';
                   7361:         } else {
                   7362:             $first = int(1+rand(9));
                   7363:         }
                   7364:         $uname=$first.
1.1011    raeburn  7365:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7366:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7367:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7368:         $uhome=&homeserver($uname,$udom,'true');
                   7369:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7370:             return 'error: unable to generate unique course-ID';
                   7371:         }
                   7372:     }
                   7373:     return $uname;
                   7374: }
                   7375: 
1.813     albertel 7376: sub is_course {
                   7377:     my ($cdom,$cnum) = @_;
                   7378:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7379: 				undef,'.');
1.813     albertel 7380:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7381:         return 1;
                   7382:     }
                   7383:     return 0;
                   7384: }
                   7385: 
1.1015    raeburn  7386: sub store_userdata {
                   7387:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7388:     my $result;
1.1016    raeburn  7389:     if ($datakey ne '') {
1.1013    raeburn  7390:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7391:             if ($udom eq '' || $uname eq '') {
                   7392:                 $udom = $env{'user.domain'};
                   7393:                 $uname = $env{'user.name'};
                   7394:             }
                   7395:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7396:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7397:                 $result = 'error: no_host';
                   7398:             } else {
                   7399:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7400:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7401: 
                   7402:                 my $namevalue='';
                   7403:                 foreach my $key (keys(%{$storehash})) {
                   7404:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7405:                 }
                   7406:                 $namevalue=~s/\&$//;
1.1056.4.24  raeburn  7407:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7408:                                   $namevalue,$uhome);
1.1013    raeburn  7409:             }
                   7410:         } else {
                   7411:             $result = 'error: data to store was not a hash reference'; 
                   7412:         }
                   7413:     } else {
                   7414:         $result= 'error: invalid requestkey'; 
                   7415:     }
                   7416:     return $result;
                   7417: }
                   7418: 
1.21      www      7419: # ---------------------------------------------------------- Assign Custom Role
                   7420: 
                   7421: sub assigncustomrole {
1.957     raeburn  7422:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7423:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7424:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7425: }
                   7426: 
                   7427: # ----------------------------------------------------------------- Revoke Role
                   7428: 
                   7429: sub revokerole {
1.957     raeburn  7430:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7431:     my $now=time;
1.965     raeburn  7432:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7433: }
                   7434: 
                   7435: # ---------------------------------------------------------- Revoke Custom Role
                   7436: 
                   7437: sub revokecustomrole {
1.957     raeburn  7438:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7439:     my $now=time;
1.357     www      7440:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7441:            $deleteflag,$selfenroll,$context);
1.17      www      7442: }
                   7443: 
1.533     banghart 7444: # ------------------------------------------------------------ Disk usage
1.535     albertel 7445: sub diskusage {
1.955     raeburn  7446:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7447:     $directorypath =~ s/\/$//;
                   7448:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7449:                        .&escape($getpropath).':'.&escape($uname).':'
                   7450:                        .&escape($udom),homeserver($uname,$udom));
                   7451:     if ($listing eq 'unknown_cmd') {
                   7452:         if ($getpropath) {
                   7453:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7454:         }
                   7455:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7456:     }
1.514     albertel 7457:     return $listing;
1.512     banghart 7458: }
                   7459: 
1.566     banghart 7460: sub is_locked {
1.1056.4.17  raeburn  7461:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7462:     my @check;
                   7463:     my $is_locked;
1.1056.4.14  raeburn  7464:     push(@check,$file_name);
1.613     albertel 7465:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7466: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7467:     my ($tmp)=keys(%locked);
                   7468:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7469:     
1.566     banghart 7470:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7471:         $is_locked = 'false';
                   7472:         foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17  raeburn  7473:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7474:                $is_locked = 'true';
1.1056.4.17  raeburn  7475:                if (ref($which) eq 'ARRAY') {
                   7476:                    push(@{$which},$entry);
                   7477:                } else {
                   7478:                    last;
                   7479:                }
1.745     raeburn  7480:            }
                   7481:        }
1.566     banghart 7482:     } else {
                   7483:         $is_locked = 'false';
                   7484:     }
1.1056.4.14  raeburn  7485:     return $is_locked;
1.566     banghart 7486: }
                   7487: 
1.759     albertel 7488: sub declutter_portfile {
                   7489:     my ($file) = @_;
1.833     albertel 7490:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7491:     return $file;
                   7492: }
                   7493: 
1.559     banghart 7494: # ------------------------------------------------------------- Mark as Read Only
                   7495: 
                   7496: sub mark_as_readonly {
                   7497:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7498:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7499:     my ($tmp)=keys(%current_permissions);
                   7500:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7501:     foreach my $file (@{$files}) {
1.759     albertel 7502: 	$file = &declutter_portfile($file);
1.561     banghart 7503:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7504:     }
1.613     albertel 7505:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7506:     return;
                   7507: }
                   7508: 
1.572     banghart 7509: # ------------------------------------------------------------Save Selected Files
                   7510: 
                   7511: sub save_selected_files {
                   7512:     my ($user, $path, @files) = @_;
                   7513:     my $filename = $user."savedfiles";
1.573     banghart 7514:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7515:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7516:     foreach my $file (@files) {
1.620     albertel 7517:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7518:     }
                   7519:     foreach my $file (@other_files) {
1.574     banghart 7520:         print (OUT $file."\n");
1.572     banghart 7521:     }
1.574     banghart 7522:     close (OUT);
1.572     banghart 7523:     return 'ok';
                   7524: }
                   7525: 
1.574     banghart 7526: sub clear_selected_files {
                   7527:     my ($user) = @_;
                   7528:     my $filename = $user."savedfiles";
                   7529:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7530:     print (OUT undef);
                   7531:     close (OUT);
                   7532:     return ("ok");    
                   7533: }
                   7534: 
1.572     banghart 7535: sub files_in_path {
                   7536:     my ($user, $path) = @_;
                   7537:     my $filename = $user."savedfiles";
                   7538:     my %return_files;
1.574     banghart 7539:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7540:     while (my $line_in = <IN>) {
1.574     banghart 7541:         chomp ($line_in);
                   7542:         my @paths_and_file = split (m!/!, $line_in);
                   7543:         my $file_part = pop (@paths_and_file);
                   7544:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7545:         $path_part.='/';
                   7546:         my $path_and_file = $path_part.$file_part;
                   7547:         if ($path_part eq $path) {
                   7548:             $return_files{$file_part}= 'selected';
                   7549:         }
                   7550:     }
1.574     banghart 7551:     close (IN);
                   7552:     return (\%return_files);
1.572     banghart 7553: }
                   7554: 
                   7555: # called in portfolio select mode, to show files selected NOT in current directory
                   7556: sub files_not_in_path {
                   7557:     my ($user, $path) = @_;
                   7558:     my $filename = $user."savedfiles";
                   7559:     my @return_files;
                   7560:     my $path_part;
1.800     albertel 7561:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7562:     while (my $line = <IN>) {
1.572     banghart 7563:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7564:         my @paths_and_file = split(m|/|, $line);
                   7565:         my $file_part = pop(@paths_and_file);
                   7566:         chomp($file_part);
                   7567:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7568:         $path_part .= '/';
                   7569:         my $path_and_file = $path_part.$file_part;
                   7570:         if ($path_part ne $path) {
1.800     albertel 7571:             push(@return_files, ($path_and_file));
1.572     banghart 7572:         }
                   7573:     }
1.800     albertel 7574:     close(OUT);
1.574     banghart 7575:     return (@return_files);
1.572     banghart 7576: }
                   7577: 
1.745     raeburn  7578: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7579: 
1.745     raeburn  7580: sub get_portfile_permissions {
                   7581:     my ($domain,$user) = @_;
1.613     albertel 7582:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7583:     my ($tmp)=keys(%current_permissions);
                   7584:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7585:     return \%current_permissions;
                   7586: }
                   7587: 
                   7588: #---------------------------------------------Get portfolio file access controls
                   7589: 
1.749     raeburn  7590: sub get_access_controls {
1.745     raeburn  7591:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7592:     my %access;
                   7593:     my $real_file = $file;
                   7594:     $file =~ s/\.meta$//;
1.745     raeburn  7595:     if (defined($file)) {
1.749     raeburn  7596:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7597:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7598:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7599:             }
                   7600:         }
1.745     raeburn  7601:     } else {
1.749     raeburn  7602:         foreach my $key (keys(%{$current_permissions})) {
                   7603:             if ($key =~ /\0accesscontrol$/) {
                   7604:                 if (defined($group)) {
                   7605:                     if ($key !~ m-^\Q$group\E/-) {
                   7606:                         next;
                   7607:                     }
                   7608:                 }
                   7609:                 my ($fullpath) = split(/\0/,$key);
                   7610:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7611:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7612:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7613:                     }
                   7614:                 }
                   7615:             }
                   7616:         }
                   7617:     }
                   7618:     return %access;
                   7619: }
                   7620: 
                   7621: sub modify_access_controls {
                   7622:     my ($file_name,$changes,$domain,$user)=@_;
                   7623:     my ($outcome,$deloutcome);
                   7624:     my %store_permissions;
                   7625:     my %new_values;
                   7626:     my %new_control;
                   7627:     my %translation;
                   7628:     my @deletions = ();
                   7629:     my $now = time;
                   7630:     if (exists($$changes{'activate'})) {
                   7631:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7632:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7633:             my $numnew = scalar(@newitems);
                   7634:             for (my $i=0; $i<$numnew; $i++) {
                   7635:                 my $newkey = $newitems[$i];
                   7636:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7637:                 if ($newkey =~ /^\d+:/) { 
                   7638:                     $newkey =~ s/^(\d+)/$newid/;
                   7639:                     $translation{$1} = $newid;
                   7640:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7641:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7642:                     $translation{$1} = $newid;
                   7643:                 }
1.749     raeburn  7644:                 $new_values{$file_name."\0".$newkey} = 
                   7645:                                           $$changes{'activate'}{$newitems[$i]};
                   7646:                 $new_control{$newkey} = $now;
                   7647:             }
                   7648:         }
                   7649:     }
                   7650:     my %todelete;
                   7651:     my %changed_items;
                   7652:     foreach my $action ('delete','update') {
                   7653:         if (exists($$changes{$action})) {
                   7654:             if (ref($$changes{$action}) eq 'HASH') {
                   7655:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7656:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7657:                     if ($action eq 'delete') { 
                   7658:                         $todelete{$itemnum} = 1;
                   7659:                     } else {
                   7660:                         $changed_items{$itemnum} = $key;
                   7661:                     }
                   7662:                 }
1.745     raeburn  7663:             }
                   7664:         }
1.749     raeburn  7665:     }
                   7666:     # get lock on access controls for file.
                   7667:     my $lockhash = {
                   7668:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7669:                                                        ':'.$env{'user.domain'},
                   7670:                    }; 
                   7671:     my $tries = 0;
                   7672:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7673:    
                   7674:     while (($gotlock ne 'ok') && $tries <3) {
                   7675:         $tries ++;
                   7676:         sleep 1;
                   7677:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7678:     }
                   7679:     if ($gotlock eq 'ok') {
                   7680:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7681:         my ($tmp)=keys(%curr_permissions);
                   7682:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7683:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7684:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7685:             if (ref($curr_controls) eq 'HASH') {
                   7686:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7687:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7688:                     if (defined($todelete{$itemnum})) {
                   7689:                         push(@deletions,$file_name."\0".$control_item);
                   7690:                     } else {
                   7691:                         if (defined($changed_items{$itemnum})) {
                   7692:                             $new_control{$changed_items{$itemnum}} = $now;
                   7693:                             push(@deletions,$file_name."\0".$control_item);
                   7694:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7695:                         } else {
                   7696:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7697:                         }
                   7698:                     }
1.745     raeburn  7699:                 }
                   7700:             }
                   7701:         }
1.970     raeburn  7702:         my ($group);
                   7703:         if (&is_course($domain,$user)) {
                   7704:             ($group,my $file) = split(/\//,$file_name,2);
                   7705:         }
1.749     raeburn  7706:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7707:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7708:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7709:         #  remove lock
                   7710:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7711:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7712:         my $sqlresult =
1.970     raeburn  7713:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7714:                                     $group);
1.749     raeburn  7715:     } else {
                   7716:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7717:     }
1.749     raeburn  7718:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7719: }
                   7720: 
1.827     raeburn  7721: sub make_public_indefinitely {
                   7722:     my ($requrl) = @_;
                   7723:     my $now = time;
                   7724:     my $action = 'activate';
                   7725:     my $aclnum = 0;
                   7726:     if (&is_portfolio_url($requrl)) {
                   7727:         my (undef,$udom,$unum,$file_name,$group) =
                   7728:             &parse_portfolio_url($requrl);
                   7729:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7730:         my %access_controls = &get_access_controls($current_perms,
                   7731:                                                    $group,$file_name);
                   7732:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7733:             my ($num,$scope,$end,$start) = 
                   7734:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7735:             if ($scope eq 'public') {
                   7736:                 if ($start <= $now && $end == 0) {
                   7737:                     $action = 'none';
                   7738:                 } else {
                   7739:                     $action = 'update';
                   7740:                     $aclnum = $num;
                   7741:                 }
                   7742:                 last;
                   7743:             }
                   7744:         }
                   7745:         if ($action eq 'none') {
                   7746:              return 'ok';
                   7747:         } else {
                   7748:             my %changes;
                   7749:             my $newend = 0;
                   7750:             my $newstart = $now;
                   7751:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7752:             $changes{$action}{$newkey} = {
                   7753:                 type => 'public',
                   7754:                 time => {
                   7755:                     start => $newstart,
                   7756:                     end   => $newend,
                   7757:                 },
                   7758:             };
                   7759:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7760:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7761:             return $outcome;
                   7762:         }
                   7763:     } else {
                   7764:         return 'invalid';
                   7765:     }
                   7766: }
                   7767: 
1.745     raeburn  7768: #------------------------------------------------------Get Marked as Read Only
                   7769: 
                   7770: sub get_marked_as_readonly {
                   7771:     my ($domain,$user,$what,$group) = @_;
                   7772:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7773:     my @readonly_files;
1.629     banghart 7774:     my $cmp1=$what;
                   7775:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7776:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7777:         if (defined($group)) {
                   7778:             if ($file_name !~ m-^\Q$group\E/-) {
                   7779:                 next;
                   7780:             }
                   7781:         }
1.561     banghart 7782:         if (ref($value) eq "ARRAY"){
                   7783:             foreach my $stored_what (@{$value}) {
1.629     banghart 7784:                 my $cmp2=$stored_what;
1.759     albertel 7785:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7786:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7787:                 }
1.629     banghart 7788:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7789:                     push(@readonly_files, $file_name);
1.745     raeburn  7790:                     last;
1.563     banghart 7791:                 } elsif (!defined($what)) {
                   7792:                     push(@readonly_files, $file_name);
1.745     raeburn  7793:                     last;
1.561     banghart 7794:                 }
                   7795:             }
1.745     raeburn  7796:         }
1.561     banghart 7797:     }
                   7798:     return @readonly_files;
                   7799: }
1.577     banghart 7800: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7801: 
1.577     banghart 7802: sub get_marked_as_readonly_hash {
1.745     raeburn  7803:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7804:     my %readonly_files;
1.745     raeburn  7805:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7806:         if (defined($group)) {
                   7807:             if ($file_name !~ m-^\Q$group\E/-) {
                   7808:                 next;
                   7809:             }
                   7810:         }
1.577     banghart 7811:         if (ref($value) eq "ARRAY"){
                   7812:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7813:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7814:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7815:                         if ($lock_descriptor eq 'graded') {
                   7816:                             $readonly_files{$file_name} = 'graded';
                   7817:                         } elsif ($lock_descriptor eq 'handback') {
                   7818:                             $readonly_files{$file_name} = 'handback';
                   7819:                         } else {
                   7820:                             if (!exists($readonly_files{$file_name})) {
                   7821:                                 $readonly_files{$file_name} = 'locked';
                   7822:                             }
                   7823:                         }
1.745     raeburn  7824:                     }
1.750     banghart 7825:                 } 
1.577     banghart 7826:             }
                   7827:         } 
                   7828:     }
                   7829:     return %readonly_files;
                   7830: }
1.559     banghart 7831: # ------------------------------------------------------------ Unmark as Read Only
                   7832: 
                   7833: sub unmark_as_readonly {
1.629     banghart 7834:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7835:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7836:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7837:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7838:     my $symb_crs = $what;
                   7839:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7840:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7841:     my ($tmp)=keys(%current_permissions);
                   7842:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7843:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7844:     foreach my $file (@readonly_files) {
1.759     albertel 7845: 	my $clean_file = &declutter_portfile($file);
                   7846: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7847: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7848:         my @new_locks;
                   7849:         my @del_keys;
                   7850:         if (ref($current_locks) eq "ARRAY"){
                   7851:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7852:                 my $compare=$locker;
1.749     raeburn  7853:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7854:                     $compare=join('',@{$locker});
1.746     raeburn  7855:                     if ($compare ne $symb_crs) {
                   7856:                         push(@new_locks, $locker);
                   7857:                     }
1.563     banghart 7858:                 }
                   7859:             }
1.650     albertel 7860:             if (scalar(@new_locks) > 0) {
1.563     banghart 7861:                 $current_permissions{$file} = \@new_locks;
                   7862:             } else {
                   7863:                 push(@del_keys, $file);
1.613     albertel 7864:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7865:                 delete($current_permissions{$file});
1.563     banghart 7866:             }
                   7867:         }
1.561     banghart 7868:     }
1.613     albertel 7869:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7870:     return;
                   7871: }
1.512     banghart 7872: 
1.17      www      7873: # ------------------------------------------------------------ Directory lister
                   7874: 
                   7875: sub dirlist {
1.955     raeburn  7876:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7877:     $uri=~s/^\///;
                   7878:     $uri=~s/\/$//;
1.253     stredwic 7879:     my ($udom, $uname);
1.955     raeburn  7880:     if ($getuserdir) {
1.253     stredwic 7881:         $udom = $userdomain;
                   7882:         $uname = $username;
1.955     raeburn  7883:     } else {
                   7884:         (undef,$udom,$uname)=split(/\//,$uri);
                   7885:         if(defined($userdomain)) {
                   7886:             $udom = $userdomain;
                   7887:         }
                   7888:         if(defined($username)) {
                   7889:             $uname = $username;
                   7890:         }
1.253     stredwic 7891:     }
1.955     raeburn  7892:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7893: 
1.955     raeburn  7894:     $dirRoot = $perlvar{'lonDocRoot'};
                   7895:     if (defined($getpropath)) {
                   7896:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7897:         $dirRoot =~ s/\/$//;
1.955     raeburn  7898:     } elsif (defined($getuserdir)) {
                   7899:         my $subdir=$uname.'__';
                   7900:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7901:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7902:                    ."/$udom/$subdir/$uname";
                   7903:     } elsif (defined($alternateRoot)) {
                   7904:         $dirRoot = $alternateRoot;
1.751     banghart 7905:     }
1.253     stredwic 7906: 
                   7907:     if($udom) {
                   7908:         if($uname) {
1.955     raeburn  7909:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7910:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7911:                               .':'.&escape($uname).':'.&escape($udom),
                   7912:                               &homeserver($uname,$udom));
                   7913:             if ($listing eq 'unknown_cmd') {
                   7914:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7915:                                   &homeserver($uname,$udom));
                   7916:             } else {
                   7917:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7918:             }
1.605     matthew  7919:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7920:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7921: 				  &homeserver($uname,$udom));
1.605     matthew  7922:                 @listing_results = split(/:/,$listing);
                   7923:             } else {
                   7924:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7925:             }
                   7926:             return @listing_results;
1.955     raeburn  7927:         } elsif(!$alternateRoot) {
1.800     albertel 7928:             my %allusers;
1.841     albertel 7929: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7930:  	    foreach my $tryserver (keys(%servers)) {
                   7931:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7932:                                   &escape($udom),$tryserver);
                   7933:                 if ($listing eq 'unknown_cmd') {
                   7934: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7935: 				      $udom, $tryserver);
                   7936:                 } else {
                   7937:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7938:                 }
1.841     albertel 7939: 		if ($listing eq 'unknown_cmd') {
                   7940: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7941: 				      $udom, $tryserver);
                   7942: 		    @listing_results = split(/:/,$listing);
                   7943: 		} else {
                   7944: 		    @listing_results =
                   7945: 			map { &unescape($_); } split(/:/,$listing);
                   7946: 		}
                   7947: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7948: 		    $listing_results[0] ne 'empty'       &&
                   7949: 		    $listing_results[0] ne 'con_lost') {
                   7950: 		    foreach my $line (@listing_results) {
                   7951: 			my ($entry) = split(/&/,$line,2);
                   7952: 			$allusers{$entry} = 1;
                   7953: 		    }
                   7954: 		}
1.253     stredwic 7955:             }
                   7956:             my $alluserstr='';
1.800     albertel 7957:             foreach my $user (sort(keys(%allusers))) {
                   7958:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7959:             }
                   7960:             $alluserstr=~s/:$//;
                   7961:             return split(/:/,$alluserstr);
                   7962:         } else {
1.800     albertel 7963:             return ('missing user name');
1.253     stredwic 7964:         }
1.955     raeburn  7965:     } elsif(!defined($getpropath)) {
1.841     albertel 7966:         my @all_domains = sort(&all_domains());
1.955     raeburn  7967:         foreach my $domain (@all_domains) {
                   7968:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7969:         }
                   7970:         return @all_domains;
                   7971:     } else {
1.800     albertel 7972:         return ('missing domain');
1.275     stredwic 7973:     }
                   7974: }
                   7975: 
                   7976: # --------------------------------------------- GetFileTimestamp
                   7977: # This function utilizes dirlist and returns the date stamp for
                   7978: # when it was last modified.  It will also return an error of -1
                   7979: # if an error occurs
                   7980: 
                   7981: sub GetFileTimestamp {
1.955     raeburn  7982:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7983:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7984:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7985:     my ($fileStat) = 
                   7986:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7987:                                  undef,$getuserdir);
1.275     stredwic 7988:     my @stats = split('&', $fileStat);
                   7989:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7990:         # @stats contains first the filename, then the stat output
                   7991:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7992:     } else {
                   7993:         return -1;
1.253     stredwic 7994:     }
1.26      www      7995: }
                   7996: 
1.712     albertel 7997: sub stat_file {
                   7998:     my ($uri) = @_;
1.787     albertel 7999:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8000: 
1.955     raeburn  8001:     my ($udom,$uname,$file);
1.712     albertel 8002:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8003: 	($udom,$uname,$file) =
1.811     albertel 8004: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8005: 	$file = 'userfiles/'.$file;
                   8006:     }
                   8007:     if ($uri =~ m-^/res/-) {
                   8008: 	($udom,$uname) = 
1.807     albertel 8009: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8010: 	$file = $uri;
                   8011:     }
                   8012: 
                   8013:     if (!$udom || !$uname || !$file) {
                   8014: 	# unable to handle the uri
                   8015: 	return ();
                   8016:     }
1.956     raeburn  8017:     my $getpropath;
                   8018:     if ($file =~ /^userfiles\//) {
                   8019:         $getpropath = 1;
                   8020:     }
1.955     raeburn  8021:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8022:     my @stats = split('&', $result);
1.721     banghart 8023:     
1.712     albertel 8024:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8025: 	shift(@stats); #filename is first
                   8026: 	return @stats;
                   8027:     }
                   8028:     return ();
                   8029: }
                   8030: 
1.26      www      8031: # -------------------------------------------------------- Value of a Condition
                   8032: 
1.713     albertel 8033: # gets the value of a specific preevaluated condition
                   8034: #    stored in the string  $env{user.state.<cid>}
                   8035: # or looks up a condition reference in the bighash and if if hasn't
                   8036: # already been evaluated recurses into docondval to get the value of
                   8037: # the condition, then memoizing it to 
                   8038: #   $env{user.state.<cid>.<condition>}
1.40      www      8039: sub directcondval {
                   8040:     my $number=shift;
1.620     albertel 8041:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8042: 	&Apache::lonuserstate::evalstate();
                   8043:     }
1.713     albertel 8044:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8045: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8046:     } elsif ($number =~ /^_/) {
                   8047: 	my $sub_condition;
                   8048: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8049: 		&GDBM_READER(),0640)) {
                   8050: 	    $sub_condition=$bighash{'conditions'.$number};
                   8051: 	    untie(%bighash);
                   8052: 	}
                   8053: 	my $value = &docondval($sub_condition);
1.949     raeburn  8054: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8055: 	return $value;
                   8056:     }
1.620     albertel 8057:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8058:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8059:     } else {
                   8060:        return 2;
                   8061:     }
                   8062: }
                   8063: 
1.713     albertel 8064: # get the collection of conditions for this resource
1.26      www      8065: sub condval {
                   8066:     my $condidx=shift;
1.54      www      8067:     my $allpathcond='';
1.713     albertel 8068:     foreach my $cond (split(/\|/,$condidx)) {
                   8069: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8070: 	    $allpathcond.=
                   8071: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8072: 	}
1.191     harris41 8073:     }
1.54      www      8074:     $allpathcond=~s/\|$//;
1.713     albertel 8075:     return &docondval($allpathcond);
                   8076: }
                   8077: 
                   8078: #evaluates an expression of conditions
                   8079: sub docondval {
                   8080:     my ($allpathcond) = @_;
                   8081:     my $result=0;
                   8082:     if ($env{'request.course.id'}
                   8083: 	&& defined($allpathcond)) {
                   8084: 	my $operand='|';
                   8085: 	my @stack;
                   8086: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8087: 	    if ($chunk eq '(') {
                   8088: 		push @stack,($operand,$result);
                   8089: 	    } elsif ($chunk eq ')') {
                   8090: 		my $before=pop @stack;
                   8091: 		if (pop @stack eq '&') {
                   8092: 		    $result=$result>$before?$before:$result;
                   8093: 		} else {
                   8094: 		    $result=$result>$before?$result:$before;
                   8095: 		}
                   8096: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8097: 		$operand=$chunk;
                   8098: 	    } else {
                   8099: 		my $new=directcondval($chunk);
                   8100: 		if ($operand eq '&') {
                   8101: 		    $result=$result>$new?$new:$result;
                   8102: 		} else {
                   8103: 		    $result=$result>$new?$result:$new;
                   8104: 		}
                   8105: 	    }
                   8106: 	}
1.26      www      8107:     }
                   8108:     return $result;
1.421     albertel 8109: }
                   8110: 
                   8111: # ---------------------------------------------------- Devalidate courseresdata
                   8112: 
                   8113: sub devalidatecourseresdata {
                   8114:     my ($coursenum,$coursedomain)=@_;
                   8115:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8116:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8117: }
                   8118: 
1.763     www      8119: 
1.200     www      8120: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8121: #
                   8122: #  Parameters:
                   8123: #      $coursenum    - Number of the course.
                   8124: #      $coursedomain - Domain at which the course was created.
                   8125: #  Returns:
                   8126: #     A hash of the course parameters along (I think) with timestamps
                   8127: #     and version info.
1.877     foxr     8128: 
1.624     albertel 8129: sub get_courseresdata {
                   8130:     my ($coursenum,$coursedomain)=@_;
1.200     www      8131:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8132:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8133:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8134:     my %dumpreply;
1.417     albertel 8135:     unless (defined($cached)) {
1.624     albertel 8136: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8137: 	$result=\%dumpreply;
1.251     albertel 8138: 	my ($tmp) = keys(%dumpreply);
                   8139: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8140: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8141: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8142: 	    return $tmp;
1.416     albertel 8143: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8144: 	    $result=undef;
1.599     albertel 8145: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8146: 	}
                   8147:     }
1.624     albertel 8148:     return $result;
                   8149: }
                   8150: 
1.633     albertel 8151: sub devalidateuserresdata {
                   8152:     my ($uname,$udom)=@_;
                   8153:     my $hashid="$udom:$uname";
                   8154:     &devalidate_cache_new('userres',$hashid);
                   8155: }
                   8156: 
1.624     albertel 8157: sub get_userresdata {
                   8158:     my ($uname,$udom)=@_;
                   8159:     #most student don\'t have any data set, check if there is some data
                   8160:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8161: 
                   8162:     my $hashid="$udom:$uname";
                   8163:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8164:     if (!defined($cached)) {
                   8165: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8166: 	$result=\%resourcedata;
                   8167: 	&do_cache_new('userres',$hashid,$result,600);
                   8168:     }
                   8169:     my ($tmp)=keys(%$result);
                   8170:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8171: 	return $result;
                   8172:     }
                   8173:     #error 2 occurs when the .db doesn't exist
                   8174:     if ($tmp!~/error: 2 /) {
1.672     albertel 8175: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8176: 		 " Trying to get resource data for ".
                   8177: 		 $uname." at ".$udom.": ".
                   8178: 		 $tmp."</font>");
                   8179:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8180: 	#&EXT_cache_set($udom,$uname);
                   8181: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8182: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8183:     }
                   8184:     return $tmp;
                   8185: }
1.879     foxr     8186: #----------------------------------------------- resdata - return resource data
                   8187: #  Purpose:
                   8188: #    Return resource data for either users or for a course.
                   8189: #  Parameters:
                   8190: #     $name      - Course/user name.
                   8191: #     $domain    - Name of the domain the user/course is registered on.
                   8192: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8193: #     @which     - Array of names of resources desired.
                   8194: #  Returns:
                   8195: #     The value of the first reasource in @which that is found in the
                   8196: #     resource hash.
                   8197: #  Exceptional Conditions:
                   8198: #     If the $type passed in is not valid (not the string 'course' or 
                   8199: #     'user', an undefined  reference is returned.
                   8200: #     If none of the resources are found, an undef is returned
1.624     albertel 8201: sub resdata {
                   8202:     my ($name,$domain,$type,@which)=@_;
                   8203:     my $result;
                   8204:     if ($type eq 'course') {
                   8205: 	$result=&get_courseresdata($name,$domain);
                   8206:     } elsif ($type eq 'user') {
                   8207: 	$result=&get_userresdata($name,$domain);
                   8208:     }
                   8209:     if (!ref($result)) { return $result; }    
1.251     albertel 8210:     foreach my $item (@which) {
1.927     albertel 8211: 	if (defined($result->{$item->[0]})) {
                   8212: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8213: 	}
1.250     albertel 8214:     }
1.291     albertel 8215:     return undef;
1.200     www      8216: }
                   8217: 
1.379     matthew  8218: #
                   8219: # EXT resource caching routines
                   8220: #
                   8221: 
                   8222: sub clear_EXT_cache_status {
1.383     albertel 8223:     &delenv('cache.EXT.');
1.379     matthew  8224: }
                   8225: 
                   8226: sub EXT_cache_status {
                   8227:     my ($target_domain,$target_user) = @_;
1.383     albertel 8228:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8229:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8230:         # We know already the user has no data
                   8231:         return 1;
                   8232:     } else {
                   8233:         return 0;
                   8234:     }
                   8235: }
                   8236: 
                   8237: sub EXT_cache_set {
                   8238:     my ($target_domain,$target_user) = @_;
1.383     albertel 8239:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8240:     #&appenv({$cachename => time});
1.379     matthew  8241: }
                   8242: 
1.28      www      8243: # --------------------------------------------------------- Value of a Variable
1.58      www      8244: sub EXT {
1.715     albertel 8245: 
1.395     albertel 8246:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8247:     unless ($varname) { return ''; }
1.218     albertel 8248:     #get real user name/domain, courseid and symb
                   8249:     my $courseid;
1.359     albertel 8250:     my $publicuser;
1.427     www      8251:     if ($symbparm) {
                   8252: 	$symbparm=&get_symb_from_alias($symbparm);
                   8253:     }
1.218     albertel 8254:     if (!($uname && $udom)) {
1.790     albertel 8255:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8256:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8257:     } else {
1.620     albertel 8258: 	$courseid=$env{'request.course.id'};
1.218     albertel 8259:     }
1.48      www      8260:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8261:     my $rest;
1.320     albertel 8262:     if (defined($therest[0])) {
1.48      www      8263:        $rest=join('.',@therest);
                   8264:     } else {
                   8265:        $rest='';
                   8266:     }
1.320     albertel 8267: 
1.57      www      8268:     my $qualifierrest=$qualifier;
                   8269:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8270:     my $spacequalifierrest=$space;
                   8271:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8272:     if ($realm eq 'user') {
1.48      www      8273: # --------------------------------------------------------------- user.resource
                   8274: 	if ($space eq 'resource') {
1.651     albertel 8275: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8276: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8277: 		 &&
1.744     albertel 8278: 		 ($symbparm eq &symbread()) ) {	
                   8279: 		# if we are in the middle of processing the resource the
                   8280: 		# get the value we are planning on committing
                   8281:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8282:                     return $Apache::lonhomework::results{$qualifierrest};
                   8283:                 } else {
                   8284:                     return $Apache::lonhomework::history{$qualifierrest};
                   8285:                 }
1.335     albertel 8286: 	    } else {
1.359     albertel 8287: 		my %restored;
1.620     albertel 8288: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8289: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8290: 		} else {
                   8291: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8292: 		}
1.335     albertel 8293: 		return $restored{$qualifierrest};
                   8294: 	    }
1.48      www      8295: # ----------------------------------------------------------------- user.access
                   8296:         } elsif ($space eq 'access') {
1.218     albertel 8297: 	    # FIXME - not supporting calls for a specific user
1.48      www      8298:             return &allowed($qualifier,$rest);
                   8299: # ------------------------------------------ user.preferences, user.environment
                   8300:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8301: 	    if (($uname eq $env{'user.name'}) &&
                   8302: 		($udom eq $env{'user.domain'})) {
                   8303: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8304: 	    } else {
1.359     albertel 8305: 		my %returnhash;
                   8306: 		if (!$publicuser) {
                   8307: 		    %returnhash=&userenvironment($udom,$uname,
                   8308: 						 $qualifierrest);
                   8309: 		}
1.218     albertel 8310: 		return $returnhash{$qualifierrest};
                   8311: 	    }
1.48      www      8312: # ----------------------------------------------------------------- user.course
                   8313:         } elsif ($space eq 'course') {
1.218     albertel 8314: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8315:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8316: # ------------------------------------------------------------------- user.role
                   8317:         } elsif ($space eq 'role') {
1.218     albertel 8318: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8319:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8320:             if ($qualifier eq 'value') {
                   8321: 		return $role;
                   8322:             } elsif ($qualifier eq 'extent') {
                   8323:                 return $where;
                   8324:             }
                   8325: # ----------------------------------------------------------------- user.domain
                   8326:         } elsif ($space eq 'domain') {
1.218     albertel 8327:             return $udom;
1.48      www      8328: # ------------------------------------------------------------------- user.name
                   8329:         } elsif ($space eq 'name') {
1.218     albertel 8330:             return $uname;
1.48      www      8331: # ---------------------------------------------------- Any other user namespace
1.29      www      8332:         } else {
1.359     albertel 8333: 	    my %reply;
                   8334: 	    if (!$publicuser) {
                   8335: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8336: 	    }
                   8337: 	    return $reply{$qualifierrest};
1.48      www      8338:         }
1.236     www      8339:     } elsif ($realm eq 'query') {
                   8340: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8341:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8342: 						[$spacequalifierrest]);
1.620     albertel 8343: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8344:    } elsif ($realm eq 'request') {
1.48      www      8345: # ------------------------------------------------------------- request.browser
                   8346:         if ($space eq 'browser') {
1.430     www      8347: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8348: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8349: 		    return 1;
                   8350: 		} else {
                   8351: 		    return 0;
                   8352: 		}
                   8353: 	    } else {
1.620     albertel 8354: 		return $env{'browser.'.$qualifier};
1.430     www      8355: 	    }
1.57      www      8356: # ------------------------------------------------------------ request.filename
                   8357:         } else {
1.620     albertel 8358:             return $env{'request.'.$spacequalifierrest};
1.29      www      8359:         }
1.28      www      8360:     } elsif ($realm eq 'course') {
1.48      www      8361: # ---------------------------------------------------------- course.description
1.620     albertel 8362:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8363:     } elsif ($realm eq 'resource') {
1.165     www      8364: 
1.620     albertel 8365: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8366: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8367: 	}
1.693     albertel 8368: 
                   8369: 	if ($space eq 'title') {
                   8370: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8371: 	    return &gettitle($symbparm);
                   8372: 	}
                   8373: 	
                   8374: 	if ($space eq 'map') {
                   8375: 	    my ($map) = &decode_symb($symbparm);
                   8376: 	    return &symbread($map);
                   8377: 	}
1.905     albertel 8378: 	if ($space eq 'filename') {
                   8379: 	    if ($symbparm) {
                   8380: 		return &clutter((&decode_symb($symbparm))[2]);
                   8381: 	    }
                   8382: 	    return &hreflocation('',$env{'request.filename'});
                   8383: 	}
1.693     albertel 8384: 
                   8385: 	my ($section, $group, @groups);
1.593     albertel 8386: 	my ($courselevelm,$courselevel);
1.539     albertel 8387: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8388: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8389: 
1.218     albertel 8390: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8391: 
1.60      www      8392: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8393: 	    my $symbp=$symbparm;
1.735     albertel 8394: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8395: 
                   8396: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8397: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8398: 
1.620     albertel 8399: 	    if (($env{'user.name'} eq $uname) &&
                   8400: 		($env{'user.domain'} eq $udom)) {
                   8401: 		$section=$env{'request.course.sec'};
1.733     raeburn  8402:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8403:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8404: 	    } else {
1.539     albertel 8405: 		if (! defined($usection)) {
1.551     albertel 8406: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8407: 		} else {
                   8408: 		    $section = $usection;
                   8409: 		}
1.733     raeburn  8410:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8411: 	    }
                   8412: 
                   8413: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8414: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8415: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8416: 
1.593     albertel 8417: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8418: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8419: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8420: 
1.60      www      8421: # ----------------------------------------------------------- first, check user
1.624     albertel 8422: 
                   8423: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8424: 				       ([$courselevelr,'resource'],
                   8425: 					[$courselevelm,'map'     ],
                   8426: 					[$courselevel, 'course'  ]));
1.931     albertel 8427: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8428: 
1.594     albertel 8429: # ------------------------------------------------ second, check some of course
1.684     raeburn  8430:             my $coursereply;
1.691     raeburn  8431:             if (@groups > 0) {
                   8432:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8433:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8434:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8435:             }
1.96      www      8436: 
1.684     raeburn  8437: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8438: 				  $env{'course.'.$courseid.'.domain'},
                   8439: 				  'course',
                   8440: 				  ([$seclevelr,   'resource'],
                   8441: 				   [$seclevelm,   'map'     ],
                   8442: 				   [$seclevel,    'course'  ],
                   8443: 				   [$courselevelr,'resource']));
                   8444: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8445: 
1.60      www      8446: # ------------------------------------------------------ third, check map parms
1.218     albertel 8447: 	    my %parmhash=();
                   8448: 	    my $thisparm='';
                   8449: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8450: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8451: 		    &GDBM_READER(),0640)) {
1.218     albertel 8452: 		$thisparm=$parmhash{$symbparm};
                   8453: 		untie(%parmhash);
                   8454: 	    }
1.927     albertel 8455: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8456: 	}
1.594     albertel 8457: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8458: 
1.218     albertel 8459: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8460: 	my $filename;
                   8461: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8462: 	if ($symbparm) {
1.409     www      8463: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8464: 	} else {
1.620     albertel 8465: 	    $filename=$env{'request.filename'};
1.282     albertel 8466: 	}
                   8467: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8468: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8469: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8470: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8471: 
1.927     albertel 8472: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8473: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8474: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8475: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8476: 				     $env{'course.'.$courseid.'.domain'},
                   8477: 				     'course',
1.927     albertel 8478: 				     ([$courselevelm,'map'   ],
                   8479: 				      [$courselevel, 'course']));
                   8480: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8481: 	}
1.145     www      8482: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8483: 	unless ($space eq '0') {
1.336     albertel 8484: 	    my @parts=split(/_/,$space);
                   8485: 	    my $id=pop(@parts);
                   8486: 	    my $part=join('_',@parts);
                   8487: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8488: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8489: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8490: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8491: 	}
1.395     albertel 8492: 	if ($recurse) { return undef; }
                   8493: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8494: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8495: # ---------------------------------------------------- Any other user namespace
                   8496:     } elsif ($realm eq 'environment') {
                   8497: # ----------------------------------------------------------------- environment
1.620     albertel 8498: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8499: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8500: 	} else {
1.770     albertel 8501: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8502: 		return '';
                   8503: 	    }
1.219     albertel 8504: 	    my %returnhash=&userenvironment($udom,$uname,
                   8505: 					    $spacequalifierrest);
                   8506: 	    return $returnhash{$spacequalifierrest};
                   8507: 	}
1.28      www      8508:     } elsif ($realm eq 'system') {
1.48      www      8509: # ----------------------------------------------------------------- system.time
                   8510: 	if ($space eq 'time') {
                   8511: 	    return time;
                   8512:         }
1.696     albertel 8513:     } elsif ($realm eq 'server') {
                   8514: # ----------------------------------------------------------------- system.time
                   8515: 	if ($space eq 'name') {
                   8516: 	    return $ENV{'SERVER_NAME'};
                   8517:         }
1.28      www      8518:     }
1.48      www      8519:     return '';
1.61      www      8520: }
                   8521: 
1.927     albertel 8522: sub get_reply {
                   8523:     my ($reply_value) = @_;
1.940     raeburn  8524:     if (ref($reply_value) eq 'ARRAY') {
                   8525:         if (wantarray) {
                   8526: 	    return @$reply_value;
                   8527:         }
                   8528:         return $reply_value->[0];
                   8529:     } else {
                   8530:         return $reply_value;
1.927     albertel 8531:     }
                   8532: }
                   8533: 
1.691     raeburn  8534: sub check_group_parms {
                   8535:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8536:     my @groupitems = ();
                   8537:     my $resultitem;
1.927     albertel 8538:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8539:     foreach my $group (@{$groups}) {
                   8540:         foreach my $level (@levels) {
1.927     albertel 8541:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8542:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8543:         }
                   8544:     }
                   8545:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8546:                             $env{'course.'.$courseid.'.domain'},
                   8547:                                      'course',@groupitems);
                   8548:     return $coursereply;
                   8549: }
                   8550: 
                   8551: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8552:     my ($courseid,@groups) = @_;
                   8553:     @groups = sort(@groups);
1.691     raeburn  8554:     return @groups;
                   8555: }
                   8556: 
1.395     albertel 8557: sub packages_tab_default {
                   8558:     my ($uri,$varname)=@_;
                   8559:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8560: 
                   8561:     my (@extension,@specifics,$do_default);
                   8562:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8563: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8564: 	if ($pack_type eq 'default') {
                   8565: 	    $do_default=1;
                   8566: 	} elsif ($pack_type eq 'extension') {
                   8567: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8568: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8569: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8570: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8571: 	}
                   8572:     }
                   8573:     # first look for a package that matches the requested part id
                   8574:     foreach my $package (@specifics) {
                   8575: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8576: 	next if ($pack_part ne $part);
                   8577: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8578: 	    return $packagetab{"$pack_type&$name&default"};
                   8579: 	}
                   8580:     }
                   8581:     # look for any possible matching non extension_ package
                   8582:     foreach my $package (@specifics) {
                   8583: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8584: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8585: 	    return $packagetab{"$pack_type&$name&default"};
                   8586: 	}
1.585     albertel 8587: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8588: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8589: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8590: 	}
                   8591:     }
1.738     albertel 8592:     # look for any posible extension_ match
                   8593:     foreach my $package (@extension) {
                   8594: 	my ($package,$pack_type)=@{$package};
                   8595: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8596: 	    return $packagetab{"$pack_type&$name&default"};
                   8597: 	}
                   8598: 	if (defined($packagetab{$package."&$name&default"})) {
                   8599: 	    return $packagetab{$package."&$name&default"};
                   8600: 	}
                   8601:     }
                   8602:     # look for a global default setting
                   8603:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8604: 	return $packagetab{"default&$name&default"};
                   8605:     }
1.395     albertel 8606:     return undef;
                   8607: }
                   8608: 
1.334     albertel 8609: sub add_prefix_and_part {
                   8610:     my ($prefix,$part)=@_;
                   8611:     my $keyroot;
                   8612:     if (defined($prefix) && $prefix !~ /^__/) {
                   8613: 	# prefix that has a part already
                   8614: 	$keyroot=$prefix;
                   8615:     } elsif (defined($prefix)) {
                   8616: 	# prefix that is missing a part
                   8617: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8618:     } else {
                   8619: 	# no prefix at all
                   8620: 	if (defined($part)) { $keyroot='_'.$part; }
                   8621:     }
                   8622:     return $keyroot;
                   8623: }
                   8624: 
1.71      www      8625: # ---------------------------------------------------------------- Get metadata
                   8626: 
1.599     albertel 8627: my %metaentry;
1.71      www      8628: sub metadata {
1.176     www      8629:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8630:     $uri=&declutter($uri);
1.288     albertel 8631:     # if it is a non metadata possible uri return quickly
1.529     albertel 8632:     if (($uri eq '') || 
                   8633: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8634: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26  raeburn  8635:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8636: 	return undef;
                   8637:     }
                   8638:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8639: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8640: 	return undef;
1.288     albertel 8641:     }
1.73      www      8642:     my $filename=$uri;
                   8643:     $uri=~s/\.meta$//;
1.172     www      8644: #
                   8645: # Is the metadata already cached?
1.177     www      8646: # Look at timestamp of caching
1.172     www      8647: # Everything is cached by the main uri, libraries are never directly cached
                   8648: #
1.428     albertel 8649:     if (!defined($liburi)) {
1.599     albertel 8650: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8651: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8652:     }
                   8653:     {
1.172     www      8654: #
                   8655: # Is this a recursive call for a library?
                   8656: #
1.599     albertel 8657: #	if (! exists($metacache{$uri})) {
                   8658: #	    $metacache{$uri}={};
                   8659: #	}
1.924     albertel 8660: 	my $cachetime = 60*60;
1.171     www      8661:         if ($liburi) {
                   8662: 	    $liburi=&declutter($liburi);
                   8663:             $filename=$liburi;
1.401     bowersj2 8664:         } else {
1.599     albertel 8665: 	    &devalidate_cache_new('meta',$uri);
                   8666: 	    undef(%metaentry);
1.401     bowersj2 8667: 	}
1.140     www      8668:         my %metathesekeys=();
1.73      www      8669:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8670: 	my $metastring;
1.924     albertel 8671: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8672: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8673: 	    $metastring = 
1.929     albertel 8674: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8675: 					  ('grade_target' => 'meta'));
                   8676: 	    $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26  raeburn  8677: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8678:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8679: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8680: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8681: 	    $metastring=&getfile($file);
1.489     albertel 8682: 	}
1.208     albertel 8683:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8684:         my $token;
1.140     www      8685:         undef %metathesekeys;
1.71      www      8686:         while ($token=$parser->get_token) {
1.339     albertel 8687: 	    if ($token->[0] eq 'S') {
                   8688: 		if (defined($token->[2]->{'package'})) {
1.172     www      8689: #
                   8690: # This is a package - get package info
                   8691: #
1.339     albertel 8692: 		    my $package=$token->[2]->{'package'};
                   8693: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8694: 		    if (defined($token->[2]->{'id'})) { 
                   8695: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8696: 		    }
1.599     albertel 8697: 		    if ($metaentry{':packages'}) {
                   8698: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8699: 		    } else {
1.599     albertel 8700: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8701: 		    }
1.736     albertel 8702: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8703: 			my $part=$keyroot;
                   8704: 			$part=~s/^\_//;
1.736     albertel 8705: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8706: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8707: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8708: 			    # ignore package.tab specified default values
                   8709:                             # here &package_tab_default() will fetch those
                   8710: 			    if ($subp eq 'default') { next; }
1.736     albertel 8711: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8712: 			    my $unikey;
                   8713: 			    if ($pack =~ /_0$/) {
                   8714: 				$unikey='parameter_0_'.$name;
                   8715: 				$part=0;
                   8716: 			    } else {
                   8717: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8718: 			    }
1.339     albertel 8719: 			    if ($subp eq 'display') {
                   8720: 				$value.=' [Part: '.$part.']';
                   8721: 			    }
1.599     albertel 8722: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8723: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8724: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8725: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8726: 			    }
1.599     albertel 8727: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8728: 				$metaentry{':'.$unikey}=
                   8729: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8730: 			    }
1.339     albertel 8731: 			}
                   8732: 		    }
                   8733: 		} else {
1.172     www      8734: #
                   8735: # This is not a package - some other kind of start tag
1.339     albertel 8736: #
                   8737: 		    my $entry=$token->[1];
                   8738: 		    my $unikey;
                   8739: 		    if ($entry eq 'import') {
                   8740: 			$unikey='';
                   8741: 		    } else {
                   8742: 			$unikey=$entry;
                   8743: 		    }
                   8744: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8745: 
                   8746: 		    if (defined($token->[2]->{'id'})) { 
                   8747: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8748: 		    }
1.175     www      8749: 
1.339     albertel 8750: 		    if ($entry eq 'import') {
1.175     www      8751: #
                   8752: # Importing a library here
1.339     albertel 8753: #
                   8754: 			if ($depthcount<20) {
                   8755: 			    my $location=$parser->get_text('/import');
                   8756: 			    my $dir=$filename;
                   8757: 			    $dir=~s|[^/]*$||;
                   8758: 			    $location=&filelocation($dir,$location);
1.736     albertel 8759: 			    my $metadata = 
                   8760: 				&metadata($uri,'keys', $location,$unikey,
                   8761: 					  $depthcount+1);
                   8762: 			    foreach my $meta (split(',',$metadata)) {
                   8763: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8764: 				$metathesekeys{$meta}=1;
1.339     albertel 8765: 			    }
                   8766: 			}
                   8767: 		    } else { 
                   8768: 			if (defined($token->[2]->{'name'})) { 
                   8769: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8770: 			}
                   8771: 			$metathesekeys{$unikey}=1;
1.736     albertel 8772: 			foreach my $param (@{$token->[3]}) {
                   8773: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8774: 				$token->[2]->{$param};
1.339     albertel 8775: 			}
                   8776: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8777: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8778: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8779: 		 # only ws inside the tag, and not in default, so use default
                   8780: 		 # as value
1.599     albertel 8781: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8782: 			} elsif ( $internaltext =~ /\S/ ) {
                   8783: 		  # something interesting inside the tag
                   8784: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8785: 			} else {
1.908     albertel 8786: 		  # no interesting values, don't set a default
1.339     albertel 8787: 			}
1.172     www      8788: # end of not-a-package not-a-library import
1.339     albertel 8789: 		    }
1.172     www      8790: # end of not-a-package start tag
1.339     albertel 8791: 		}
1.172     www      8792: # the next is the end of "start tag"
1.339     albertel 8793: 	    }
                   8794: 	}
1.483     albertel 8795: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8796: 	$extension = lc($extension);
                   8797: 	if ($extension eq 'htm') { $extension='html'; }
                   8798: 
1.737     albertel 8799: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8800: 	    #no specific packages #how's our extension
                   8801: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8802: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8803: 					 \%metathesekeys);
                   8804: 	}
1.883     albertel 8805: 
                   8806: 	if (!exists($metaentry{':packages'})
                   8807: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8808: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8809: 		#no specific packages well let's get default then
                   8810: 		if ($key!~/^default&/) { next; }
1.488     albertel 8811: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8812: 					     \%metathesekeys);
                   8813: 	    }
                   8814: 	}
1.338     www      8815: # are there custom rights to evaluate
1.599     albertel 8816: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8817: 
1.338     www      8818:     #
                   8819:     # Importing a rights file here
1.339     albertel 8820:     #
                   8821: 	    unless ($depthcount) {
1.599     albertel 8822: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8823: 		my $dir=$filename;
                   8824: 		$dir=~s|[^/]*$||;
                   8825: 		$location=&filelocation($dir,$location);
1.736     albertel 8826: 		my $rights_metadata =
                   8827: 		    &metadata($uri,'keys',$location,'_rights',
                   8828: 			      $depthcount+1);
                   8829: 		foreach my $rights (split(',',$rights_metadata)) {
                   8830: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8831: 		    $metathesekeys{$rights}=1;
1.339     albertel 8832: 		}
                   8833: 	    }
                   8834: 	}
1.737     albertel 8835: 	# uniqifiy package listing
                   8836: 	my %seen;
                   8837: 	my @uniq_packages =
                   8838: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8839: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8840: 
                   8841: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8842: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8843: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8844: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8845: # this is the end of "was not already recently cached
1.71      www      8846:     }
1.599     albertel 8847:     return $metaentry{':'.$what};
1.261     albertel 8848: }
                   8849: 
1.488     albertel 8850: sub metadata_create_package_def {
1.483     albertel 8851:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8852:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8853:     if ($subp eq 'default') { next; }
                   8854:     
1.599     albertel 8855:     if (defined($metaentry{':packages'})) {
                   8856: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8857:     } else {
1.599     albertel 8858: 	$metaentry{':packages'}=$package;
1.483     albertel 8859:     }
                   8860:     my $value=$packagetab{$key};
                   8861:     my $unikey;
                   8862:     $unikey='parameter_0_'.$name;
1.599     albertel 8863:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8864:     $$metathesekeys{$unikey}=1;
1.599     albertel 8865:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8866: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8867:     }
1.599     albertel 8868:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8869: 	$metaentry{':'.$unikey}=
                   8870: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8871:     }
                   8872: }
                   8873: 
1.261     albertel 8874: sub metadata_generate_part0 {
                   8875:     my ($metadata,$metacache,$uri) = @_;
                   8876:     my %allnames;
1.737     albertel 8877:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8878: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8879: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8880: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8881: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8882: 	    $allnames{$name}=$part;
                   8883: 	  }
                   8884: 	}
                   8885:     }
                   8886:     foreach my $name (keys(%allnames)) {
                   8887:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8888:       my $key=":parameter_0_$name";
1.261     albertel 8889:       $$metacache{"$key.part"}='0';
                   8890:       $$metacache{"$key.name"}=$name;
1.428     albertel 8891:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8892: 					   $allnames{$name}.'_'.$name.
                   8893: 					   '.type'};
1.428     albertel 8894:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8895: 			     '.display'};
1.644     www      8896:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8897:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8898:       $$metacache{"$key.display"}=$olddis;
                   8899:     }
1.71      www      8900: }
                   8901: 
1.764     albertel 8902: # ------------------------------------------------------ Devalidate title cache
                   8903: 
                   8904: sub devalidate_title_cache {
                   8905:     my ($url)=@_;
                   8906:     if (!$env{'request.course.id'}) { return; }
                   8907:     my $symb=&symbread($url);
                   8908:     if (!$symb) { return; }
                   8909:     my $key=$env{'request.course.id'}."\0".$symb;
                   8910:     &devalidate_cache_new('title',$key);
                   8911: }
                   8912: 
1.1014    droeschl 8913: # ------------------------------------------------- Get the title of a course
                   8914: 
                   8915: sub current_course_title {
                   8916:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8917: }
1.301     www      8918: # ------------------------------------------------- Get the title of a resource
                   8919: 
                   8920: sub gettitle {
                   8921:     my $urlsymb=shift;
                   8922:     my $symb=&symbread($urlsymb);
1.534     albertel 8923:     if ($symb) {
1.620     albertel 8924: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8925: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8926: 	if (defined($cached)) { 
                   8927: 	    return $result;
                   8928: 	}
1.534     albertel 8929: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8930: 	my $title='';
1.907     albertel 8931: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8932: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8933: 	} else {
                   8934: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8935: 		    &GDBM_READER(),0640)) {
                   8936: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8937: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8938: 		untie(%bighash);
                   8939: 	    }
1.534     albertel 8940: 	}
                   8941: 	$title=~s/\&colon\;/\:/gs;
                   8942: 	if ($title) {
1.599     albertel 8943: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8944: 	}
                   8945: 	$urlsymb=$url;
                   8946:     }
                   8947:     my $title=&metadata($urlsymb,'title');
                   8948:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8949:     return $title;
1.301     www      8950: }
1.613     albertel 8951: 
1.614     albertel 8952: sub get_slot {
                   8953:     my ($which,$cnum,$cdom)=@_;
                   8954:     if (!$cnum || !$cdom) {
1.790     albertel 8955: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8956: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8957: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8958:     }
1.703     albertel 8959:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8960:     my %slotinfo;
                   8961:     if (exists($remembered{$key})) {
                   8962: 	$slotinfo{$which} = $remembered{$key};
                   8963:     } else {
                   8964: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8965: 	&Apache::lonhomework::showhash(%slotinfo);
                   8966: 	my ($tmp)=keys(%slotinfo);
                   8967: 	if ($tmp=~/^error:/) { return (); }
                   8968: 	$remembered{$key} = $slotinfo{$which};
                   8969:     }
1.616     albertel 8970:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8971: 	return %{$slotinfo{$which}};
                   8972:     }
                   8973:     return $slotinfo{$which};
1.614     albertel 8974: }
1.31      www      8975: # ------------------------------------------------- Update symbolic store links
                   8976: 
                   8977: sub symblist {
                   8978:     my ($mapname,%newhash)=@_;
1.438     www      8979:     $mapname=&deversion(&declutter($mapname));
1.31      www      8980:     my %hash;
1.620     albertel 8981:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8982:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8983:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8984: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8985: 		next if ($url eq 'last_known'
                   8986: 			 && $env{'form.no_update_last_known'});
                   8987: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8988: 						    $newhash{$url}->[1],
                   8989: 						    $newhash{$url}->[0]);
1.191     harris41 8990:             }
1.31      www      8991:             if (untie(%hash)) {
                   8992: 		return 'ok';
                   8993:             }
                   8994:         }
                   8995:     }
                   8996:     return 'error';
1.212     www      8997: }
                   8998: 
                   8999: # --------------------------------------------------------------- Verify a symb
                   9000: 
                   9001: sub symbverify {
1.510     www      9002:     my ($symb,$thisurl)=@_;
                   9003:     my $thisfn=$thisurl;
1.439     www      9004:     $thisfn=&declutter($thisfn);
1.215     www      9005: # direct jump to resource in page or to a sequence - will construct own symbs
                   9006:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9007: # check URL part
1.409     www      9008:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9009: 
1.431     www      9010:     unless ($url eq $thisfn) { return 0; }
1.213     www      9011: 
1.216     www      9012:     $symb=&symbclean($symb);
1.510     www      9013:     $thisurl=&deversion($thisurl);
1.439     www      9014:     $thisfn=&deversion($thisfn);
1.213     www      9015: 
                   9016:     my %bighash;
                   9017:     my $okay=0;
1.431     www      9018: 
1.620     albertel 9019:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9020:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9021:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9022:             $thisurl =~ s/\?.+$//;
                   9023:         }
1.510     www      9024:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      9025:         unless ($ids) { 
1.1056.4.21  raeburn  9026:            my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
                   9027:            $ids=$bighash{$idkey};
1.216     www      9028:         }
                   9029:         if ($ids) {
                   9030: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9031: 	    foreach my $id (split(/\,/,$ids)) {
                   9032: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9033:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9034:                    $symb =~ s/\?.+$//;
                   9035:                }
1.216     www      9036:                if (
                   9037:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9038:    eq $symb) { 
1.620     albertel 9039: 		   if (($env{'request.role.adv'}) ||
1.1056.4.20  raeburn  9040: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9041: 		       ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9042: 		       $okay=1; 
                   9043: 		   }
                   9044: 	       }
1.216     www      9045: 	   }
                   9046:         }
1.213     www      9047: 	untie(%bighash);
                   9048:     }
                   9049:     return $okay;
1.31      www      9050: }
                   9051: 
1.210     www      9052: # --------------------------------------------------------------- Clean-up symb
                   9053: 
                   9054: sub symbclean {
                   9055:     my $symb=shift;
1.568     albertel 9056:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9057: # remove version from map
                   9058:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9059: 
1.210     www      9060: # remove version from URL
                   9061:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9062: 
1.507     www      9063: # remove wrapper
                   9064: 
1.510     www      9065:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9066:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9067:     return $symb;
1.409     www      9068: }
                   9069: 
                   9070: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9071: 
                   9072: sub encode_symb {
                   9073:     my ($map,$resid,$url)=@_;
                   9074:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9075: }
1.409     www      9076: 
                   9077: sub decode_symb {
1.568     albertel 9078:     my $symb=shift;
                   9079:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9080:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9081:     return (&fixversion($map),$resid,&fixversion($url));
                   9082: }
                   9083: 
                   9084: sub fixversion {
                   9085:     my $fn=shift;
1.609     banghart 9086:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9087:     my %bighash;
                   9088:     my $uri=&clutter($fn);
1.620     albertel 9089:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9090: # is this cached?
1.599     albertel 9091:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9092:     if (defined($cached)) { return $result; }
                   9093: # unfortunately not cached, or expired
1.620     albertel 9094:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9095: 	    &GDBM_READER(),0640)) {
                   9096:  	if ($bighash{'version_'.$uri}) {
                   9097:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9098:  	    unless (($version eq 'mostrecent') || 
                   9099: 		    ($version==&getversion($uri))) {
1.440     www      9100:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9101:  	    }
                   9102:  	}
                   9103:  	untie %bighash;
1.413     www      9104:     }
1.599     albertel 9105:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9106: }
                   9107: 
                   9108: sub deversion {
                   9109:     my $url=shift;
                   9110:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9111:     return $url;
1.210     www      9112: }
                   9113: 
1.31      www      9114: # ------------------------------------------------------ Return symb list entry
                   9115: 
                   9116: sub symbread {
1.249     www      9117:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9118:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9119:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9120: # no filename provided? try from environment
1.44      www      9121:     unless ($thisfn) {
1.620     albertel 9122:         if ($env{'request.symb'}) {
                   9123: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9124: 	}
1.620     albertel 9125: 	$thisfn=$env{'request.filename'};
1.44      www      9126:     }
1.569     albertel 9127:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9128: # is that filename actually a symb? Verify, clean, and return
                   9129:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9130: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9131: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9132: 	}
1.242     www      9133:     }
1.44      www      9134:     $thisfn=declutter($thisfn);
1.31      www      9135:     my %hash;
1.37      www      9136:     my %bighash;
                   9137:     my $syval='';
1.620     albertel 9138:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9139:         my $targetfn = $thisfn;
1.609     banghart 9140:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9141:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9142:         }
1.687     albertel 9143: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9144: 	    $targetfn=$1;
                   9145: 	}
1.620     albertel 9146:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9147:                       &GDBM_READER(),0640)) {
1.481     raeburn  9148: 	    $syval=$hash{$targetfn};
1.37      www      9149:             untie(%hash);
                   9150:         }
                   9151: # ---------------------------------------------------------- There was an entry
                   9152:         if ($syval) {
1.601     albertel 9153: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9154: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9155: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9156: 		    #return $env{$cache_str}='';
1.601     albertel 9157: 		#}    
                   9158: 		#$syval.=$1;
                   9159: 	    #}
1.37      www      9160:         } else {
                   9161: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9162:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9163:                             &GDBM_READER(),0640)) {
1.37      www      9164: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9165:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9166:               unless ($ids) { 
                   9167:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9168:               }
                   9169:               unless ($ids) {
                   9170: # alias?
                   9171: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9172:               }
1.37      www      9173:               if ($ids) {
                   9174: # ------------------------------------------------------------------- Has ID(s)
                   9175:                  my @possibilities=split(/\,/,$ids);
1.39      www      9176:                  if ($#possibilities==0) {
                   9177: # ----------------------------------------------- There is only one possibility
1.37      www      9178: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9179: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9180: 						    $resid,$thisfn);
1.249     www      9181:                  } elsif (!$donotrecurse) {
1.39      www      9182: # ------------------------------------------ There is more than one possibility
                   9183:                      my $realpossible=0;
1.800     albertel 9184:                      foreach my $id (@possibilities) {
                   9185: 			 my $file=$bighash{'src_'.$id};
1.39      www      9186:                          if (&allowed('bre',$file)) {
1.800     albertel 9187:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9188:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9189: 				$realpossible++;
1.626     albertel 9190:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9191: 						    $resid,$thisfn);
1.39      www      9192:                             }
                   9193: 			 }
1.191     harris41 9194:                      }
1.39      www      9195: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9196:                  } else {
                   9197:                      $syval='';
1.37      www      9198:                  }
                   9199: 	      }
                   9200:               untie(%bighash)
1.481     raeburn  9201:            }
1.31      www      9202:         }
1.62      www      9203:         if ($syval) {
1.620     albertel 9204: 	    return $env{$cache_str}=$syval;
1.62      www      9205:         }
1.31      www      9206:     }
1.949     raeburn  9207:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9208:     return $env{$cache_str}='';
1.31      www      9209: }
                   9210: 
                   9211: # ---------------------------------------------------------- Return random seed
                   9212: 
1.32      www      9213: sub numval {
                   9214:     my $txt=shift;
                   9215:     $txt=~tr/A-J/0-9/;
                   9216:     $txt=~tr/a-j/0-9/;
                   9217:     $txt=~tr/K-T/0-9/;
                   9218:     $txt=~tr/k-t/0-9/;
                   9219:     $txt=~tr/U-Z/0-5/;
                   9220:     $txt=~tr/u-z/0-5/;
                   9221:     $txt=~s/\D//g;
1.564     albertel 9222:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9223:     return int($txt);
1.368     albertel 9224: }
                   9225: 
1.484     albertel 9226: sub numval2 {
                   9227:     my $txt=shift;
                   9228:     $txt=~tr/A-J/0-9/;
                   9229:     $txt=~tr/a-j/0-9/;
                   9230:     $txt=~tr/K-T/0-9/;
                   9231:     $txt=~tr/k-t/0-9/;
                   9232:     $txt=~tr/U-Z/0-5/;
                   9233:     $txt=~tr/u-z/0-5/;
                   9234:     $txt=~s/\D//g;
                   9235:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9236:     my $total;
                   9237:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9238:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9239:     return int($total);
                   9240: }
                   9241: 
1.575     albertel 9242: sub numval3 {
                   9243:     use integer;
                   9244:     my $txt=shift;
                   9245:     $txt=~tr/A-J/0-9/;
                   9246:     $txt=~tr/a-j/0-9/;
                   9247:     $txt=~tr/K-T/0-9/;
                   9248:     $txt=~tr/k-t/0-9/;
                   9249:     $txt=~tr/U-Z/0-5/;
                   9250:     $txt=~tr/u-z/0-5/;
                   9251:     $txt=~s/\D//g;
                   9252:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9253:     my $total;
                   9254:     foreach my $val (@txts) { $total+=$val; }
                   9255:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9256:     return $total;
                   9257: }
                   9258: 
1.675     albertel 9259: sub digest {
                   9260:     my ($data)=@_;
                   9261:     my $digest=&Digest::MD5::md5($data);
                   9262:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9263:     my ($e,$f);
                   9264:     {
                   9265:         use integer;
                   9266:         $e=($a+$b);
                   9267:         $f=($c+$d);
                   9268:         if ($_64bit) {
                   9269:             $e=(($e<<32)>>32);
                   9270:             $f=(($f<<32)>>32);
                   9271:         }
                   9272:     }
                   9273:     if (wantarray) {
                   9274: 	return ($e,$f);
                   9275:     } else {
                   9276: 	my $g;
                   9277: 	{
                   9278: 	    use integer;
                   9279: 	    $g=($e+$f);
                   9280: 	    if ($_64bit) {
                   9281: 		$g=(($g<<32)>>32);
                   9282: 	    }
                   9283: 	}
                   9284: 	return $g;
                   9285:     }
                   9286: }
                   9287: 
1.368     albertel 9288: sub latest_rnd_algorithm_id {
1.675     albertel 9289:     return '64bit5';
1.366     albertel 9290: }
1.32      www      9291: 
1.503     albertel 9292: sub get_rand_alg {
                   9293:     my ($courseid)=@_;
1.790     albertel 9294:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9295:     if ($courseid) {
1.620     albertel 9296: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9297:     }
                   9298:     return &latest_rnd_algorithm_id();
                   9299: }
                   9300: 
1.562     albertel 9301: sub validCODE {
                   9302:     my ($CODE)=@_;
                   9303:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9304:     return 0;
                   9305: }
                   9306: 
1.491     albertel 9307: sub getCODE {
1.620     albertel 9308:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9309:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9310: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9311: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9312: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9313:     }
                   9314:     return undef;
                   9315: }
                   9316: 
1.31      www      9317: sub rndseed {
1.155     albertel 9318:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9319:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9320:     if (!defined($symb)) {
1.366     albertel 9321: 	unless ($symb=$wsymb) { return time; }
                   9322:     }
                   9323:     if (!$courseid) { $courseid=$wcourseid; }
                   9324:     if (!$domain) { $domain=$wdomain; }
                   9325:     if (!$username) { $username=$wusername }
1.503     albertel 9326:     my $which=&get_rand_alg();
1.803     albertel 9327: 
1.491     albertel 9328:     if (defined(&getCODE())) {
1.675     albertel 9329: 	if ($which eq '64bit5') {
                   9330: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9331: 	} elsif ($which eq '64bit4') {
1.575     albertel 9332: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9333: 	} else {
                   9334: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9335: 	}
1.675     albertel 9336:     } elsif ($which eq '64bit5') {
                   9337: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9338:     } elsif ($which eq '64bit4') {
                   9339: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9340:     } elsif ($which eq '64bit3') {
                   9341: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9342:     } elsif ($which eq '64bit2') {
                   9343: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9344:     } elsif ($which eq '64bit') {
                   9345: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9346:     }
                   9347:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9348: }
                   9349: 
                   9350: sub rndseed_32bit {
                   9351:     my ($symb,$courseid,$domain,$username)=@_;
                   9352:     {
                   9353: 	use integer;
                   9354: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9355: 	my $symbseed=numval($symb) << 22;
                   9356: 	my $namechck=unpack("%32C*",$username) << 17;
                   9357: 	my $nameseed=numval($username) << 12;
                   9358: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9359: 	my $courseseed=unpack("%32C*",$courseid);
                   9360: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9361: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9362: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9363: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9364: 	return $num;
                   9365:     }
                   9366: }
                   9367: 
                   9368: sub rndseed_64bit {
                   9369:     my ($symb,$courseid,$domain,$username)=@_;
                   9370:     {
                   9371: 	use integer;
                   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;
                   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.564     albertel 9384: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9385: 	return "$num1,$num2";
1.155     albertel 9386:     }
1.366     albertel 9387: }
                   9388: 
1.443     albertel 9389: sub rndseed_64bit2 {
                   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=numval($symb) << 10;
                   9397: 	my $namechck=unpack("%32S*",$username.' ');
                   9398: 	
                   9399: 	my $nameseed=numval($username) << 21;
1.501     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 :$num:$symb");
1.803     albertel 9407: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9408: 	return "$num1,$num2";
                   9409:     }
                   9410: }
                   9411: 
                   9412: sub rndseed_64bit3 {
                   9413:     my ($symb,$courseid,$domain,$username)=@_;
                   9414:     {
                   9415: 	use integer;
                   9416: 	# strings need to be an even # of cahracters long, it it is odd the
                   9417:         # last characters gets thrown away
                   9418: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9419: 	my $symbseed=numval2($symb) << 10;
                   9420: 	my $namechck=unpack("%32S*",$username.' ');
                   9421: 	
                   9422: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9423: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9424: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9425: 	
                   9426: 	my $num1=$symbchck+$symbseed+$namechck;
                   9427: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9428: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9429: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9430: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9431: 	
1.503     albertel 9432: 	return "$num1:$num2";
1.443     albertel 9433:     }
                   9434: }
                   9435: 
1.575     albertel 9436: sub rndseed_64bit4 {
                   9437:     my ($symb,$courseid,$domain,$username)=@_;
                   9438:     {
                   9439: 	use integer;
                   9440: 	# strings need to be an even # of cahracters long, it it is odd the
                   9441:         # last characters gets thrown away
                   9442: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9443: 	my $symbseed=numval3($symb) << 10;
                   9444: 	my $namechck=unpack("%32S*",$username.' ');
                   9445: 	
                   9446: 	my $nameseed=numval3($username) << 21;
                   9447: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9448: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9449: 	
                   9450: 	my $num1=$symbchck+$symbseed+$namechck;
                   9451: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9452: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9453: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9454: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9455: 	
                   9456: 	return "$num1:$num2";
                   9457:     }
                   9458: }
                   9459: 
1.675     albertel 9460: sub rndseed_64bit5 {
                   9461:     my ($symb,$courseid,$domain,$username)=@_;
                   9462:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9463:     return "$num1:$num2";
                   9464: }
                   9465: 
1.366     albertel 9466: sub rndseed_CODE_64bit {
                   9467:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9468:     {
1.366     albertel 9469: 	use integer;
1.443     albertel 9470: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9471: 	my $symbseed=numval2($symb);
1.491     albertel 9472: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9473: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9474: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9475: 	my $num1=$symbseed+$CODEchck;
                   9476: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9477: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9478: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9479: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9480: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9481: 	return "$num1:$num2";
1.366     albertel 9482:     }
                   9483: }
                   9484: 
1.575     albertel 9485: sub rndseed_CODE_64bit4 {
                   9486:     my ($symb,$courseid,$domain,$username)=@_;
                   9487:     {
                   9488: 	use integer;
                   9489: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9490: 	my $symbseed=numval3($symb);
                   9491: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9492: 	my $CODEseed=numval3(&getCODE());
                   9493: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9494: 	my $num1=$symbseed+$CODEchck;
                   9495: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9496: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9497: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9498: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9499: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9500: 	return "$num1:$num2";
                   9501:     }
                   9502: }
                   9503: 
1.675     albertel 9504: sub rndseed_CODE_64bit5 {
                   9505:     my ($symb,$courseid,$domain,$username)=@_;
                   9506:     my $code = &getCODE();
                   9507:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9508:     return "$num1:$num2";
                   9509: }
                   9510: 
1.366     albertel 9511: sub setup_random_from_rndseed {
                   9512:     my ($rndseed)=@_;
1.503     albertel 9513:     if ($rndseed =~/([,:])/) {
                   9514: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9515: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9516:     } else {
                   9517: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9518:     }
1.36      albertel 9519: }
                   9520: 
1.474     albertel 9521: sub latest_receipt_algorithm_id {
1.835     albertel 9522:     return 'receipt3';
1.474     albertel 9523: }
                   9524: 
1.480     www      9525: sub recunique {
                   9526:     my $fucourseid=shift;
                   9527:     my $unique;
1.835     albertel 9528:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9529: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9530: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9531:     } else {
                   9532: 	$unique=$perlvar{'lonReceipt'};
                   9533:     }
                   9534:     return unpack("%32C*",$unique);
                   9535: }
                   9536: 
                   9537: sub recprefix {
                   9538:     my $fucourseid=shift;
                   9539:     my $prefix;
1.835     albertel 9540:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9541: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9542: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9543:     } else {
                   9544: 	$prefix=$perlvar{'lonHostID'};
                   9545:     }
                   9546:     return unpack("%32C*",$prefix);
                   9547: }
                   9548: 
1.76      www      9549: sub ireceipt {
1.474     albertel 9550:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9551: 
                   9552:     my $return =&recprefix($fucourseid).'-';
                   9553: 
                   9554:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9555: 	$env{'request.state'} eq 'construct') {
                   9556: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9557: 	return $return;
                   9558:     }
                   9559: 
1.76      www      9560:     my $cuname=unpack("%32C*",$funame);
                   9561:     my $cudom=unpack("%32C*",$fudom);
                   9562:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9563:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9564:     my $cunique=&recunique($fucourseid);
1.474     albertel 9565:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9566:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9567: 
1.790     albertel 9568: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9569: 			       
                   9570: 	$return.= ($cunique%$cuname+
                   9571: 		   $cunique%$cudom+
                   9572: 		   $cusymb%$cuname+
                   9573: 		   $cusymb%$cudom+
                   9574: 		   $cucourseid%$cuname+
                   9575: 		   $cucourseid%$cudom+
                   9576: 		   $cpart%$cuname+
                   9577: 		   $cpart%$cudom);
                   9578:     } else {
                   9579: 	$return.= ($cunique%$cuname+
                   9580: 		   $cunique%$cudom+
                   9581: 		   $cusymb%$cuname+
                   9582: 		   $cusymb%$cudom+
                   9583: 		   $cucourseid%$cuname+
                   9584: 		   $cucourseid%$cudom);
                   9585:     }
                   9586:     return $return;
1.76      www      9587: }
                   9588: 
                   9589: sub receipt {
1.474     albertel 9590:     my ($part)=@_;
1.790     albertel 9591:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9592:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9593: }
1.260     ng       9594: 
1.790     albertel 9595: sub whichuser {
                   9596:     my ($passedsymb)=@_;
                   9597:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9598:     if (defined($env{'form.grade_symb'})) {
                   9599: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9600: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9601: 	if (!$allowed &&
                   9602: 	    exists($env{'request.course.sec'}) &&
                   9603: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9604: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9605: 			      '/'.$env{'request.course.sec'});
                   9606: 	}
                   9607: 	if ($allowed) {
                   9608: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9609: 	    $courseid=$tmp_courseid;
                   9610: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9611: 	    ($name)=&get_env_multiple('form.grade_username');
                   9612: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9613: 	}
                   9614:     }
                   9615:     if (!$passedsymb) {
                   9616: 	$symb=&symbread();
                   9617:     } else {
                   9618: 	$symb=$passedsymb;
                   9619:     }
                   9620:     $courseid=$env{'request.course.id'};
                   9621:     $domain=$env{'user.domain'};
                   9622:     $name=$env{'user.name'};
                   9623:     if ($name eq 'public' && $domain eq 'public') {
                   9624: 	if (!defined($env{'form.username'})) {
                   9625: 	    $env{'form.username'}.=time.rand(10000000);
                   9626: 	}
                   9627: 	$name.=$env{'form.username'};
                   9628:     }
                   9629:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9630: 
                   9631: }
                   9632: 
1.36      albertel 9633: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9634: # returns either the contents of the file or 
                   9635: # -1 if the file doesn't exist
1.481     raeburn  9636: #
                   9637: # if the target is a file that was uploaded via DOCS, 
                   9638: # a check will be made to see if a current copy exists on the local server,
                   9639: # if it does this will be served, otherwise a copy will be retrieved from
                   9640: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9641: # the local server.   
1.472     albertel 9642: 
1.36      albertel 9643: sub getfile {
1.538     albertel 9644:     my ($file) = @_;
1.609     banghart 9645:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9646:     &repcopy($file);
                   9647:     return &readfile($file);
                   9648: }
                   9649: 
                   9650: sub repcopy_userfile {
                   9651:     my ($file)=@_;
1.609     banghart 9652:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9653:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9654:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9655: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9656:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9657:     if (-e "$file") {
1.828     www      9658: # we already have a local copy, check it out
1.538     albertel 9659: 	my @fileinfo = stat($file);
1.828     www      9660: 	my $rtncode;
                   9661: 	my $info;
1.538     albertel 9662: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9663: 	if ($lwpresp ne 'ok') {
1.828     www      9664: # there is no such file anymore, even though we had a local copy
1.482     albertel 9665: 	    if ($rtncode eq '404') {
1.538     albertel 9666: 		unlink($file);
1.482     albertel 9667: 	    }
                   9668: 	    return -1;
                   9669: 	}
                   9670: 	if ($info < $fileinfo[9]) {
1.828     www      9671: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9672: 	    return 'ok';
1.828     www      9673: 	} else {
                   9674: # the file is outdated, get rid of it
                   9675: 	    unlink($file);
1.482     albertel 9676: 	}
1.828     www      9677:     }
                   9678: # one way or the other, at this point, we don't have the file
                   9679: # construct the correct path for the file
                   9680:     my @parts = ($cdom,$cnum); 
                   9681:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9682: 	push @parts, split(/\//,$1);
                   9683:     }
                   9684:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9685:     foreach my $part (@parts) {
                   9686: 	$path .= '/'.$part;
                   9687: 	if (!-e $path) {
                   9688: 	    mkdir($path,0770);
1.482     albertel 9689: 	}
                   9690:     }
1.828     www      9691: # now the path exists for sure
                   9692: # get a user agent
                   9693:     my $ua=new LWP::UserAgent;
                   9694:     my $transferfile=$file.'.in.transfer';
                   9695: # FIXME: this should flock
                   9696:     if (-e $transferfile) { return 'ok'; }
                   9697:     my $request;
                   9698:     $uri=~s/^\///;
1.980     raeburn  9699:     my $homeserver = &homeserver($cnum,$cdom);
                   9700:     my $protocol = $protocol{$homeserver};
                   9701:     $protocol = 'http' if ($protocol ne 'https');
                   9702:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9703:     my $response=$ua->request($request,$transferfile);
                   9704: # did it work?
                   9705:     if ($response->is_error()) {
                   9706: 	unlink($transferfile);
                   9707: 	&logthis("Userfile repcopy failed for $uri");
                   9708: 	return -1;
                   9709:     }
                   9710: # worked, rename the transfer file
                   9711:     rename($transferfile,$file);
1.607     raeburn  9712:     return 'ok';
1.481     raeburn  9713: }
                   9714: 
1.517     albertel 9715: sub tokenwrapper {
                   9716:     my $uri=shift;
1.980     raeburn  9717:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9718:     $uri=~s|^/||;
1.620     albertel 9719:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9720:     my $token=$1;
1.552     albertel 9721:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9722:     if ($udom && $uname && $file) {
                   9723: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9724:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9725:         my $homeserver = &homeserver($uname,$udom);
                   9726:         my $protocol = $protocol{$homeserver};
                   9727:         $protocol = 'http' if ($protocol ne 'https');
                   9728:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9729:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9730:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9731:     } else {
                   9732:         return '/adm/notfound.html';
                   9733:     }
                   9734: }
                   9735: 
1.828     www      9736: # call with reqtype HEAD: get last modification time
                   9737: # call with reqtype GET: get the file contents
                   9738: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9739: #
1.481     raeburn  9740: sub getuploaded {
                   9741:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9742:     $uri=~s/^\///;
1.980     raeburn  9743:     my $homeserver = &homeserver($cnum,$cdom);
                   9744:     my $protocol = $protocol{$homeserver};
                   9745:     $protocol = 'http' if ($protocol ne 'https');
                   9746:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9747:     my $ua=new LWP::UserAgent;
                   9748:     my $request=new HTTP::Request($reqtype,$uri);
                   9749:     my $response=$ua->request($request);
                   9750:     $$rtncode = $response->code;
1.482     albertel 9751:     if (! $response->is_success()) {
                   9752: 	return 'failed';
                   9753:     }      
                   9754:     if ($reqtype eq 'HEAD') {
1.486     www      9755: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9756:     } elsif ($reqtype eq 'GET') {
                   9757: 	$$info = $response->content;
1.472     albertel 9758:     }
1.482     albertel 9759:     return 'ok';
1.36      albertel 9760: }
                   9761: 
1.481     raeburn  9762: sub readfile {
                   9763:     my $file = shift;
                   9764:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9765:     my $fh;
                   9766:     open($fh,"<$file");
                   9767:     my $a='';
1.800     albertel 9768:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9769:     return $a;
                   9770: }
                   9771: 
1.36      albertel 9772: sub filelocation {
1.590     banghart 9773:     my ($dir,$file) = @_;
                   9774:     my $location;
                   9775:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9776: 
                   9777:     if ($file =~ m-^/adm/-) {
                   9778: 	$file=~s-^/adm/wrapper/-/-;
                   9779: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9780:     }
1.882     albertel 9781: 
1.590     banghart 9782:     if ($file=~m:^/~:) { # is a contruction space reference
                   9783:         $location = $file;
                   9784:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9785:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9786: 	# is a correct contruction space reference
                   9787:         $location = $file;
1.956     raeburn  9788:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9789:         $location = $file;
1.609     banghart 9790:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9791:         my ($udom,$uname,$filename)=
1.811     albertel 9792:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9793:         my $home=&homeserver($uname,$udom);
                   9794:         my $is_me=0;
                   9795:         my @ids=&current_machine_ids();
                   9796:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9797:         if ($is_me) {
1.955     raeburn  9798:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9799:         } else {
                   9800:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9801:   	      $udom.'/'.$uname.'/'.$filename;
                   9802:         }
1.882     albertel 9803:     } elsif ($file =~ m-^/adm/-) {
                   9804: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9805:     } else {
                   9806:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9807:         $file=~s:^/res/:/:;
                   9808:         if ( !( $file =~ m:^/:) ) {
                   9809:             $location = $dir. '/'.$file;
                   9810:         } else {
                   9811:             $location = '/home/httpd/html/res'.$file;
                   9812:         }
1.59      albertel 9813:     }
1.590     banghart 9814:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9815:     while ($location=~m{/\.\./}) {
                   9816: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9817: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9818: 	} else {
                   9819: 	    $location=~ s{/\.\./}{/}g;
                   9820: 	}
                   9821:     } #remove dir/..
1.590     banghart 9822:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9823:     return $location;
1.46      www      9824: }
1.36      albertel 9825: 
1.46      www      9826: sub hreflocation {
                   9827:     my ($dir,$file)=@_;
1.980     raeburn  9828:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9829: 	$file=filelocation($dir,$file);
1.700     albertel 9830:     } elsif ($file=~m-^/adm/-) {
                   9831: 	$file=~s-^/adm/wrapper/-/-;
                   9832: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9833:     }
                   9834:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9835: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9836:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9837: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9838:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9839: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9840: 	    -/uploaded/$1/$2/-x;
1.46      www      9841:     }
1.913     albertel 9842:     if ($file=~ m{^/userfiles/}) {
                   9843: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9844:     }
1.462     albertel 9845:     return $file;
1.465     albertel 9846: }
                   9847: 
                   9848: sub current_machine_domains {
1.853     albertel 9849:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9850: }
                   9851: 
                   9852: sub machine_domains {
                   9853:     my ($hostname) = @_;
1.465     albertel 9854:     my @domains;
1.838     albertel 9855:     my %hostname = &all_hostnames();
1.465     albertel 9856:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9857: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9858: 	if ($hostname eq $name) {
1.844     albertel 9859: 	    push(@domains,&host_domain($id));
1.465     albertel 9860: 	}
                   9861:     }
                   9862:     return @domains;
                   9863: }
                   9864: 
                   9865: sub current_machine_ids {
1.853     albertel 9866:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9867: }
                   9868: 
                   9869: sub machine_ids {
                   9870:     my ($hostname) = @_;
                   9871:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9872:     my @ids;
1.888     albertel 9873:     my %name_to_host = &all_names();
1.889     albertel 9874:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9875: 	return @{ $name_to_host{$hostname} };
                   9876:     }
                   9877:     return;
1.31      www      9878: }
                   9879: 
1.824     raeburn  9880: sub additional_machine_domains {
                   9881:     my @domains;
                   9882:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9883:     while( my $line = <$fh>) {
                   9884:         $line =~ s/\s//g;
                   9885:         push(@domains,$line);
                   9886:     }
                   9887:     return @domains;
                   9888: }
                   9889: 
                   9890: sub default_login_domain {
                   9891:     my $domain = $perlvar{'lonDefDomain'};
                   9892:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9893:     foreach my $posdom (&current_machine_domains(),
                   9894:                         &additional_machine_domains()) {
                   9895:         if (lc($posdom) eq lc($testdomain)) {
                   9896:             $domain=$posdom;
                   9897:             last;
                   9898:         }
                   9899:     }
                   9900:     return $domain;
                   9901: }
                   9902: 
1.31      www      9903: # ------------------------------------------------------------- Declutters URLs
                   9904: 
                   9905: sub declutter {
                   9906:     my $thisfn=shift;
1.569     albertel 9907:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9908:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9909:     $thisfn=~s/^\///;
1.697     albertel 9910:     $thisfn=~s|^adm/wrapper/||;
                   9911:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9912:     $thisfn=~s/^res\///;
1.1032    raeburn  9913:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9914:         $thisfn=~s/\?.+$//;
                   9915:     }
1.268     www      9916:     return $thisfn;
                   9917: }
                   9918: 
                   9919: # ------------------------------------------------------------- Clutter up URLs
                   9920: 
                   9921: sub clutter {
                   9922:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9923:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9924: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9925:        $thisfn='/res'.$thisfn; 
                   9926:     }
1.1031    raeburn  9927:     if ($thisfn !~m|^/adm|) {
                   9928: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9929: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9930: 	} else {
                   9931: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9932: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9933: 	    if ($embstyle eq 'ssi'
                   9934: 		|| ($embstyle eq 'hdn')
                   9935: 		|| ($embstyle eq 'rat')
                   9936: 		|| ($embstyle eq 'prv')
                   9937: 		|| ($embstyle eq 'ign')) {
                   9938: 		#do nothing with these
                   9939: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9940: 		|| ($embstyle eq 'emb')
                   9941: 		|| ($embstyle eq 'wrp')) {
                   9942: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9943: 	    } elsif ($embstyle eq 'unk'
                   9944: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9945: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9946: 	    } else {
1.718     www      9947: #		&logthis("Got a blank emb style");
1.695     albertel 9948: 	    }
1.694     albertel 9949: 	}
                   9950:     }
1.31      www      9951:     return $thisfn;
1.12      www      9952: }
                   9953: 
1.787     albertel 9954: sub clutter_with_no_wrapper {
                   9955:     my $uri = &clutter(shift);
                   9956:     if ($uri =~ m-^/adm/-) {
                   9957: 	$uri =~ s-^/adm/wrapper/-/-;
                   9958: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9959:     }
                   9960:     return $uri;
                   9961: }
                   9962: 
1.557     albertel 9963: sub freeze_escape {
                   9964:     my ($value)=@_;
                   9965:     if (ref($value)) {
                   9966: 	$value=&nfreeze($value);
                   9967: 	return '__FROZEN__'.&escape($value);
                   9968:     }
                   9969:     return &escape($value);
                   9970: }
                   9971: 
1.11      www      9972: 
1.557     albertel 9973: sub thaw_unescape {
                   9974:     my ($value)=@_;
                   9975:     if ($value =~ /^__FROZEN__/) {
                   9976: 	substr($value,0,10,undef);
                   9977: 	$value=&unescape($value);
                   9978: 	return &thaw($value);
                   9979:     }
                   9980:     return &unescape($value);
                   9981: }
                   9982: 
1.436     albertel 9983: sub correct_line_ends {
                   9984:     my ($result)=@_;
                   9985:     $$result =~s/\r\n/\n/mg;
                   9986:     $$result =~s/\r/\n/mg;
1.415     albertel 9987: }
1.1       albertel 9988: # ================================================================ Main Program
                   9989: 
1.184     www      9990: sub goodbye {
1.204     albertel 9991:    &logthis("Starting Shut down");
1.443     albertel 9992: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9993:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9994: #converted
1.599     albertel 9995: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9996:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9997: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9998: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9999: #1.1 only
1.870     albertel 10000: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10001: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10002: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10003: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10004:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10005:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10006:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10007:    &flushcourselogs();
                   10008:    &logthis("Shutting down");
                   10009: }
                   10010: 
1.852     albertel 10011: sub get_dns {
1.869     albertel 10012:     my ($url,$func,$ignore_cache) = @_;
                   10013:     if (!$ignore_cache) {
                   10014: 	my ($content,$cached)=
                   10015: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10016: 	if ($cached) {
                   10017: 	    &$func($content);
                   10018: 	    return;
                   10019: 	}
                   10020:     }
                   10021: 
                   10022:     my %alldns;
1.852     albertel 10023:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10024:     foreach my $dns (<$config>) {
                   10025: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10026:         my $line = $1;
                   10027:         my ($host,$protocol) = split(/:/,$line);
                   10028:         if ($protocol ne 'https') {
                   10029:             $protocol = 'http';
                   10030:         }
                   10031: 	$alldns{$host} = $protocol;
1.869     albertel 10032:     }
                   10033:     while (%alldns) {
                   10034: 	my ($dns) = keys(%alldns);
1.852     albertel 10035: 	my $ua=new LWP::UserAgent;
1.1056.4.33  raeburn  10036:         $ua->timeout(30);
1.979     raeburn  10037: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10038: 	my $response=$ua->request($request);
1.979     raeburn  10039:         delete($alldns{$dns});
1.852     albertel 10040: 	next if ($response->is_error());
                   10041: 	my @content = split("\n",$response->content);
1.869     albertel 10042: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10043: 	&$func(\@content);
1.869     albertel 10044: 	return;
1.852     albertel 10045:     }
                   10046:     close($config);
1.871     albertel 10047:     my $which = (split('/',$url))[3];
                   10048:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10049:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10050:     my @content = <$config>;
                   10051:     &$func(\@content);
                   10052:     return;
1.852     albertel 10053: }
1.327     albertel 10054: # ------------------------------------------------------------ Read domain file
                   10055: {
1.852     albertel 10056:     my $loaded;
1.846     albertel 10057:     my %domain;
                   10058: 
1.852     albertel 10059:     sub parse_domain_tab {
                   10060: 	my ($lines) = @_;
                   10061: 	foreach my $line (@$lines) {
                   10062: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10063: 
1.846     albertel 10064: 	    chomp($line);
1.852     albertel 10065: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10066: 	    my %this_domain;
                   10067: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10068: 			       'lang_def', 'city', 'longi', 'lati',
                   10069: 			       'primary') {
                   10070: 		$this_domain{$field} = shift(@elements);
                   10071: 	    }
                   10072: 	    $domain{$name} = \%this_domain;
1.852     albertel 10073: 	}
                   10074:     }
1.864     albertel 10075: 
                   10076:     sub reset_domain_info {
                   10077: 	undef($loaded);
                   10078: 	undef(%domain);
                   10079:     }
                   10080: 
1.852     albertel 10081:     sub load_domain_tab {
1.869     albertel 10082: 	my ($ignore_cache) = @_;
                   10083: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10084: 	my $fh;
                   10085: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10086: 	    my @lines = <$fh>;
                   10087: 	    &parse_domain_tab(\@lines);
1.448     albertel 10088: 	}
1.852     albertel 10089: 	close($fh);
                   10090: 	$loaded = 1;
1.327     albertel 10091:     }
1.846     albertel 10092: 
                   10093:     sub domain {
1.852     albertel 10094: 	&load_domain_tab() if (!$loaded);
                   10095: 
1.846     albertel 10096: 	my ($name,$what) = @_;
                   10097: 	return if ( !exists($domain{$name}) );
                   10098: 
                   10099: 	if (!$what) {
                   10100: 	    return $domain{$name}{'description'};
                   10101: 	}
                   10102: 	return $domain{$name}{$what};
                   10103:     }
1.974     raeburn  10104: 
                   10105:     sub domain_info {
                   10106:         &load_domain_tab() if (!$loaded);
                   10107:         return %domain;
                   10108:     }
                   10109: 
1.327     albertel 10110: }
                   10111: 
                   10112: 
1.1       albertel 10113: # ------------------------------------------------------------- Read hosts file
                   10114: {
1.838     albertel 10115:     my %hostname;
1.844     albertel 10116:     my %hostdom;
1.845     albertel 10117:     my %libserv;
1.852     albertel 10118:     my $loaded;
1.888     albertel 10119:     my %name_to_host;
1.1056.4.6  raeburn  10120:     my %internetdom;
1.1056.4.25  raeburn  10121:     my %LC_dns_serv;
1.852     albertel 10122: 
                   10123:     sub parse_hosts_tab {
                   10124: 	my ($file) = @_;
                   10125: 	foreach my $configline (@$file) {
                   10126: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25  raeburn  10127:             chomp($configline);
                   10128:             if ($configline =~ /^\^/) {
                   10129:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10130:                     $LC_dns_serv{$1} = 1;
                   10131:                 }
                   10132:                 next;
                   10133:             }
1.1056.4.6  raeburn  10134: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10135: 	    $name=~s/\s//g;
                   10136: 	    if ($id && $domain && $role && $name) {
                   10137: 		$hostname{$id}=$name;
1.888     albertel 10138: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10139: 		$hostdom{$id}=$domain;
                   10140: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10141:                 if (defined($protocol)) {
                   10142:                     if ($protocol eq 'https') {
                   10143:                         $protocol{$id} = $protocol;
                   10144:                     } else {
                   10145:                         $protocol{$id} = 'http'; 
                   10146:                     }
1.968     raeburn  10147:                 } else {
1.969     raeburn  10148:                     $protocol{$id} = 'http';
1.968     raeburn  10149:                 }
1.1056.4.6  raeburn  10150:                 if (defined($intdom)) {
                   10151:                     $internetdom{$id} = $intdom;
                   10152:                 }
1.852     albertel 10153: 	    }
                   10154: 	}
                   10155:     }
1.864     albertel 10156:     
                   10157:     sub reset_hosts_info {
1.897     albertel 10158: 	&purge_remembered();
1.864     albertel 10159: 	&reset_domain_info();
                   10160: 	&reset_hosts_ip_info();
1.892     albertel 10161: 	undef(%name_to_host);
1.864     albertel 10162: 	undef(%hostname);
                   10163: 	undef(%hostdom);
                   10164: 	undef(%libserv);
                   10165: 	undef($loaded);
                   10166:     }
1.1       albertel 10167: 
1.852     albertel 10168:     sub load_hosts_tab {
1.869     albertel 10169: 	my ($ignore_cache) = @_;
                   10170: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10171: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10172: 	my @config = <$config>;
                   10173: 	&parse_hosts_tab(\@config);
                   10174: 	close($config);
                   10175: 	$loaded=1;
1.1       albertel 10176:     }
1.852     albertel 10177: 
1.838     albertel 10178:     sub hostname {
1.852     albertel 10179: 	&load_hosts_tab() if (!$loaded);
                   10180: 
1.838     albertel 10181: 	my ($lonid) = @_;
                   10182: 	return $hostname{$lonid};
                   10183:     }
1.845     albertel 10184: 
1.838     albertel 10185:     sub all_hostnames {
1.852     albertel 10186: 	&load_hosts_tab() if (!$loaded);
                   10187: 
1.838     albertel 10188: 	return %hostname;
                   10189:     }
1.845     albertel 10190: 
1.888     albertel 10191:     sub all_names {
                   10192: 	&load_hosts_tab() if (!$loaded);
                   10193: 
                   10194: 	return %name_to_host;
                   10195:     }
                   10196: 
1.974     raeburn  10197:     sub all_host_domain {
                   10198:         &load_hosts_tab() if (!$loaded);
                   10199:         return %hostdom;
                   10200:     }
                   10201: 
1.845     albertel 10202:     sub is_library {
1.852     albertel 10203: 	&load_hosts_tab() if (!$loaded);
                   10204: 
1.845     albertel 10205: 	return exists($libserv{$_[0]});
                   10206:     }
                   10207: 
                   10208:     sub all_library {
1.852     albertel 10209: 	&load_hosts_tab() if (!$loaded);
                   10210: 
1.845     albertel 10211: 	return %libserv;
                   10212:     }
                   10213: 
1.1056.4.2  raeburn  10214:     sub unique_library {
                   10215:         #2x reverse removes all hostnames that appear more than once
                   10216:         my %unique = reverse &all_library();
                   10217:         return reverse %unique;
                   10218:     }
                   10219: 
1.841     albertel 10220:     sub get_servers {
1.852     albertel 10221: 	&load_hosts_tab() if (!$loaded);
                   10222: 
1.841     albertel 10223: 	my ($domain,$type) = @_;
                   10224: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10225: 	                                          : %hostname;
                   10226: 	my %result;
1.842     albertel 10227: 	if (ref($domain) eq 'ARRAY') {
                   10228: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10229: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10230: 		    $result{$host} = $hostname;
                   10231: 		}
                   10232: 	    }
                   10233: 	} else {
                   10234: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10235: 		if ($hostdom{$host} eq $domain) {
                   10236: 		    $result{$host} = $hostname;
                   10237: 		}
1.841     albertel 10238: 	    }
                   10239: 	}
                   10240: 	return %result;
                   10241:     }
1.845     albertel 10242: 
1.1056.4.2  raeburn  10243:     sub get_unique_servers {
                   10244:         my %unique = reverse &get_servers(@_);
                   10245:         return reverse %unique;
                   10246:     }
                   10247: 
1.844     albertel 10248:     sub host_domain {
1.852     albertel 10249: 	&load_hosts_tab() if (!$loaded);
                   10250: 
1.844     albertel 10251: 	my ($lonid) = @_;
                   10252: 	return $hostdom{$lonid};
                   10253:     }
                   10254: 
1.841     albertel 10255:     sub all_domains {
1.852     albertel 10256: 	&load_hosts_tab() if (!$loaded);
                   10257: 
1.841     albertel 10258: 	my %seen;
                   10259: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10260: 	return @uniq;
                   10261:     }
1.1056.4.3  raeburn  10262: 
                   10263:     sub internet_dom {
                   10264:         &load_hosts_tab() if (!$loaded);
                   10265: 
                   10266:         my ($lonid) = @_;
                   10267:         return $internetdom{$lonid};
                   10268:     }
1.1056.4.27  raeburn  10269: 
                   10270:     sub is_LC_dns {
                   10271:         &load_hosts_tab() if (!$loaded);
                   10272: 
                   10273:         my ($hostname) = @_;
                   10274:         return exists($LC_dns_serv{$hostname});
                   10275:     }
                   10276: 
1.1       albertel 10277: }
                   10278: 
1.847     albertel 10279: { 
                   10280:     my %iphost;
1.856     albertel 10281:     my %name_to_ip;
                   10282:     my %lonid_to_ip;
1.869     albertel 10283: 
1.847     albertel 10284:     sub get_hosts_from_ip {
                   10285: 	my ($ip) = @_;
                   10286: 	my %iphosts = &get_iphost();
                   10287: 	if (ref($iphosts{$ip})) {
                   10288: 	    return @{$iphosts{$ip}};
                   10289: 	}
                   10290: 	return;
1.839     albertel 10291:     }
1.864     albertel 10292:     
                   10293:     sub reset_hosts_ip_info {
                   10294: 	undef(%iphost);
                   10295: 	undef(%name_to_ip);
                   10296: 	undef(%lonid_to_ip);
                   10297:     }
1.856     albertel 10298: 
                   10299:     sub get_host_ip {
                   10300: 	my ($lonid) = @_;
                   10301: 	if (exists($lonid_to_ip{$lonid})) {
                   10302: 	    return $lonid_to_ip{$lonid};
                   10303: 	}
                   10304: 	my $name=&hostname($lonid);
                   10305:    	my $ip = gethostbyname($name);
                   10306: 	return if (!$ip || length($ip) ne 4);
                   10307: 	$ip=inet_ntoa($ip);
                   10308: 	$name_to_ip{$name}   = $ip;
                   10309: 	$lonid_to_ip{$lonid} = $ip;
                   10310: 	return $ip;
                   10311:     }
1.847     albertel 10312:     
                   10313:     sub get_iphost {
1.869     albertel 10314: 	my ($ignore_cache) = @_;
1.894     albertel 10315: 
1.869     albertel 10316: 	if (!$ignore_cache) {
                   10317: 	    if (%iphost) {
                   10318: 		return %iphost;
                   10319: 	    }
                   10320: 	    my ($ip_info,$cached)=
                   10321: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10322: 	    if ($cached) {
                   10323: 		%iphost      = %{$ip_info->[0]};
                   10324: 		%name_to_ip  = %{$ip_info->[1]};
                   10325: 		%lonid_to_ip = %{$ip_info->[2]};
                   10326: 		return %iphost;
                   10327: 	    }
                   10328: 	}
1.894     albertel 10329: 
                   10330: 	# get yesterday's info for fallback
                   10331: 	my %old_name_to_ip;
                   10332: 	my ($ip_info,$cached)=
                   10333: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10334: 	if ($cached) {
                   10335: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10336: 	}
                   10337: 
1.888     albertel 10338: 	my %name_to_host = &all_names();
                   10339: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10340: 	    my $ip;
                   10341: 	    if (!exists($name_to_ip{$name})) {
                   10342: 		$ip = gethostbyname($name);
                   10343: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10344: 		    if (defined($old_name_to_ip{$name})) {
                   10345: 			$ip = $old_name_to_ip{$name};
                   10346: 			&logthis("Can't find $name defaulting to old $ip");
                   10347: 		    } else {
                   10348: 			&logthis("Name $name no IP found");
                   10349: 			next;
                   10350: 		    }
                   10351: 		} else {
                   10352: 		    $ip=inet_ntoa($ip);
1.847     albertel 10353: 		}
                   10354: 		$name_to_ip{$name} = $ip;
                   10355: 	    } else {
                   10356: 		$ip = $name_to_ip{$name};
1.653     albertel 10357: 	    }
1.888     albertel 10358: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10359: 		$lonid_to_ip{$id} = $ip;
                   10360: 	    }
                   10361: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10362: 	}
1.869     albertel 10363: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10364: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10365: 				      48*60*60);
1.869     albertel 10366: 
1.847     albertel 10367: 	return %iphost;
1.598     albertel 10368:     }
                   10369: 
1.992     raeburn  10370:     #
                   10371:     #  Given a DNS returns the loncapa host name for that DNS 
                   10372:     # 
                   10373:     sub host_from_dns {
                   10374:         my ($dns) = @_;
                   10375:         my @hosts;
                   10376:         my $ip;
                   10377: 
1.993     raeburn  10378:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10379:             $ip = $name_to_ip{$dns};
                   10380:         }
                   10381:         if (!$ip) {
                   10382:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10383:             if (length($ip) == 4) { 
                   10384: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10385:             }
                   10386:         }
                   10387:         if ($ip) {
                   10388: 	    @hosts = get_hosts_from_ip($ip);
                   10389: 	    return $hosts[0];
                   10390:         }
                   10391:         return undef;
1.986     foxr     10392:     }
1.992     raeburn  10393: 
1.1056.4.3  raeburn  10394:     sub get_internet_names {
                   10395:         my ($lonid) = @_;
                   10396:         return if ($lonid eq '');
                   10397:         my ($idnref,$cached)=
                   10398:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10399:         if ($cached) {
                   10400:             return $idnref;
                   10401:         }
                   10402:         my $ip = &get_host_ip($lonid);
                   10403:         my @hosts = &get_hosts_from_ip($ip);
                   10404:         my %iphost = &get_iphost();
                   10405:         my (@idns,%seen);
                   10406:         foreach my $id (@hosts) {
                   10407:             my $dom = &host_domain($id);
                   10408:             my $prim_id = &domain($dom,'primary');
                   10409:             my $prim_ip = &get_host_ip($prim_id);
                   10410:             next if ($seen{$prim_ip});
                   10411:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10412:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10413:                     my $intdom = &internet_dom($id);
                   10414:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10415:                         push(@idns,$intdom);
                   10416:                     }
                   10417:                 }
                   10418:             }
                   10419:             $seen{$prim_ip} = 1;
                   10420:         }
                   10421:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10422:     }
                   10423: 
                   10424: }
                   10425: 
                   10426: sub all_loncaparevs {
                   10427:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986     foxr     10428: }
                   10429: 
1.862     albertel 10430: BEGIN {
                   10431: 
                   10432: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10433:     unless ($readit) {
                   10434: {
                   10435:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10436:     %perlvar = (%perlvar,%{$configvars});
                   10437: }
                   10438: 
                   10439: 
1.1       albertel 10440: # ------------------------------------------------------ Read spare server file
                   10441: {
1.448     albertel 10442:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10443: 
                   10444:     while (my $configline=<$config>) {
                   10445:        chomp($configline);
1.284     matthew  10446:        if ($configline) {
1.784     albertel 10447: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10448: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10449: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10450:        }
                   10451:     }
1.448     albertel 10452:     close($config);
1.1       albertel 10453: }
1.11      www      10454: # ------------------------------------------------------------ Read permissions
                   10455: {
1.448     albertel 10456:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10457: 
                   10458:     while (my $configline=<$config>) {
1.448     albertel 10459: 	chomp($configline);
                   10460: 	if ($configline) {
                   10461: 	    my ($role,$perm)=split(/ /,$configline);
                   10462: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10463: 	}
1.11      www      10464:     }
1.448     albertel 10465:     close($config);
1.11      www      10466: }
                   10467: 
                   10468: # -------------------------------------------- Read plain texts for permissions
                   10469: {
1.448     albertel 10470:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10471: 
                   10472:     while (my $configline=<$config>) {
1.448     albertel 10473: 	chomp($configline);
                   10474: 	if ($configline) {
1.742     raeburn  10475: 	    my ($short,@plain)=split(/:/,$configline);
                   10476:             %{$prp{$short}} = ();
                   10477: 	    if (@plain > 0) {
                   10478:                 $prp{$short}{'std'} = $plain[0];
                   10479:                 for (my $i=1; $i<@plain; $i++) {
                   10480:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10481:                 }
                   10482:             }
1.448     albertel 10483: 	}
1.135     www      10484:     }
1.448     albertel 10485:     close($config);
1.135     www      10486: }
                   10487: 
                   10488: # ---------------------------------------------------------- Read package table
                   10489: {
1.448     albertel 10490:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10491: 
                   10492:     while (my $configline=<$config>) {
1.483     albertel 10493: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10494: 	chomp($configline);
                   10495: 	my ($short,$plain)=split(/:/,$configline);
                   10496: 	my ($pack,$name)=split(/\&/,$short);
                   10497: 	if ($plain ne '') {
                   10498: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10499: 	    $packagetab{$short}=$plain; 
                   10500: 	}
1.11      www      10501:     }
1.448     albertel 10502:     close($config);
1.329     matthew  10503: }
                   10504: 
1.1056.4.3  raeburn  10505: # ---------------------------------------------------------- Read loncaparev table
                   10506: {
                   10507:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10508:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10509:             while (my $configline=<$config>) {
                   10510:                 chomp($configline);
                   10511:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10512:                 $loncaparevs{$hostid}=$loncaparev;
                   10513:             }
                   10514:             close($config);
                   10515:         }
                   10516:     }
                   10517: }
                   10518: 
                   10519: # ---------------------------------------------------------- Read serverhostID table
                   10520: {
                   10521:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10522:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10523:             while (my $configline=<$config>) {
                   10524:                 chomp($configline);
                   10525:                 my ($name,$id)=split(/:/,$configline);
                   10526:                 $serverhomeIDs{$name}=$id;
                   10527:             }
                   10528:             close($config);
                   10529:         }
                   10530:     }
                   10531: }
                   10532: 
1.1056.4.5  raeburn  10533: {
                   10534:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10535:     if (-e $file) {
                   10536:         my $parser = HTML::LCParser->new($file);
                   10537:         while (my $token = $parser->get_token()) {
                   10538:             if ($token->[0] eq 'S') {
                   10539:                 my $item = $token->[1];
                   10540:                 my $name = $token->[2]{'name'};
                   10541:                 my $value = $token->[2]{'value'};
                   10542:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10543:                     my $release = $parser->get_text();
                   10544:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10545:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10546:                 }
                   10547:             }
                   10548:         }
                   10549:     }
                   10550: }
                   10551: 
1.1056.4.33  raeburn  10552: # ---------------------------------------------------------- Read managers table
                   10553: {
                   10554:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   10555:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   10556:             while (my $configline=<$config>) {
                   10557:                 chomp($configline);
                   10558:                 next if ($configline =~ /^\#/);
                   10559:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   10560:                     $managerstab{$configline} = 1;
                   10561:                 }
                   10562:             }
                   10563:             close($config);
                   10564:         }
                   10565:     }
                   10566: }
                   10567: 
1.329     matthew  10568: # ------------- set up temporary directory
                   10569: {
                   10570:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10571: 
1.11      www      10572: }
                   10573: 
1.794     albertel 10574: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10575: 				'compress_threshold'=> 20_000,
                   10576:  			        });
1.185     www      10577: 
1.281     www      10578: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10579: $dumpcount=0;
1.958     www      10580: $locknum=0;
1.22      www      10581: 
1.163     harris41 10582: &logtouch();
1.672     albertel 10583: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10584: $readit=1;
1.564     albertel 10585:     {
                   10586: 	use integer;
                   10587: 	my $test=(2**32)+1;
1.568     albertel 10588: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10589: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10590:     }
1.195     www      10591: }
1.1       albertel 10592: }
1.179     www      10593: 
1.1       albertel 10594: 1;
1.191     harris41 10595: __END__
                   10596: 
1.243     albertel 10597: =pod
                   10598: 
1.191     harris41 10599: =head1 NAME
                   10600: 
1.243     albertel 10601: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10602: 
                   10603: =head1 SYNOPSIS
                   10604: 
1.243     albertel 10605: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10606: 
                   10607:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10608: 
1.243     albertel 10609: Common parameters:
                   10610: 
                   10611: =over 4
                   10612: 
                   10613: =item *
                   10614: 
                   10615: $uname : an internal username (if $cname expecting a course Id specifically)
                   10616: 
                   10617: =item *
                   10618: 
                   10619: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10620: 
                   10621: =item *
                   10622: 
                   10623: $symb : a resource instance identifier
                   10624: 
                   10625: =item *
                   10626: 
                   10627: $namespace : the name of a .db file that contains the data needed or
                   10628: being set.
                   10629: 
                   10630: =back
                   10631: 
1.394     bowersj2 10632: =head1 OVERVIEW
1.191     harris41 10633: 
1.394     bowersj2 10634: lonnet provides subroutines which interact with the
                   10635: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10636: about classes, users, and resources.
1.243     albertel 10637: 
                   10638: For many of these objects you can also use this to store data about
                   10639: them or modify them in various ways.
1.191     harris41 10640: 
1.394     bowersj2 10641: =head2 Symbs
1.191     harris41 10642: 
1.394     bowersj2 10643: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10644: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10645: map, the resource number of the resource in the map, and the URL of
                   10646: the resource itself. The latter is somewhat redundant, but might help
                   10647: if maps change.
                   10648: 
                   10649: An example is
                   10650: 
                   10651:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10652: 
                   10653: The respective map entry is
                   10654: 
                   10655:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10656:   title="Problem 2">
                   10657:  </resource>
                   10658: 
                   10659: Symbs are used by the random number generator, as well as to store and
                   10660: restore data specific to a certain instance of for example a problem.
                   10661: 
                   10662: =head2 Storing And Retrieving Data
                   10663: 
                   10664: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10665: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10666: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10667: is is the non-critical message twin of cstore. These functions are for
                   10668: handlers to store a perl hash to a user's permanent data space in an
                   10669: easy manner, and to retrieve it again on another call. It is expected
                   10670: that a handler would use this once at the beginning to retrieve data,
                   10671: and then again once at the end to send only the new data back.
                   10672: 
                   10673: The data is stored in the user's data directory on the user's
                   10674: homeserver under the ID of the course.
                   10675: 
                   10676: The hash that is returned by restore will have all of the previous
                   10677: value for all of the elements of the hash.
                   10678: 
                   10679: Example:
                   10680: 
                   10681:  #creating a hash
                   10682:  my %hash;
                   10683:  $hash{'foo'}='bar';
                   10684: 
                   10685:  #storing it
                   10686:  &Apache::lonnet::cstore(\%hash);
                   10687: 
                   10688:  #changing a value
                   10689:  $hash{'foo'}='notbar';
                   10690: 
                   10691:  #adding a new value
                   10692:  $hash{'bar'}='foo';
                   10693:  &Apache::lonnet::cstore(\%hash);
                   10694: 
                   10695:  #retrieving the hash
                   10696:  my %history=&Apache::lonnet::restore();
                   10697: 
                   10698:  #print the hash
                   10699:  foreach my $key (sort(keys(%history))) {
                   10700:    print("\%history{$key} = $history{$key}");
                   10701:  }
                   10702: 
                   10703: Will print out:
1.191     harris41 10704: 
1.394     bowersj2 10705:  %history{1:foo} = bar
                   10706:  %history{1:keys} = foo:timestamp
                   10707:  %history{1:timestamp} = 990455579
                   10708:  %history{2:bar} = foo
                   10709:  %history{2:foo} = notbar
                   10710:  %history{2:keys} = foo:bar:timestamp
                   10711:  %history{2:timestamp} = 990455580
                   10712:  %history{bar} = foo
                   10713:  %history{foo} = notbar
                   10714:  %history{timestamp} = 990455580
                   10715:  %history{version} = 2
                   10716: 
                   10717: Note that the special hash entries C<keys>, C<version> and
                   10718: C<timestamp> were added to the hash. C<version> will be equal to the
                   10719: total number of versions of the data that have been stored. The
                   10720: C<timestamp> attribute will be the UNIX time the hash was
                   10721: stored. C<keys> is available in every historical section to list which
                   10722: keys were added or changed at a specific historical revision of a
                   10723: hash.
                   10724: 
                   10725: B<Warning>: do not store the hash that restore returns directly. This
                   10726: will cause a mess since it will restore the historical keys as if the
                   10727: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10728: 
1.394     bowersj2 10729: Calling convention:
1.191     harris41 10730: 
1.394     bowersj2 10731:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10732:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10733: 
1.394     bowersj2 10734: For more detailed information, see lonnet specific documentation.
1.191     harris41 10735: 
1.394     bowersj2 10736: =head1 RETURN MESSAGES
1.191     harris41 10737: 
1.394     bowersj2 10738: =over 4
1.191     harris41 10739: 
1.394     bowersj2 10740: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10741: 
1.394     bowersj2 10742: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10743: when the connection is brought back up
1.191     harris41 10744: 
1.394     bowersj2 10745: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10746: for later delivery
1.191     harris41 10747: 
1.967     bisitz   10748: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10749: 
1.394     bowersj2 10750: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10751: that was requested
1.191     harris41 10752: 
1.243     albertel 10753: =back
1.191     harris41 10754: 
1.243     albertel 10755: =head1 PUBLIC SUBROUTINES
1.191     harris41 10756: 
1.243     albertel 10757: =head2 Session Environment Functions
1.191     harris41 10758: 
1.243     albertel 10759: =over 4
1.191     harris41 10760: 
1.394     bowersj2 10761: =item * 
                   10762: X<appenv()>
1.949     raeburn  10763: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10764: the user envirnoment file, and will be restored for each access this
1.620     albertel 10765: user makes during this session, also modifies the %env for the current
1.949     raeburn  10766: process. Optional rolesarrayref - if defined contains a reference to an array
                   10767: of roles which are exempt from the restriction on modifying user.role entries 
                   10768: in the user's environment.db and in %env.    
1.191     harris41 10769: 
                   10770: =item *
1.394     bowersj2 10771: X<delenv()>
1.987     raeburn  10772: B<delenv($delthis,$regexp)>: removes all items from the session
                   10773: environment file that begin with $delthis. If the 
                   10774: optional second arg - $regexp - is true, $delthis is treated as a 
                   10775: regular expression, otherwise \Q$delthis\E is used. 
                   10776: The values are also deleted from the current processes %env.
1.191     harris41 10777: 
1.795     albertel 10778: =item * get_env_multiple($name) 
                   10779: 
                   10780: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10781: values may be defined and end up as an array ref.
                   10782: 
                   10783: returns an array of values
                   10784: 
1.243     albertel 10785: =back
                   10786: 
                   10787: =head2 User Information
1.191     harris41 10788: 
1.243     albertel 10789: =over 4
1.191     harris41 10790: 
                   10791: =item *
1.394     bowersj2 10792: X<queryauthenticate()>
                   10793: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10794: authentication scheme
                   10795: 
                   10796: =item *
1.394     bowersj2 10797: X<authenticate()>
1.1056.4.3  raeburn  10798: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10799: authenticate user from domain's lib servers (first use the current
                   10800: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10801: $checkdefauth is optional (value is 1 if a check should be made to
                   10802:    authenticate user using default authentication method, and allow
                   10803:    account creation if username does not have account in the domain).
                   10804: $clientcancheckhost is optional (value is 1 if checking whether the
                   10805:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10806: 
                   10807: =item *
1.394     bowersj2 10808: X<homeserver()>
                   10809: B<homeserver($uname,$udom)>: find the server which has
                   10810: the user's directory and files (there must be only one), this caches
                   10811: the answer, and also caches if there is a borken connection.
1.191     harris41 10812: 
                   10813: =item *
1.394     bowersj2 10814: X<idget()>
                   10815: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10816: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10817: username, and only 1 username per ID in a specific domain) (returns
                   10818: hash: id=>name,id=>name)
1.191     harris41 10819: 
                   10820: =item *
1.394     bowersj2 10821: X<idrget()>
                   10822: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10823: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10824: 
                   10825: =item *
1.394     bowersj2 10826: X<idput()>
                   10827: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10828: 
                   10829: =item *
1.394     bowersj2 10830: X<rolesinit()>
                   10831: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10832: 
                   10833: =item *
1.551     albertel 10834: X<getsection()>
                   10835: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10836: course $cname, return section name/number or '' for "not in course"
                   10837: and '-1' for "no section"
                   10838: 
                   10839: =item *
1.394     bowersj2 10840: X<userenvironment()>
                   10841: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10842: passed in @what from the requested user's environment, returns a hash
                   10843: 
1.858     raeburn  10844: =item * 
                   10845: X<userlog_query()>
1.859     albertel 10846: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10847: activity.log file. %filters defines filters applied when parsing the
                   10848: log file. These can be start or end timestamps, or the type of action
                   10849: - log to look for Login or Logout events, check for Checkin or
                   10850: Checkout, role for role selection. The response is in the form
                   10851: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10852: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10853: 
1.243     albertel 10854: =back
                   10855: 
                   10856: =head2 User Roles
                   10857: 
                   10858: =over 4
                   10859: 
                   10860: =item *
                   10861: 
1.810     raeburn  10862: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10863:  F: full access
                   10864:  U,I,K: authentication modes (cxx only)
                   10865:  '': forbidden
                   10866:  1: user needs to choose course
                   10867:  2: browse allowed
1.766     albertel 10868:  A: passphrase authentication needed
1.243     albertel 10869: 
                   10870: =item *
                   10871: 
                   10872: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10873: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10874: and course level
                   10875: 
                   10876: =item *
                   10877: 
1.988     raeburn  10878: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10879: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10880: $type is Course (default) or Community.
1.988     raeburn  10881: If $forcedefault evaluates to true, text returned will be default 
                   10882: text for $type. Otherwise, if this is a course, the text returned 
                   10883: will be a custom name for the role (if defined in the course's 
                   10884: environment).  If no custom name is defined the default is returned.
                   10885:    
1.832     raeburn  10886: =item *
                   10887: 
1.935     raeburn  10888: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10889: All arguments are optional. Returns a hash of a roles, either for
                   10890: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10891: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10892: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10893: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10894: For each key, value is set to colon-separated start and end times for
                   10895: the role.  If no username and domain are specified, will default to
1.934     raeburn  10896: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10897: of role statuses (active, future or previous), roles 
                   10898: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10899: to restrict the list of roles reported. If no array ref is 
                   10900: provided for types, will default to return only active roles.
1.834     albertel 10901: 
1.243     albertel 10902: =back
                   10903: 
                   10904: =head2 User Modification
                   10905: 
                   10906: =over 4
                   10907: 
                   10908: =item *
                   10909: 
1.957     raeburn  10910: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10911: user for the level given by URL.  Optional start and end dates (leave empty
                   10912: string or zero for "no date")
1.191     harris41 10913: 
                   10914: =item *
                   10915: 
1.243     albertel 10916: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10917: change a users, password, possible return values are: ok,
                   10918: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10919: refused
1.191     harris41 10920: 
                   10921: =item *
                   10922: 
1.243     albertel 10923: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10924: 
                   10925: =item *
                   10926: 
1.1056.4.1  raeburn  10927: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10928:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10929: 
                   10930: will update user information (firstname,middlename,lastname,generation,
                   10931: permanentemail), and if forceid is true, student/employee ID also.
                   10932: A user's institutional affiliation(s) can also be updated.
                   10933: User information fields will not be overwritten with empty entries 
                   10934: unless the field is included in the $candelete array reference.
                   10935: This array is included when a single user is modified via "Manage Users",
                   10936: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10937: 
                   10938: =item *
                   10939: 
1.286     matthew  10940: modifystudent
                   10941: 
1.957     raeburn  10942: modify a student's enrollment and identification information.
1.286     matthew  10943: The course id is resolved based on the current users environment.  
                   10944: This means the envoking user must be a course coordinator or otherwise
                   10945: associated with a course.
                   10946: 
1.297     matthew  10947: This call is essentially a wrapper for lonnet::modifyuser and
                   10948: lonnet::modify_student_enrollment
1.286     matthew  10949: 
                   10950: Inputs: 
                   10951: 
                   10952: =over 4
                   10953: 
1.957     raeburn  10954: =item B<$udom> Student's loncapa domain
1.286     matthew  10955: 
1.957     raeburn  10956: =item B<$uname> Student's loncapa login name
1.286     matthew  10957: 
1.964     bisitz   10958: =item B<$uid> Student/Employee ID
1.286     matthew  10959: 
1.957     raeburn  10960: =item B<$umode> Student's authentication mode
1.286     matthew  10961: 
1.957     raeburn  10962: =item B<$upass> Student's password
1.286     matthew  10963: 
1.957     raeburn  10964: =item B<$first> Student's first name
1.286     matthew  10965: 
1.957     raeburn  10966: =item B<$middle> Student's middle name
1.286     matthew  10967: 
1.957     raeburn  10968: =item B<$last> Student's last name
1.286     matthew  10969: 
1.957     raeburn  10970: =item B<$gene> Student's generation
1.286     matthew  10971: 
1.957     raeburn  10972: =item B<$usec> Student's section in course
1.286     matthew  10973: 
                   10974: =item B<$end> Unix time of the roles expiration
                   10975: 
                   10976: =item B<$start> Unix time of the roles start date
                   10977: 
                   10978: =item B<$forceid> If defined, allow $uid to be changed
                   10979: 
                   10980: =item B<$desiredhome> server to use as home server for student
                   10981: 
1.957     raeburn  10982: =item B<$email> Student's permanent e-mail address
                   10983: 
                   10984: =item B<$type> Type of enrollment (auto or manual)
                   10985: 
1.963     raeburn  10986: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10987: 
                   10988: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10989: 
1.963     raeburn  10990: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10991: 
1.963     raeburn  10992: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10993: 
1.963     raeburn  10994: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10995: 
1.286     matthew  10996: =back
1.297     matthew  10997: 
                   10998: =item *
                   10999: 
                   11000: modify_student_enrollment
                   11001: 
                   11002: Change a students enrollment status in a class.  The environment variable
                   11003: 'role.request.course' must be defined for this function to proceed.
                   11004: 
                   11005: Inputs:
                   11006: 
                   11007: =over 4
                   11008: 
                   11009: =item $udom, students domain
                   11010: 
                   11011: =item $uname, students name
                   11012: 
                   11013: =item $uid, students user id
                   11014: 
                   11015: =item $first, students first name
                   11016: 
                   11017: =item $middle
                   11018: 
                   11019: =item $last
                   11020: 
                   11021: =item $gene
                   11022: 
                   11023: =item $usec
                   11024: 
                   11025: =item $end
                   11026: 
                   11027: =item $start
                   11028: 
1.957     raeburn  11029: =item $type
                   11030: 
                   11031: =item $locktype
                   11032: 
                   11033: =item $cid
                   11034: 
                   11035: =item $selfenroll
                   11036: 
                   11037: =item $context
                   11038: 
1.297     matthew  11039: =back
                   11040: 
1.191     harris41 11041: 
                   11042: =item *
                   11043: 
1.243     albertel 11044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11045: custom role; give a custom role to a user for the level given by URL.  Specify
                   11046: name and domain of role author, and role name
1.191     harris41 11047: 
                   11048: =item *
                   11049: 
1.243     albertel 11050: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11051: 
                   11052: =item *
                   11053: 
1.243     albertel 11054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11055: 
                   11056: =back
                   11057: 
                   11058: =head2 Course Infomation
                   11059: 
                   11060: =over 4
1.191     harris41 11061: 
                   11062: =item *
                   11063: 
1.631     albertel 11064: coursedescription($courseid) : returns a hash of information about the
                   11065: specified course id, including all environment settings for the
                   11066: course, the description of the course will be in the hash under the
                   11067: key 'description'
1.191     harris41 11068: 
                   11069: =item *
                   11070: 
1.624     albertel 11071: resdata($name,$domain,$type,@which) : request for current parameter
                   11072: setting for a specific $type, where $type is either 'course' or 'user',
                   11073: @what should be a list of parameters to ask about. This routine caches
                   11074: answers for 5 minutes.
1.243     albertel 11075: 
1.877     foxr     11076: =item *
                   11077: 
                   11078: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11079: data base, returning a hash that is keyed by the resource name and has
                   11080: values that are the resource value.  I believe that the timestamps and
                   11081: versions are also returned.
                   11082: 
                   11083: 
1.243     albertel 11084: =back
                   11085: 
                   11086: =head2 Course Modification
                   11087: 
                   11088: =over 4
1.191     harris41 11089: 
                   11090: =item *
                   11091: 
1.243     albertel 11092: writecoursepref($courseid,%prefs) : write preferences (environment
                   11093: database) for a course
1.191     harris41 11094: 
                   11095: =item *
                   11096: 
1.1011    raeburn  11097: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11098: 
                   11099: =item *
                   11100: 
1.1038    raeburn  11101: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11102: 
                   11103: =back
                   11104: 
                   11105: =head2 Resource Subroutines
                   11106: 
                   11107: =over 4
1.191     harris41 11108: 
                   11109: =item *
                   11110: 
1.243     albertel 11111: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11112: 
                   11113: =item *
                   11114: 
1.243     albertel 11115: repcopy($filename) : subscribes to the requested file, and attempts to
                   11116: replicate from the owning library server, Might return
1.607     raeburn  11117: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11118: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11119: resource. Expects the local filesystem pathname
                   11120: (/home/httpd/html/res/....)
                   11121: 
                   11122: =back
                   11123: 
                   11124: =head2 Resource Information
                   11125: 
                   11126: =over 4
1.191     harris41 11127: 
                   11128: =item *
                   11129: 
1.243     albertel 11130: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11131: a vairety of different possible values, $varname should be a request
                   11132: string, and the other parameters can be used to specify who and what
                   11133: one is asking about.
                   11134: 
                   11135: Possible values for $varname are environment.lastname (or other item
                   11136: from the envirnment hash), user.name (or someother aspect about the
                   11137: user), resource.0.maxtries (or some other part and parameter of a
                   11138: resource)
1.204     albertel 11139: 
                   11140: =item *
                   11141: 
1.243     albertel 11142: directcondval($number) : get current value of a condition; reads from a state
                   11143: string
1.204     albertel 11144: 
                   11145: =item *
                   11146: 
1.243     albertel 11147: condval($condidx) : value of condition index based on state
1.204     albertel 11148: 
                   11149: =item *
                   11150: 
1.243     albertel 11151: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11152: resource's metadata, $what should be either a specific key, or either
                   11153: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11154: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11155: 
                   11156: this function automatically caches all requests
1.191     harris41 11157: 
                   11158: =item *
                   11159: 
1.243     albertel 11160: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11161: network of library servers; returns file handle of where SQL and regex results
                   11162: will be stored for query
1.191     harris41 11163: 
                   11164: =item *
                   11165: 
1.243     albertel 11166: symbread($filename) : return symbolic list entry (filename argument optional);
                   11167: returns the data handle
1.191     harris41 11168: 
                   11169: =item *
                   11170: 
1.243     albertel 11171: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11172: a possible symb for the URL in $thisfn, and if is an encryypted
                   11173: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11174: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11175: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11176: 
1.191     harris41 11177: 
                   11178: =item *
                   11179: 
1.243     albertel 11180: symbclean($symb) : removes versions numbers from a symb, returns the
                   11181: cleaned symb
1.191     harris41 11182: 
                   11183: =item *
                   11184: 
1.243     albertel 11185: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11186: course map, user must be in a course for it to work.
1.191     harris41 11187: 
                   11188: =item *
                   11189: 
1.243     albertel 11190: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11191: 
                   11192: =item *
                   11193: 
1.243     albertel 11194: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11195: a random seed, all arguments are optional, if they aren't sent it uses the
                   11196: environment to derive them. Note: if symb isn't sent and it can't get one
                   11197: from &symbread it will use the current time as its return value
1.191     harris41 11198: 
                   11199: =item *
                   11200: 
1.243     albertel 11201: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11202: unfakeable, receipt
1.191     harris41 11203: 
                   11204: =item *
                   11205: 
1.620     albertel 11206: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11207: 
                   11208: =item *
                   11209: 
1.243     albertel 11210: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11211: 
                   11212: =item *
                   11213: 
1.243     albertel 11214: 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 11215: 
                   11216: =item *
                   11217: 
1.243     albertel 11218: 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 11219: 
                   11220: =item *
                   11221: 
1.243     albertel 11222: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11223: 
                   11224: =item *
                   11225: 
1.243     albertel 11226: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11227: forcing spreadsheet to reevaluate the resource scores next time.
                   11228: 
                   11229: =back
                   11230: 
                   11231: =head2 Storing/Retreiving Data
                   11232: 
                   11233: =over 4
1.191     harris41 11234: 
                   11235: =item *
                   11236: 
1.243     albertel 11237: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11238: for this url; hashref needs to be given and should be a \%hashname; the
                   11239: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11240: be derived from the env
1.191     harris41 11241: 
                   11242: =item *
                   11243: 
1.243     albertel 11244: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11245: uses critical subroutine
1.191     harris41 11246: 
                   11247: =item *
                   11248: 
1.243     albertel 11249: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11250: all args are optional
1.191     harris41 11251: 
                   11252: =item *
                   11253: 
1.717     albertel 11254: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11255: dumps the complete (or key matching regexp) namespace into a hash
                   11256: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11257: normally &store()ed into
                   11258: 
                   11259: $range should be either an integer '100' (give me the first 100
                   11260:                                            matching records)
                   11261:               or be  two integers sperated by a - with no spaces
                   11262:                  '30-50' (give me the 30th through the 50th matching
                   11263:                           records)
                   11264: 
                   11265: 
                   11266: =item *
                   11267: 
                   11268: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11269: replaces a &store() version of data with a replacement set of data
                   11270: for a particular resource in a namespace passed in the $storehash hash 
                   11271: reference
                   11272: 
                   11273: =item *
                   11274: 
1.243     albertel 11275: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11276: works very similar to store/cstore, but all data is stored in a
                   11277: temporary location and can be reset using tmpreset, $storehash should
                   11278: be a hash reference, returns nothing on success
1.191     harris41 11279: 
                   11280: =item *
                   11281: 
1.243     albertel 11282: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11283: similar to restore, but all data is stored in a temporary location and
                   11284: can be reset using tmpreset. Returns a hash of values on success,
                   11285: error string otherwise.
1.191     harris41 11286: 
                   11287: =item *
                   11288: 
1.243     albertel 11289: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11290: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11291: 
                   11292: =item *
                   11293: 
1.243     albertel 11294: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11295: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11296: 
                   11297: =item *
                   11298: 
1.243     albertel 11299: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11300: namesp ($udom and $uname are optional)
1.191     harris41 11301: 
                   11302: =item *
                   11303: 
1.702     albertel 11304: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11305: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11306: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11307: 
1.702     albertel 11308: $range should be either an integer '100' (give me the first 100
                   11309:                                            matching records)
                   11310:               or be  two integers sperated by a - with no spaces
                   11311:                  '30-50' (give me the 30th through the 50th matching
                   11312:                           records)
1.449     matthew  11313: =item *
                   11314: 
                   11315: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11316: $store can be a scalar, an array reference, or if the amount to be 
                   11317: incremented is > 1, a hash reference.
                   11318: 
                   11319: ($udom and $uname are optional)
1.191     harris41 11320: 
                   11321: =item *
                   11322: 
1.243     albertel 11323: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11324: ($udom and $uname are optional)
1.191     harris41 11325: 
                   11326: =item *
                   11327: 
1.243     albertel 11328: cput($namespace,$storehash,$udom,$uname) : critical put
                   11329: ($udom and $uname are optional)
1.191     harris41 11330: 
                   11331: =item *
                   11332: 
1.748     albertel 11333: newput($namespace,$storehash,$udom,$uname) :
                   11334: 
                   11335: Attempts to store the items in the $storehash, but only if they don't
                   11336: currently exist, if this succeeds you can be certain that you have 
                   11337: successfully created a new key value pair in the $namespace db.
                   11338: 
                   11339: 
                   11340: Args:
                   11341:  $namespace: name of database to store values to
                   11342:  $storehash: hashref to store to the db
                   11343:  $udom: (optional) domain of user containing the db
                   11344:  $uname: (optional) name of user caontaining the db
                   11345: 
                   11346: Returns:
                   11347:  'ok' -> succeeded in storing all keys of $storehash
                   11348:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11349:                         least <key> already existed in the db (other
                   11350:                         requested keys may also already exist)
1.967     bisitz   11351:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11352:  'con_lost' -> unable to contact request server
                   11353:  'refused' -> action was not allowed by remote machine
                   11354: 
                   11355: 
                   11356: =item *
                   11357: 
1.243     albertel 11358: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11359: reference filled in from namesp (encrypts the return communication)
                   11360: ($udom and $uname are optional)
1.191     harris41 11361: 
                   11362: =item *
                   11363: 
1.243     albertel 11364: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11365: critical subroutine
                   11366: 
1.806     raeburn  11367: =item *
                   11368: 
1.860     raeburn  11369: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11370: array reference filled in from namespace found in domain level on either
                   11371: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11372: 
                   11373: =item *
                   11374: 
1.860     raeburn  11375: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11376: domain level either on specified domain server ($uhome) or primary domain 
                   11377: server ($udom and $uhome are optional)
1.806     raeburn  11378: 
1.943     raeburn  11379: =item * 
                   11380: 
                   11381: get_domain_defaults($target_domain) : returns hash with defaults for
                   11382: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11383: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11384: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11385: Values are retrieved from cache (if current), or from domain's configuration.db
                   11386: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11387: or lonTabs/domain.tab. 
                   11388: 
                   11389: %domdefaults = &get_auth_defaults($target_domain);
                   11390: 
1.243     albertel 11391: =back
                   11392: 
                   11393: =head2 Network Status Functions
                   11394: 
                   11395: =over 4
1.191     harris41 11396: 
                   11397: =item *
                   11398: 
                   11399: dirlist($uri) : return directory list based on URI
                   11400: 
                   11401: =item *
                   11402: 
1.243     albertel 11403: spareserver() : find server with least workload from spare.tab
                   11404: 
1.986     foxr     11405: 
                   11406: =item *
                   11407: 
                   11408: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11409: if there is no corresponding loncapa host.
                   11410: 
1.243     albertel 11411: =back
                   11412: 
1.986     foxr     11413: 
1.243     albertel 11414: =head2 Apache Request
                   11415: 
                   11416: =over 4
1.191     harris41 11417: 
                   11418: =item *
                   11419: 
1.243     albertel 11420: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11421: localhost, posts hash
                   11422: 
                   11423: =back
                   11424: 
                   11425: =head2 Data to String to Data
                   11426: 
                   11427: =over 4
1.191     harris41 11428: 
                   11429: =item *
                   11430: 
1.243     albertel 11431: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11432: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11433: 
                   11434: =item *
                   11435: 
1.243     albertel 11436: hashref2str($hashref) : convert a hashref into a string complete with
                   11437: escaping and '=' and '&' separators, supports elements that are
                   11438: arrayrefs and hashrefs
1.191     harris41 11439: 
                   11440: =item *
                   11441: 
1.243     albertel 11442: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11443: with escaping and '&' separators, supports elements that are arrayrefs
                   11444: and hashrefs
1.191     harris41 11445: 
                   11446: =item *
                   11447: 
1.243     albertel 11448: str2hash($string) : convert string to hash using unescaping and
                   11449: splitting on '=' and '&', supports elements that are arrayrefs and
                   11450: hashrefs
1.191     harris41 11451: 
                   11452: =item *
                   11453: 
1.243     albertel 11454: str2array($string) : convert string to hash using unescaping and
                   11455: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11456: 
                   11457: =back
                   11458: 
                   11459: =head2 Logging Routines
                   11460: 
                   11461: These routines allow one to make log messages in the lonnet.log and
                   11462: lonnet.perm logfiles.
1.191     harris41 11463: 
1.1056.4.31  raeburn  11464: =over 4
                   11465: 
1.191     harris41 11466: =item *
                   11467: 
1.243     albertel 11468: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11469: 
                   11470: =item *
                   11471: 
1.243     albertel 11472: logthis() : append message to the normal lonnet.log file, it gets
                   11473: preiodically rolled over and deleted.
1.191     harris41 11474: 
                   11475: =item *
                   11476: 
1.243     albertel 11477: logperm() : append a permanent message to lonnet.perm.log, this log
                   11478: file never gets deleted by any automated portion of the system, only
                   11479: messages of critical importance should go in here.
                   11480: 
                   11481: =back
                   11482: 
                   11483: =head2 General File Helper Routines
                   11484: 
                   11485: =over 4
1.191     harris41 11486: 
                   11487: =item *
                   11488: 
1.481     raeburn  11489: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11490: (a) files in /uploaded
                   11491:   (i) If a local copy of the file exists - 
                   11492:       compares modification date of local copy with last-modified date for 
                   11493:       definitive version stored on home server for course. If local copy is 
                   11494:       stale, requests a new version from the home server and stores it. 
                   11495:       If the original has been removed from the home server, then local copy 
                   11496:       is unlinked.
                   11497:   (ii) If local copy does not exist -
                   11498:       requests the file from the home server and stores it. 
                   11499:   
                   11500:   If $caller is 'uploadrep':  
                   11501:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11502:     for request for files originally uploaded via DOCS. 
                   11503:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11504:   
                   11505:   Otherwise:
                   11506:      This indicates a call from the content generation phase of the request.
                   11507:      -  returns the entire contents of the file or -1.
                   11508:      
                   11509: (b) files in /res
                   11510:    - returns the entire contents of a file or -1; 
                   11511:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11512: 
1.712     albertel 11513: 
                   11514: =item *
                   11515: 
                   11516: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11517:                   reference
                   11518: 
                   11519: returns either a stat() list of data about the file or an empty list
                   11520: if the file doesn't exist or couldn't find out about it (connection
                   11521: problems or user unknown)
                   11522: 
1.191     harris41 11523: =item *
                   11524: 
1.243     albertel 11525: filelocation($dir,$file) : returns file system location of a file
                   11526: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11527: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11528: and a file of ../bob will become /a/bob)
1.191     harris41 11529: 
                   11530: =item *
                   11531: 
                   11532: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11533: filelocation except for hrefs
                   11534: 
                   11535: =item *
                   11536: 
                   11537: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11538: 
1.243     albertel 11539: =back
                   11540: 
1.608     albertel 11541: =head2 Usererfile file routines (/uploaded*)
                   11542: 
                   11543: =over 4
                   11544: 
                   11545: =item *
                   11546: 
                   11547: userfileupload(): main rotine for putting a file in a user or course's
                   11548:                   filespace, arguments are,
                   11549: 
1.620     albertel 11550:  formname - required - this is the name of the element in $env where the
1.608     albertel 11551:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11552:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11553:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11554:  context - if coursedoc, store the file in the course of the active role
                   11555:              of the current user;
                   11556:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11557:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11558:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11559:          if undefined, it will be placed in "unknown"
                   11560: 
                   11561:  (This routine calls clean_filename() to remove any dangerous
                   11562:  characters from the filename, and then calls finuserfileupload() to
                   11563:  complete the transaction)
                   11564: 
                   11565:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11566:  and /adm/notfound.html if unsuccessful
                   11567: 
                   11568: =item *
                   11569: 
                   11570: clean_filename(): routine for cleaing a filename up for storage in
                   11571:                  userfile space, argument is:
                   11572: 
                   11573:  filename - proposed filename
                   11574: 
                   11575: returns: the new clean filename
                   11576: 
                   11577: =item *
                   11578: 
1.1056.4.13  raeburn  11579: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11580: userspace, probably shouldn't be called directly
                   11581: 
                   11582:   docuname: username or courseid of destination for the file
                   11583:   docudom: domain of user/course of destination for the file
                   11584:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11585:   fname: filename (including subdirectories) for the file
                   11586:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11587:   allfiles: reference to hash used to store objects found by parser
                   11588:   codebase: reference to hash used for codebases of java objects found by parser
                   11589:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11590:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11591:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11592:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11593:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11594:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16  raeburn  11595:   mimetype: reference to scalar to accommodate mime type determined
                   11596:             from File::MMagic if $parser = parse.
1.608     albertel 11597: 
                   11598:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11599:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11600:  was 'overwrite').
                   11601: 
1.608     albertel 11602: 
                   11603: =item *
                   11604: 
                   11605: renameuserfile(): renames an existing userfile to a new name
                   11606: 
                   11607:   Args:
                   11608:    docuname: username or courseid of destination for the file
                   11609:    docudom: domain of user/course of destination for the file
                   11610:    old: current file name (including any subdirs under userfiles)
                   11611:    new: desired file name (including any subdirs under userfiles)
                   11612: 
                   11613: =item *
                   11614: 
                   11615: mkdiruserfile(): creates a directory is a userfiles dir
                   11616: 
                   11617:   Args:
                   11618:    docuname: username or courseid of destination for the file
                   11619:    docudom: domain of user/course of destination for the file
                   11620:    dir: dir to create (including any subdirs under userfiles)
                   11621: 
                   11622: =item *
                   11623: 
                   11624: removeuserfile(): removes a file that exists in userfiles
                   11625: 
                   11626:   Args:
                   11627:    docuname: username or courseid of destination for the file
                   11628:    docudom: domain of user/course of destination for the file
                   11629:    fname: filname to delete (including any subdirs under userfiles)
                   11630: 
                   11631: =item *
                   11632: 
                   11633: removeuploadedurl(): convience function for removeuserfile()
                   11634: 
                   11635:   Args:
                   11636:    url:  a full /uploaded/... url to delete
                   11637: 
1.747     albertel 11638: =item * 
                   11639: 
                   11640: get_portfile_permissions():
                   11641:   Args:
                   11642:     domain: domain of user or course contain the portfolio files
                   11643:     user: name of user or num of course contain the portfolio files
                   11644:   Returns:
                   11645:     hashref of a dump of the proper file_permissions.db
                   11646:    
                   11647: 
                   11648: =item * 
                   11649: 
                   11650: get_access_controls():
                   11651: 
                   11652: Args:
                   11653:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11654:   group: (optional) the group you want the files associated with
                   11655:   file: (optional) the file you want access info on
                   11656: 
                   11657: Returns:
1.749     raeburn  11658:     a hash (keys are file names) of hashes containing
                   11659:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11660:         values are XML containing access control settings (see below) 
1.747     albertel 11661: 
                   11662: Internal notes:
                   11663: 
1.749     raeburn  11664:  access controls are stored in file_permissions.db as key=value pairs.
                   11665:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11666:         where scope -> public,guest,course,group,domains or users.
                   11667:               end -> UNIX time for end of access (0 -> no end date)
                   11668:               start -> UNIX time for start of access
                   11669: 
                   11670:     value -> XML description of access control
                   11671:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11672:             <start></start>
                   11673:             <end></end>
                   11674: 
                   11675:             <password></password>  for scope type = guest
                   11676: 
                   11677:             <domain></domain>     for scope type = course or group
                   11678:             <number></number>
                   11679:             <roles id="">
                   11680:              <role></role>
                   11681:              <access></access>
                   11682:              <section></section>
                   11683:              <group></group>
                   11684:             </roles>
                   11685: 
                   11686:             <dom></dom>         for scope type = domains
                   11687: 
                   11688:             <users>             for scope type = users
                   11689:              <user>
                   11690:               <uname></uname>
                   11691:               <udom></udom>
                   11692:              </user>
                   11693:             </users>
                   11694:            </scope> 
                   11695:               
                   11696:  Access data is also aggregated for each file in an additional key=value pair:
                   11697:  key -> path to file/file_name\0accesscontrol 
                   11698:  value -> reference to hash
                   11699:           hash contains key = value pairs
                   11700:           where key = uniqueID:scope_end_start
                   11701:                 value = UNIX time record was last updated
                   11702: 
                   11703:           Used to improve speed of look-ups of access controls for each file.  
                   11704:  
                   11705:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11706: 
                   11707: modify_access_controls():
                   11708: 
                   11709: Modifies access controls for a portfolio file
                   11710: Args
                   11711: 1. file name
                   11712: 2. reference to hash of required changes,
                   11713: 3. domain
                   11714: 4. username
                   11715:   where domain,username are the domain of the portfolio owner 
                   11716:   (either a user or a course) 
                   11717: 
                   11718: Returns:
                   11719: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11720: 2. result of deletions ('ok' or 'error', with error message).
                   11721: 3. reference to hash of any new or updated access controls.
                   11722: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11723:    key = integer (inbound ID)
                   11724:    value = uniqueID  
1.747     albertel 11725: 
1.608     albertel 11726: =back
                   11727: 
1.243     albertel 11728: =head2 HTTP Helper Routines
                   11729: 
                   11730: =over 4
                   11731: 
1.191     harris41 11732: =item *
                   11733: 
                   11734: escape() : unpack non-word characters into CGI-compatible hex codes
                   11735: 
                   11736: =item *
                   11737: 
                   11738: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11739: 
1.243     albertel 11740: =back
                   11741: 
                   11742: =head1 PRIVATE SUBROUTINES
                   11743: 
                   11744: =head2 Underlying communication routines (Shouldn't call)
                   11745: 
                   11746: =over 4
                   11747: 
                   11748: =item *
                   11749: 
                   11750: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11751: 
                   11752: =item *
                   11753: 
                   11754: reply() : uses subreply to send a message to remote machine, logs all failures
                   11755: 
                   11756: =item *
                   11757: 
                   11758: critical() : passes a critical message to another server; if cannot
                   11759: get through then place message in connection buffer directory and
                   11760: returns con_delayed, if incapable of saving message, returns
                   11761: con_failed
                   11762: 
                   11763: =item *
                   11764: 
                   11765: reconlonc() : tries to reconnect lonc client processes.
                   11766: 
                   11767: =back
                   11768: 
                   11769: =head2 Resource Access Logging
                   11770: 
                   11771: =over 4
                   11772: 
                   11773: =item *
                   11774: 
                   11775: flushcourselogs() : flush (save) buffer logs and access logs
                   11776: 
                   11777: =item *
                   11778: 
                   11779: courselog($what) : save message for course in hash
                   11780: 
                   11781: =item *
                   11782: 
                   11783: courseacclog($what) : save message for course using &courselog().  Perform
                   11784: special processing for specific resource types (problems, exams, quizzes, etc).
                   11785: 
1.191     harris41 11786: =item *
                   11787: 
                   11788: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11789: as a PerlChildExitHandler
1.243     albertel 11790: 
                   11791: =back
                   11792: 
                   11793: =head2 Other
                   11794: 
                   11795: =over 4
                   11796: 
                   11797: =item *
                   11798: 
                   11799: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11800: 
                   11801: =back
                   11802: 
                   11803: =cut
1.877     foxr     11804: 

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