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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1056.4.33! raeburn     4: # $Id: lonnet.pm,v 1.1056.4.32 2011/10/07 01:19:01 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.31  raeburn   885:     my ($login_host,$hostname,$portal_path);
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;
                    896:                 }
                    897:             } else {
                    898:                 ($login_host, $lowest_load) =
                    899:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    900:                 if ($login_host eq $lonhost) {
                    901:                     $portal_path = '';
                    902:                 }
                    903:             }
                    904:         } else {
1.1056.4.3  raeburn   905:             ($login_host, $lowest_load) =
1.1056.4.31  raeburn   906:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1056.4.3  raeburn   907:         }
                    908:     }
                    909:     if ($login_host ne '') {
1.1056.4.31  raeburn   910:         $hostname = &hostname($login_host);
1.1056.4.3  raeburn   911:     }
                    912:     return ($login_host,$hostname);
                    913: }
                    914: 
1.202     matthew   915: # --------------------------------------------- Try to change a user's password
                    916: 
                    917: sub changepass {
1.799     raeburn   918:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   919:     $currentpass = &escape($currentpass);
                    920:     $newpass     = &escape($newpass);
1.1030    raeburn   921:     my $lonhost = $perlvar{'lonHostID'};
                    922:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   923: 		       $server);
                    924:     if (! $answer) {
                    925: 	&logthis("No reply on password change request to $server ".
                    926: 		 "by $uname in domain $udom.");
                    927:     } elsif ($answer =~ "^ok") {
                    928:         &logthis("$uname in $udom successfully changed their password ".
                    929: 		 "on $server.");
                    930:     } elsif ($answer =~ "^pwchange_failure") {
                    931: 	&logthis("$uname in $udom was unable to change their password ".
                    932: 		 "on $server.  The action was blocked by either lcpasswd ".
                    933: 		 "or pwchange");
                    934:     } elsif ($answer =~ "^non_authorized") {
                    935:         &logthis("$uname in $udom did not get their password correct when ".
                    936: 		 "attempting to change it on $server.");
                    937:     } elsif ($answer =~ "^auth_mode_error") {
                    938:         &logthis("$uname in $udom attempted to change their password despite ".
                    939: 		 "not being locally or internally authenticated on $server.");
                    940:     } elsif ($answer =~ "^unknown_user") {
                    941:         &logthis("$uname in $udom attempted to change their password ".
                    942: 		 "on $server but were unable to because $server is not ".
                    943: 		 "their home server.");
                    944:     } elsif ($answer =~ "^refused") {
                    945: 	&logthis("$server refused to change $uname in $udom password because ".
                    946: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   947:     } elsif ($answer =~ "invalid_client") {
                    948:         &logthis("$server refused to change $uname in $udom password because ".
                    949:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   950:     }
                    951:     return $answer;
1.1       albertel  952: }
                    953: 
1.169     harris41  954: # ----------------------- Try to determine user's current authentication scheme
                    955: 
                    956: sub queryauthenticate {
                    957:     my ($uname,$udom)=@_;
1.456     albertel  958:     my $uhome=&homeserver($uname,$udom);
                    959:     if (!$uhome) {
                    960: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    961: 	return 'no_host';
                    962:     }
                    963:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    964:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    965: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  966:     }
1.456     albertel  967:     return $answer;
1.169     harris41  968: }
                    969: 
1.1       albertel  970: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       971: 
1.1       albertel  972: sub authenticate {
1.1056.4.3  raeburn   973:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel  974:     $upass=&escape($upass);
                    975:     $uname= &LONCAPA::clean_username($uname);
1.836     www       976:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   977:     my $newhome;
1.836     www       978:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    979: # Maybe the machine was offline and only re-appeared again recently?
                    980:         &reconlonc();
                    981: # One more
1.952     raeburn   982: 	$uhome=&homeserver($uname,$udom,1);
                    983:         if (($uhome eq 'no_host') && $checkdefauth) {
                    984:             if (defined(&domain($udom,'primary'))) {
                    985:                 $newhome=&domain($udom,'primary');
                    986:             }
                    987:             if ($newhome ne '') {
                    988:                 $uhome = $newhome;
                    989:             }
                    990:         }
1.836     www       991: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    992: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   993: 	    return 'no_host';
                    994:         }
1.1       albertel  995:     }
1.1056.4.3  raeburn   996:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel  997:     if ($answer eq 'authorized') {
1.952     raeburn   998:         if ($newhome) {
                    999:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1000:             return 'no_account_on_host'; 
                   1001:         } else {
                   1002:             &logthis("User $uname at $udom authorized by $uhome");
                   1003:             return $uhome;
                   1004:         }
1.471     albertel 1005:     }
                   1006:     if ($answer eq 'non_authorized') {
                   1007: 	&logthis("User $uname at $udom rejected by $uhome");
                   1008: 	return 'no_host'; 
1.9       www      1009:     }
1.471     albertel 1010:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1011:     return 'no_host';
                   1012: }
                   1013: 
1.1056.4.3  raeburn  1014: sub can_host_session {
                   1015:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
                   1016:     my $canhost = 1;
                   1017:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
                   1018:     if (ref($remotesessions) eq 'HASH') {
                   1019:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
                   1020:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
                   1021:                 $canhost = 0;
                   1022:             } else {
                   1023:                 $canhost = 1;
                   1024:             }
                   1025:         }
                   1026:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
                   1027:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
                   1028:                 $canhost = 1;
                   1029:             } else {
                   1030:                 $canhost = 0;
                   1031:             }
                   1032:         }
                   1033:         if ($canhost) {
                   1034:             if ($remotesessions->{'version'} ne '') {
                   1035:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1036:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1037:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1038:                         my $major = $1;
                   1039:                         my $minor = $2;
                   1040:                         if (($major < $reqmajor ) ||
                   1041:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1042:                             $canhost = 0;
                   1043:                         }
                   1044:                     } else {
                   1045:                         $canhost = 0;
                   1046:                     }
                   1047:                 }
                   1048:             }
                   1049:         }
                   1050:     }
                   1051:     if ($canhost) {
                   1052:         if (ref($hostedsessions) eq 'HASH') {
1.1056.4.28  raeburn  1053:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1054:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1056.4.3  raeburn  1055:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1056:                 if (($uint_dom ne '') && 
                   1057:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1056.4.3  raeburn  1058:                     $canhost = 0;
                   1059:                 } else {
                   1060:                     $canhost = 1;
                   1061:                 }
                   1062:             }
                   1063:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1056.4.28  raeburn  1064:                 if (($uint_dom ne '') && 
                   1065:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1056.4.3  raeburn  1066:                     $canhost = 1;
                   1067:                 } else {
                   1068:                     $canhost = 0;
                   1069:                 }
                   1070:             }
                   1071:         }
                   1072:     }
                   1073:     return $canhost;
                   1074: }
                   1075: 
1.1056.4.8  raeburn  1076: sub spare_can_host {
                   1077:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1078:     my $canhost=1;
                   1079:     my @intdoms;
                   1080:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1081:     if (ref($internet_names) eq 'ARRAY') {
                   1082:         @intdoms = @{$internet_names};
                   1083:     }
                   1084:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1085:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1086:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1087:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1088:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1089:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1090:                                      $remotesessions,
                   1091:                                      $defdomdefaults{'hostedsessions'});
                   1092:     }
                   1093:     return $canhost;
                   1094: }
                   1095: 
1.1       albertel 1096: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1097: 
1.599     albertel 1098: my %homecache;
1.1       albertel 1099: sub homeserver {
1.230     stredwic 1100:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1101:     my $index="$uname:$udom";
1.426     albertel 1102: 
1.599     albertel 1103:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1104: 
                   1105:     my %servers = &get_servers($udom,'library');
                   1106:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1107:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1108: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1109: 
                   1110: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1111: 	if ($answer eq 'found') {
                   1112: 	    delete($badServerCache{$tryserver}); 
                   1113: 	    return $homecache{$index}=$tryserver;
                   1114: 	} elsif ($answer eq 'no_host') {
                   1115: 	    $badServerCache{$tryserver}=1;
                   1116: 	}
1.1       albertel 1117:     }    
                   1118:     return 'no_host';
1.70      www      1119: }
                   1120: 
                   1121: # ------------------------------------- Find the usernames behind a list of IDs
                   1122: 
                   1123: sub idget {
                   1124:     my ($udom,@ids)=@_;
                   1125:     my %returnhash=();
                   1126:     
1.841     albertel 1127:     my %servers = &get_servers($udom,'library');
                   1128:     foreach my $tryserver (keys(%servers)) {
                   1129: 	my $idlist=join('&',@ids);
                   1130: 	$idlist=~tr/A-Z/a-z/; 
                   1131: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1132: 	my @answer=();
                   1133: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1134: 	    @answer=split(/\&/,$reply);
                   1135: 	}                    ;
                   1136: 	my $i;
                   1137: 	for ($i=0;$i<=$#ids;$i++) {
                   1138: 	    if ($answer[$i]) {
                   1139: 		$returnhash{$ids[$i]}=$answer[$i];
                   1140: 	    } 
                   1141: 	}
                   1142:     } 
1.70      www      1143:     return %returnhash;
                   1144: }
                   1145: 
                   1146: # ------------------------------------- Find the IDs behind a list of usernames
                   1147: 
                   1148: sub idrget {
                   1149:     my ($udom,@unames)=@_;
                   1150:     my %returnhash=();
1.800     albertel 1151:     foreach my $uname (@unames) {
                   1152:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1153:     }
1.70      www      1154:     return %returnhash;
                   1155: }
                   1156: 
                   1157: # ------------------------------- Store away a list of names and associated IDs
                   1158: 
                   1159: sub idput {
                   1160:     my ($udom,%ids)=@_;
                   1161:     my %servers=();
1.800     albertel 1162:     foreach my $uname (keys(%ids)) {
                   1163: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1164:         my $uhom=&homeserver($uname,$udom);
1.70      www      1165:         if ($uhom ne 'no_host') {
1.800     albertel 1166:             my $id=&escape($ids{$uname});
1.70      www      1167:             $id=~tr/A-Z/a-z/;
1.800     albertel 1168:             my $esc_unam=&escape($uname);
1.70      www      1169: 	    if ($servers{$uhom}) {
1.800     albertel 1170: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1171:             } else {
1.800     albertel 1172:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1173:             }
                   1174:         }
1.191     harris41 1175:     }
1.800     albertel 1176:     foreach my $server (keys(%servers)) {
                   1177:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1178:     }
1.344     www      1179: }
                   1180: 
1.1023    raeburn  1181: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1182: sub dump_dom {
1.1023    raeburn  1183:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1184:     if (!$udom) {
                   1185:         $udom=$env{'user.domain'};
                   1186:     }
                   1187:     my %returnhash;
1.1023    raeburn  1188:     if ($udom) {
                   1189:         my $uname = &get_domainconfiguser($udom);
                   1190:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1191:     }
                   1192:     return %returnhash;
                   1193: }
                   1194: 
1.1023    raeburn  1195: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1196: 
                   1197: sub get_dom {
1.860     raeburn  1198:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1199:     my $items='';
                   1200:     foreach my $item (@$storearr) {
                   1201:         $items.=&escape($item).'&';
                   1202:     }
                   1203:     $items=~s/\&$//;
1.860     raeburn  1204:     if (!$udom) {
                   1205:         $udom=$env{'user.domain'};
                   1206:         if (defined(&domain($udom,'primary'))) {
                   1207:             $uhome=&domain($udom,'primary');
                   1208:         } else {
1.874     albertel 1209:             undef($uhome);
1.860     raeburn  1210:         }
                   1211:     } else {
                   1212:         if (!$uhome) {
                   1213:             if (defined(&domain($udom,'primary'))) {
                   1214:                 $uhome=&domain($udom,'primary');
                   1215:             }
                   1216:         }
                   1217:     }
                   1218:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1219:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1220:         my %returnhash;
1.875     albertel 1221:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1222:             return %returnhash;
                   1223:         }
1.806     raeburn  1224:         my @pairs=split(/\&/,$rep);
                   1225:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1226:             return @pairs;
                   1227:         }
                   1228:         my $i=0;
                   1229:         foreach my $item (@$storearr) {
                   1230:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1231:             $i++;
                   1232:         }
                   1233:         return %returnhash;
                   1234:     } else {
1.880     banghart 1235:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1236:     }
                   1237: }
                   1238: 
                   1239: # -------------------------------------------- put items in domain db files 
                   1240: 
                   1241: sub put_dom {
1.860     raeburn  1242:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1243:     if (!$udom) {
                   1244:         $udom=$env{'user.domain'};
                   1245:         if (defined(&domain($udom,'primary'))) {
                   1246:             $uhome=&domain($udom,'primary');
                   1247:         } else {
1.874     albertel 1248:             undef($uhome);
1.860     raeburn  1249:         }
                   1250:     } else {
                   1251:         if (!$uhome) {
                   1252:             if (defined(&domain($udom,'primary'))) {
                   1253:                 $uhome=&domain($udom,'primary');
                   1254:             }
                   1255:         }
                   1256:     } 
                   1257:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1258:         my $items='';
                   1259:         foreach my $item (keys(%$storehash)) {
                   1260:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1261:         }
                   1262:         $items=~s/\&$//;
                   1263:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1264:     } else {
1.860     raeburn  1265:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1266:     }
                   1267: }
                   1268: 
1.1023    raeburn  1269: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1270: sub newput_dom {
1.1023    raeburn  1271:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1272:     my $result;
                   1273:     if (!$udom) {
                   1274:         $udom=$env{'user.domain'};
                   1275:     }
1.1023    raeburn  1276:     if ($udom) {
                   1277:         my $uname = &get_domainconfiguser($udom);
                   1278:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1279:     }
                   1280:     return $result;
                   1281: }
                   1282: 
1.1023    raeburn  1283: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1284: sub del_dom {
1.1023    raeburn  1285:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1286:     if (ref($storearr) eq 'ARRAY') {
                   1287:         if (!$udom) {
                   1288:             $udom=$env{'user.domain'};
                   1289:         }
1.1023    raeburn  1290:         if ($udom) {
                   1291:             my $uname = &get_domainconfiguser($udom); 
                   1292:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1293:         }
                   1294:     }
                   1295: }
                   1296: 
1.1023    raeburn  1297: # ----------------------------------construct domainconfig user for a domain 
                   1298: sub get_domainconfiguser {
                   1299:     my ($udom) = @_;
                   1300:     return $udom.'-domainconfig';
                   1301: }
                   1302: 
1.837     raeburn  1303: sub retrieve_inst_usertypes {
                   1304:     my ($udom) = @_;
                   1305:     my (%returnhash,@order);
1.989     raeburn  1306:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1307:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1308:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1309:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1310:         @order = @{$domdefs{'inststatusorder'}};
                   1311:     } else {
                   1312:         if (defined(&domain($udom,'primary'))) {
                   1313:             my $uhome=&domain($udom,'primary');
                   1314:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1315:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1316:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1317:                 return (\%returnhash,\@order);
                   1318:             }
                   1319:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1320:             my @pairs=split(/\&/,$hashitems);
                   1321:             foreach my $item (@pairs) {
                   1322:                 my ($key,$value)=split(/=/,$item,2);
                   1323:                 $key = &unescape($key);
                   1324:                 next if ($key =~ /^error: 2 /);
                   1325:                 $returnhash{$key}=&thaw_unescape($value);
                   1326:             }
                   1327:             my @esc_order = split(/\&/,$orderitems);
                   1328:             foreach my $item (@esc_order) {
                   1329:                 push(@order,&unescape($item));
                   1330:             }
                   1331:         } else {
                   1332:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1333:         }
                   1334:     }
                   1335:     return (\%returnhash,\@order);
                   1336: }
                   1337: 
1.868     raeburn  1338: sub is_domainimage {
                   1339:     my ($url) = @_;
                   1340:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1341:         if (&domain($1) ne '') {
                   1342:             return '1';
                   1343:         }
                   1344:     }
                   1345:     return;
                   1346: }
                   1347: 
1.899     raeburn  1348: sub inst_directory_query {
                   1349:     my ($srch) = @_;
                   1350:     my $udom = $srch->{'srchdomain'};
                   1351:     my %results;
                   1352:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1353:     my $outcome;
1.899     raeburn  1354:     if ($homeserver ne '') {
1.904     albertel 1355: 	my $queryid=&reply("querysend:instdirsearch:".
                   1356: 			   &escape($srch->{'srchby'}).':'.
                   1357: 			   &escape($srch->{'srchterm'}).':'.
                   1358: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1359: 	my $host=&hostname($homeserver);
                   1360: 	if ($queryid !~/^\Q$host\E\_/) {
                   1361: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1362: 	    return;
                   1363: 	}
                   1364: 	my $response = &get_query_reply($queryid);
                   1365: 	my $maxtries = 5;
                   1366: 	my $tries = 1;
                   1367: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1368: 	    $response = &get_query_reply($queryid);
                   1369: 	    $tries ++;
                   1370: 	}
                   1371: 
                   1372:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1373:             if ($response eq 'unavailable') {
                   1374:                 $outcome = $response;
                   1375:             } else {
                   1376:                 $outcome = 'ok';
                   1377:                 my @matches = split(/\n/,$response);
                   1378:                 foreach my $match (@matches) {
                   1379:                     my ($key,$value) = split(/=/,$match);
                   1380:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1381:                 }
1.899     raeburn  1382:             }
                   1383:         }
                   1384:     }
1.909     raeburn  1385:     return ($outcome,%results);
1.899     raeburn  1386: }
                   1387: 
                   1388: sub usersearch {
                   1389:     my ($srch) = @_;
                   1390:     my $dom = $srch->{'srchdomain'};
                   1391:     my %results;
                   1392:     my %libserv = &all_library();
                   1393:     my $query = 'usersearch';
                   1394:     foreach my $tryserver (keys(%libserv)) {
                   1395:         if (&host_domain($tryserver) eq $dom) {
                   1396:             my $host=&hostname($tryserver);
                   1397:             my $queryid=
1.911     raeburn  1398:                 &reply("querysend:".&escape($query).':'.
                   1399:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1400:                        &escape($srch->{'srchtype'}).':'.
                   1401:                        &escape($srch->{'srchterm'}),$tryserver);
                   1402:             if ($queryid !~/^\Q$host\E\_/) {
                   1403:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1404:                 next;
1.899     raeburn  1405:             }
                   1406:             my $reply = &get_query_reply($queryid);
                   1407:             my $maxtries = 1;
                   1408:             my $tries = 1;
                   1409:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1410:                 $reply = &get_query_reply($queryid);
                   1411:                 $tries ++;
                   1412:             }
                   1413:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1414:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1415:             } else {
1.911     raeburn  1416:                 my @matches;
                   1417:                 if ($reply =~ /\n/) {
                   1418:                     @matches = split(/\n/,$reply);
                   1419:                 } else {
                   1420:                     @matches = split(/\&/,$reply);
                   1421:                 }
1.899     raeburn  1422:                 foreach my $match (@matches) {
                   1423:                     my ($uname,$udom,%userhash);
1.911     raeburn  1424:                     foreach my $entry (split(/:/,$match)) {
                   1425:                         my ($key,$value) =
                   1426:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1427:                         $userhash{$key} = $value;
                   1428:                         if ($key eq 'username') {
                   1429:                             $uname = $value;
                   1430:                         } elsif ($key eq 'domain') {
                   1431:                             $udom = $value;
1.911     raeburn  1432:                         }
1.899     raeburn  1433:                     }
                   1434:                     $results{$uname.':'.$udom} = \%userhash;
                   1435:                 }
                   1436:             }
                   1437:         }
                   1438:     }
                   1439:     return %results;
                   1440: }
                   1441: 
1.912     raeburn  1442: sub get_instuser {
                   1443:     my ($udom,$uname,$id) = @_;
                   1444:     my $homeserver = &domain($udom,'primary');
                   1445:     my ($outcome,%results);
                   1446:     if ($homeserver ne '') {
                   1447:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1448:                            &escape($id).':'.&escape($udom),$homeserver);
                   1449:         my $host=&hostname($homeserver);
                   1450:         if ($queryid !~/^\Q$host\E\_/) {
                   1451:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1452:             return;
                   1453:         }
                   1454:         my $response = &get_query_reply($queryid);
                   1455:         my $maxtries = 5;
                   1456:         my $tries = 1;
                   1457:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1458:             $response = &get_query_reply($queryid);
                   1459:             $tries ++;
                   1460:         }
                   1461:         if (!&error($response) && $response ne 'refused') {
                   1462:             if ($response eq 'unavailable') {
                   1463:                 $outcome = $response;
                   1464:             } else {
                   1465:                 $outcome = 'ok';
                   1466:                 my @matches = split(/\n/,$response);
                   1467:                 foreach my $match (@matches) {
                   1468:                     my ($key,$value) = split(/=/,$match);
                   1469:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1470:                 }
                   1471:             }
                   1472:         }
                   1473:     }
                   1474:     my %userinfo;
                   1475:     if (ref($results{$uname}) eq 'HASH') {
                   1476:         %userinfo = %{$results{$uname}};
                   1477:     } 
                   1478:     return ($outcome,%userinfo);
                   1479: }
                   1480: 
                   1481: sub inst_rulecheck {
1.923     raeburn  1482:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1483:     my %returnhash;
                   1484:     if ($udom ne '') {
                   1485:         if (ref($rules) eq 'ARRAY') {
                   1486:             @{$rules} = map {&escape($_);} (@{$rules});
                   1487:             my $rulestr = join(':',@{$rules});
                   1488:             my $homeserver=&domain($udom,'primary');
                   1489:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1490:                 my $response;
                   1491:                 if ($item eq 'username') {                
                   1492:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1493:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1494:                                               $homeserver));
1.923     raeburn  1495:                 } elsif ($item eq 'id') {
                   1496:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1497:                                               ':'.&escape($id).':'.$rulestr,
                   1498:                                               $homeserver));
1.945     raeburn  1499:                 } elsif ($item eq 'selfcreate') {
                   1500:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1501:                                                &escape($udom).':'.&escape($uname).
                   1502:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1503:                 }
1.912     raeburn  1504:                 if ($response ne 'refused') {
                   1505:                     my @pairs=split(/\&/,$response);
                   1506:                     foreach my $item (@pairs) {
                   1507:                         my ($key,$value)=split(/=/,$item,2);
                   1508:                         $key = &unescape($key);
                   1509:                         next if ($key =~ /^error: 2 /);
                   1510:                         $returnhash{$key}=&thaw_unescape($value);
                   1511:                     }
                   1512:                 }
                   1513:             }
                   1514:         }
                   1515:     }
                   1516:     return %returnhash;
                   1517: }
                   1518: 
                   1519: sub inst_userrules {
1.923     raeburn  1520:     my ($udom,$check) = @_;
1.912     raeburn  1521:     my (%ruleshash,@ruleorder);
                   1522:     if ($udom ne '') {
                   1523:         my $homeserver=&domain($udom,'primary');
                   1524:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1525:             my $response;
                   1526:             if ($check eq 'id') {
                   1527:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1528:                                  $homeserver);
1.943     raeburn  1529:             } elsif ($check eq 'email') {
                   1530:                 $response=&reply('instemailrules:'.&escape($udom),
                   1531:                                  $homeserver);
1.923     raeburn  1532:             } else {
                   1533:                 $response=&reply('instuserrules:'.&escape($udom),
                   1534:                                  $homeserver);
                   1535:             }
1.912     raeburn  1536:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1537:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1538:                 ($response ne 'no_such_host')) {
                   1539:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1540:                 my @pairs=split(/\&/,$hashitems);
                   1541:                 foreach my $item (@pairs) {
                   1542:                     my ($key,$value)=split(/=/,$item,2);
                   1543:                     $key = &unescape($key);
                   1544:                     next if ($key =~ /^error: 2 /);
                   1545:                     $ruleshash{$key}=&thaw_unescape($value);
                   1546:                 }
                   1547:                 my @esc_order = split(/\&/,$orderitems);
                   1548:                 foreach my $item (@esc_order) {
                   1549:                     push(@ruleorder,&unescape($item));
                   1550:                 }
                   1551:             }
                   1552:         }
                   1553:     }
                   1554:     return (\%ruleshash,\@ruleorder);
                   1555: }
                   1556: 
1.976     raeburn  1557: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1558: 
                   1559: sub get_domain_defaults {
                   1560:     my ($domain) = @_;
                   1561:     my $cachetime = 60*60*24;
                   1562:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1563:     if (defined($cached)) {
                   1564:         if (ref($result) eq 'HASH') {
                   1565:             return %{$result};
                   1566:         }
                   1567:     }
                   1568:     my %domdefaults;
                   1569:     my %domconfig =
1.989     raeburn  1570:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1571:                                   'requestcourses','inststatus',
1.1056.4.3  raeburn  1572:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1573:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1574:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1575:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1576:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1577:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1578:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1579:     } else {
                   1580:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1581:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1582:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1583:     }
1.976     raeburn  1584:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1585:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1586:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1587:         } else {
                   1588:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1589:         } 
                   1590:         my @usertools = ('aboutme','blog','portfolio');
                   1591:         foreach my $item (@usertools) {
                   1592:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1593:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1594:             }
                   1595:         }
                   1596:     }
1.985     raeburn  1597:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1598:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1599:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1600:         }
                   1601:     }
1.989     raeburn  1602:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1603:         foreach my $item ('inststatustypes','inststatusorder') {
                   1604:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1605:         }
                   1606:     }
1.1047    raeburn  1607:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1608:         foreach my $item ('canuse_pdfforms') {
                   1609:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1610:         }
                   1611:     }
1.1056.4.3  raeburn  1612:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1613:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1614:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1615:         }
                   1616:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1617:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1618:         }
                   1619:     }
1.943     raeburn  1620:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1621:                                   $cachetime);
                   1622:     return %domdefaults;
                   1623: }
                   1624: 
1.344     www      1625: # --------------------------------------------------- Assign a key to a student
                   1626: 
                   1627: sub assign_access_key {
1.364     www      1628: #
                   1629: # a valid key looks like uname:udom#comments
                   1630: # comments are being appended
                   1631: #
1.498     www      1632:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1633:     $kdom=
1.620     albertel 1634:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1635:     $knum=
1.620     albertel 1636:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1637:     $cdom=
1.620     albertel 1638:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1639:     $cnum=
1.620     albertel 1640:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1641:     $udom=$env{'user.name'} unless (defined($udom));
                   1642:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1643:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1644:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1645:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1646:                                                   # assigned to this person
                   1647:                                                   # - this should not happen,
1.345     www      1648:                                                   # unless something went wrong
                   1649:                                                   # the first time around
                   1650: # ready to assign
1.364     www      1651:         $logentry=$1.'; '.$logentry;
1.496     www      1652:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1653:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1654: # key now belongs to user
1.346     www      1655: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1656:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1657:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1658:                 return 'ok';
                   1659:             } else {
                   1660:                 return 
                   1661:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1662: 	    }
                   1663:         } else {
                   1664:             return 'error: Could not assign key, try again later.';
                   1665:         }
1.364     www      1666:     } elsif (!$existing{$ckey}) {
1.345     www      1667: # the key does not exist
                   1668: 	return 'error: The key does not exist';
                   1669:     } else {
                   1670: # the key is somebody else's
                   1671: 	return 'error: The key is already in use';
                   1672:     }
1.344     www      1673: }
                   1674: 
1.364     www      1675: # ------------------------------------------ put an additional comment on a key
                   1676: 
                   1677: sub comment_access_key {
                   1678: #
                   1679: # a valid key looks like uname:udom#comments
                   1680: # comments are being appended
                   1681: #
                   1682:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1683:     $cdom=
1.620     albertel 1684:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1685:     $cnum=
1.620     albertel 1686:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1687:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1688:     if ($existing{$ckey}) {
                   1689:         $existing{$ckey}.='; '.$logentry;
                   1690: # ready to assign
1.367     www      1691:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1692:                                                  $cdom,$cnum) eq 'ok') {
                   1693: 	    return 'ok';
                   1694:         } else {
                   1695: 	    return 'error: Count not store comment.';
                   1696:         }
                   1697:     } else {
                   1698: # the key does not exist
                   1699: 	return 'error: The key does not exist';
                   1700:     }
                   1701: }
                   1702: 
1.344     www      1703: # ------------------------------------------------------ Generate a set of keys
                   1704: 
                   1705: sub generate_access_keys {
1.364     www      1706:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1707:     $cdom=
1.620     albertel 1708:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1709:     $cnum=
1.620     albertel 1710:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1711:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1712:     unless (($cdom) && ($cnum)) { return 0; }
                   1713:     if ($number>10000) { return 0; }
                   1714:     sleep(2); # make sure don't get same seed twice
                   1715:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1716:     my $total=0;
                   1717:     for (my $i=1;$i<=$number;$i++) {
                   1718:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1719:                   sprintf("%lx",int(100000*rand)).'-'.
                   1720:                   sprintf("%lx",int(100000*rand));
                   1721:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1722:        $newkey=~s/0/h/g; # and also 0 and O
                   1723:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1724:        if ($existing{$newkey}) {
                   1725:            $i--;
                   1726:        } else {
1.364     www      1727: 	  if (&put('accesskeys',
                   1728:               { $newkey => '# generated '.localtime().
1.620     albertel 1729:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1730:                            '; '.$logentry },
                   1731: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1732:               $total++;
                   1733: 	  }
                   1734:        }
                   1735:     }
1.620     albertel 1736:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1737:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1738:     return $total;
                   1739: }
                   1740: 
                   1741: # ------------------------------------------------------- Validate an accesskey
                   1742: 
                   1743: sub validate_access_key {
                   1744:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1745:     $cdom=
1.620     albertel 1746:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1747:     $cnum=
1.620     albertel 1748:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1749:     $udom=$env{'user.domain'} unless (defined($udom));
                   1750:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1751:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1752:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1753: }
                   1754: 
                   1755: # ------------------------------------- Find the section of student in a course
1.652     albertel 1756: sub devalidate_getsection_cache {
                   1757:     my ($udom,$unam,$courseid)=@_;
                   1758:     my $hashid="$udom:$unam:$courseid";
                   1759:     &devalidate_cache_new('getsection',$hashid);
                   1760: }
1.298     matthew  1761: 
1.815     albertel 1762: sub courseid_to_courseurl {
                   1763:     my ($courseid) = @_;
                   1764:     #already url style courseid
                   1765:     return $courseid if ($courseid =~ m{^/});
                   1766: 
                   1767:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1768: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1769: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1770: 	return "/$cdom/$cnum";
                   1771:     }
                   1772: 
                   1773:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1774:     if (exists($courseinfo{'num'})) {
                   1775: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1776:     }
                   1777: 
                   1778:     return undef;
                   1779: }
                   1780: 
1.298     matthew  1781: sub getsection {
                   1782:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1783:     my $cachetime=1800;
1.551     albertel 1784: 
                   1785:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1786:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1787:     if (defined($cached)) { return $result; }
                   1788: 
1.298     matthew  1789:     my %Pending; 
                   1790:     my %Expired;
                   1791:     #
                   1792:     # Each role can either have not started yet (pending), be active, 
                   1793:     #    or have expired.
                   1794:     #
                   1795:     # If there is an active role, we are done.
                   1796:     #
                   1797:     # If there is more than one role which has not started yet, 
                   1798:     #     choose the one which will start sooner
                   1799:     # If there is one role which has not started yet, return it.
                   1800:     #
                   1801:     # If there is more than one expired role, choose the one which ended last.
                   1802:     # If there is a role which has expired, return it.
                   1803:     #
1.815     albertel 1804:     $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  1805:     my $extra = &freeze_escape({'skipcheck' => 1});
                   1806:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  1807:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1808:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1809:         my $section=$1;
                   1810:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1811:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1812:         my $now=time;
1.548     albertel 1813:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1814:             $Expired{$end}=$section;
                   1815:             next;
                   1816:         }
1.548     albertel 1817:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1818:             $Pending{$start}=$section;
                   1819:             next;
                   1820:         }
1.599     albertel 1821:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1822:     }
                   1823:     #
                   1824:     # Presumedly there will be few matching roles from the above
                   1825:     # loop and the sorting time will be negligible.
                   1826:     if (scalar(keys(%Pending))) {
                   1827:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1828:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1829:     } 
                   1830:     if (scalar(keys(%Expired))) {
                   1831:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1832:         my $time = pop(@sorted);
1.599     albertel 1833:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1834:     }
1.599     albertel 1835:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1836: }
1.70      www      1837: 
1.599     albertel 1838: sub save_cache {
                   1839:     &purge_remembered();
1.722     albertel 1840:     #&Apache::loncommon::validate_page();
1.620     albertel 1841:     undef(%env);
1.780     albertel 1842:     undef($env_loaded);
1.599     albertel 1843: }
1.452     albertel 1844: 
1.599     albertel 1845: my $to_remember=-1;
                   1846: my %remembered;
                   1847: my %accessed;
                   1848: my $kicks=0;
                   1849: my $hits=0;
1.849     albertel 1850: sub make_key {
                   1851:     my ($name,$id) = @_;
1.872     albertel 1852:     if (length($id) > 65 
                   1853: 	&& length(&escape($id)) > 200) {
                   1854: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1855:     }
1.849     albertel 1856:     return &escape($name.':'.$id);
                   1857: }
                   1858: 
1.599     albertel 1859: sub devalidate_cache_new {
                   1860:     my ($name,$id,$debug) = @_;
                   1861:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1862:     $id=&make_key($name,$id);
1.599     albertel 1863:     $memcache->delete($id);
                   1864:     delete($remembered{$id});
                   1865:     delete($accessed{$id});
                   1866: }
                   1867: 
                   1868: sub is_cached_new {
                   1869:     my ($name,$id,$debug) = @_;
1.849     albertel 1870:     $id=&make_key($name,$id);
1.599     albertel 1871:     if (exists($remembered{$id})) {
                   1872: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1873: 	$accessed{$id}=[&gettimeofday()];
                   1874: 	$hits++;
                   1875: 	return ($remembered{$id},1);
                   1876:     }
                   1877:     my $value = $memcache->get($id);
                   1878:     if (!(defined($value))) {
                   1879: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1880: 	return (undef,undef);
1.416     albertel 1881:     }
1.599     albertel 1882:     if ($value eq '__undef__') {
                   1883: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1884: 	$value=undef;
                   1885:     }
                   1886:     &make_room($id,$value,$debug);
                   1887:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1888:     return ($value,1);
                   1889: }
                   1890: 
                   1891: sub do_cache_new {
                   1892:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1893:     $id=&make_key($name,$id);
1.599     albertel 1894:     my $setvalue=$value;
                   1895:     if (!defined($setvalue)) {
                   1896: 	$setvalue='__undef__';
                   1897:     }
1.623     albertel 1898:     if (!defined($time) ) {
                   1899: 	$time=600;
                   1900:     }
1.599     albertel 1901:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1902:     my $result = $memcache->set($id,$setvalue,$time);
                   1903:     if (! $result) {
1.872     albertel 1904: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1905: 	$memcache->disconnect_all();
1.872     albertel 1906:     }
1.600     albertel 1907:     # need to make a copy of $value
1.919     albertel 1908:     &make_room($id,$value,$debug);
1.599     albertel 1909:     return $value;
                   1910: }
                   1911: 
                   1912: sub make_room {
                   1913:     my ($id,$value,$debug)=@_;
1.919     albertel 1914: 
                   1915:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1916:                                     : $value;
1.599     albertel 1917:     if ($to_remember<0) { return; }
                   1918:     $accessed{$id}=[&gettimeofday()];
                   1919:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1920:     my $to_kick;
                   1921:     my $max_time=0;
                   1922:     foreach my $other (keys(%accessed)) {
                   1923: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1924: 	    $to_kick=$other;
                   1925: 	    $max_time=&tv_interval($accessed{$other});
                   1926: 	}
                   1927:     }
                   1928:     delete($remembered{$to_kick});
                   1929:     delete($accessed{$to_kick});
                   1930:     $kicks++;
                   1931:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1932:     return;
                   1933: }
                   1934: 
1.599     albertel 1935: sub purge_remembered {
1.604     albertel 1936:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1937:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1938:     undef(%remembered);
                   1939:     undef(%accessed);
1.428     albertel 1940: }
1.70      www      1941: # ------------------------------------- Read an entry from a user's environment
                   1942: 
                   1943: sub userenvironment {
                   1944:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1945:     my $items;
                   1946:     foreach my $item (@what) {
                   1947:         $items.=&escape($item).'&';
                   1948:     }
                   1949:     $items=~s/\&$//;
1.70      www      1950:     my %returnhash=();
1.1009    raeburn  1951:     my $uhome = &homeserver($unam,$udom);
                   1952:     unless ($uhome eq 'no_host') {
                   1953:         my @answer=split(/\&/, 
                   1954:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1955:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1956:             return %returnhash;
                   1957:         }
1.1009    raeburn  1958:         my $i;
                   1959:         for ($i=0;$i<=$#what;$i++) {
                   1960: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1961:         }
1.70      www      1962:     }
                   1963:     return %returnhash;
1.1       albertel 1964: }
                   1965: 
1.617     albertel 1966: # ---------------------------------------------------------- Get a studentphoto
                   1967: sub studentphoto {
                   1968:     my ($udom,$unam,$ext) = @_;
                   1969:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1970:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1971:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1972:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1973:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1974:             } else {
                   1975:                 my ($result,$perm_reqd)=
1.707     albertel 1976: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1977:                 if ($result eq 'ok') {
                   1978:                     if (!($perm_reqd eq 'yes')) {
                   1979:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1980:                     }
                   1981:                 }
                   1982:             }
                   1983:         }
                   1984:     } else {
                   1985:         my ($result,$perm_reqd) = 
1.707     albertel 1986: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1987:         if ($result eq 'ok') {
                   1988:             if (!($perm_reqd eq 'yes')) {
                   1989:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1990:             }
                   1991:         }
                   1992:     }
                   1993:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1994: }
                   1995: 
                   1996: sub retrievestudentphoto {
                   1997:     my ($udom,$unam,$ext,$type) = @_;
                   1998:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1999:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2000:     if ($ret eq 'ok') {
                   2001:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2002:         if ($type eq 'thumbnail') {
                   2003:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2004:         }
                   2005:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2006:         return $tokenurl;
                   2007:     } else {
                   2008:         if ($type eq 'thumbnail') {
                   2009:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2010:         } else { 
                   2011:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2012:         }
1.617     albertel 2013:     }
                   2014: }
                   2015: 
1.263     www      2016: # -------------------------------------------------------------------- New chat
                   2017: 
                   2018: sub chatsend {
1.724     raeburn  2019:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2020:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2021:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2022:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2023:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2024: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2025: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2026: }
                   2027: 
                   2028: # ------------------------------------------ Find current version of a resource
                   2029: 
                   2030: sub getversion {
                   2031:     my $fname=&clutter(shift);
                   2032:     unless ($fname=~/^\/res\//) { return -1; }
                   2033:     return &currentversion(&filelocation('',$fname));
                   2034: }
                   2035: 
                   2036: sub currentversion {
                   2037:     my $fname=shift;
1.599     albertel 2038:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      2039:     if (defined($cached)) { return $result; }
1.292     www      2040:     my $author=$fname;
                   2041:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2042:     my ($udom,$uname)=split(/\//,$author);
                   2043:     my $home=homeserver($uname,$udom);
                   2044:     if ($home eq 'no_host') { 
                   2045:         return -1; 
                   2046:     }
                   2047:     my $answer=reply("currentversion:$fname",$home);
                   2048:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2049: 	return -1;
                   2050:     }
1.599     albertel 2051:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      2052: }
                   2053: 
1.1       albertel 2054: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2055: 
1.1       albertel 2056: sub subscribe {
                   2057:     my $fname=shift;
1.761     raeburn  2058:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2059:     $fname=~s/[\n\r]//g;
1.1       albertel 2060:     my $author=$fname;
                   2061:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2062:     my ($udom,$uname)=split(/\//,$author);
                   2063:     my $home=homeserver($uname,$udom);
1.335     albertel 2064:     if ($home eq 'no_host') {
                   2065:         return 'not_found';
1.1       albertel 2066:     }
                   2067:     my $answer=reply("sub:$fname",$home);
1.64      www      2068:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2069: 	$answer.=' by '.$home;
                   2070:     }
1.1       albertel 2071:     return $answer;
                   2072: }
                   2073:     
1.8       www      2074: # -------------------------------------------------------------- Replicate file
                   2075: 
                   2076: sub repcopy {
                   2077:     my $filename=shift;
1.23      www      2078:     $filename=~s/\/+/\//g;
1.607     raeburn  2079:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2080:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2081:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2082: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2083: 	return &repcopy_userfile($filename);
                   2084:     }
1.532     albertel 2085:     $filename=~s/[\n\r]//g;
1.8       www      2086:     my $transname="$filename.in.transfer";
1.828     www      2087: # FIXME: this should flock
1.607     raeburn  2088:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2089:     my $remoteurl=subscribe($filename);
1.64      www      2090:     if ($remoteurl =~ /^con_lost by/) {
                   2091: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2092:            return 'unavailable';
1.8       www      2093:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2094: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2095: 	   return 'not_found';
1.64      www      2096:     } elsif ($remoteurl =~ /^rejected by/) {
                   2097: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2098:            return 'forbidden';
1.20      www      2099:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2100:            return 'ok';
1.8       www      2101:     } else {
1.290     www      2102:         my $author=$filename;
                   2103:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2104:         my ($udom,$uname)=split(/\//,$author);
                   2105:         my $home=homeserver($uname,$udom);
                   2106:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2107:            my @parts=split(/\//,$filename);
                   2108:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2109:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2110:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2111: 	       return 'bad_request';
1.8       www      2112:            }
                   2113:            my $count;
                   2114:            for ($count=5;$count<$#parts;$count++) {
                   2115:                $path.="/$parts[$count]";
                   2116:                if ((-e $path)!=1) {
                   2117: 		   mkdir($path,0777);
                   2118:                }
                   2119:            }
                   2120:            my $ua=new LWP::UserAgent;
                   2121:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2122:            my $response=$ua->request($request,$transname);
                   2123:            if ($response->is_error()) {
                   2124: 	       unlink($transname);
                   2125:                my $message=$response->status_line;
1.672     albertel 2126:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2127:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2128:                return 'unavailable';
1.8       www      2129:            } else {
1.16      www      2130: 	       if ($remoteurl!~/\.meta$/) {
                   2131:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2132:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2133:                   if ($mresponse->is_error()) {
                   2134: 		      unlink($filename.'.meta');
                   2135:                       &logthis(
1.672     albertel 2136:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2137:                   }
                   2138: 	       }
1.8       www      2139:                rename($transname,$filename);
1.607     raeburn  2140:                return 'ok';
1.8       www      2141:            }
1.290     www      2142:        }
1.8       www      2143:     }
1.330     www      2144: }
                   2145: 
                   2146: # ------------------------------------------------ Get server side include body
                   2147: sub ssi_body {
1.381     albertel 2148:     my ($filelink,%form)=@_;
1.606     matthew  2149:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2150:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2151:     }
1.953     www      2152:     my $output='';
                   2153:     my $response;
1.980     raeburn  2154:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2155:        ($output,$response)=&externalssi($filelink);
1.953     www      2156:     } else {
1.1004    droeschl 2157:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2158:        $filelink .= 'inhibitmenu=yes';
1.953     www      2159:        ($output,$response)=&ssi($filelink,%form);
                   2160:     }
1.778     albertel 2161:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2162:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2163:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2164:     if (wantarray) {
                   2165:         return ($output, $response);
                   2166:     } else {
                   2167:         return $output;
                   2168:     }
1.8       www      2169: }
                   2170: 
1.15      www      2171: # --------------------------------------------------------- Server Side Include
                   2172: 
1.782     albertel 2173: sub absolute_url {
                   2174:     my ($host_name) = @_;
                   2175:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2176:     if ($host_name eq '') {
                   2177: 	$host_name = $ENV{'SERVER_NAME'};
                   2178:     }
                   2179:     return $protocol.$host_name;
                   2180: }
                   2181: 
1.942     foxr     2182: #
                   2183: #   Server side include.
                   2184: # Parameters:
                   2185: #  fn     Possibly encrypted resource name/id.
                   2186: #  form   Hash that describes how the rendering should be done
                   2187: #         and other things.
1.944     foxr     2188: # Returns:
1.950     raeburn  2189: #   Scalar context: The content of the response.
                   2190: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2191: #     
1.15      www      2192: sub ssi {
                   2193: 
1.944     foxr     2194:     my ($fn,%form)=@_;
1.15      www      2195:     my $ua=new LWP::UserAgent;
1.23      www      2196:     my $request;
1.711     albertel 2197: 
                   2198:     $form{'no_update_last_known'}=1;
1.895     albertel 2199:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2200:     if (%form) {
1.782     albertel 2201:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2202:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2203:     } else {
1.782     albertel 2204:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2205:     }
                   2206: 
1.15      www      2207:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2208:     my $response=$ua->request($request);
                   2209: 
1.944     foxr     2210:     if (wantarray) {
                   2211: 	return ($response->content, $response);
                   2212:     } else {
                   2213: 	return $response->content;
1.942     foxr     2214:     }
1.324     www      2215: }
                   2216: 
                   2217: sub externalssi {
                   2218:     my ($url)=@_;
                   2219:     my $ua=new LWP::UserAgent;
                   2220:     my $request=new HTTP::Request('GET',$url);
                   2221:     my $response=$ua->request($request);
1.954     raeburn  2222:     if (wantarray) {
                   2223:         return ($response->content, $response);
                   2224:     } else {
                   2225:         return $response->content;
                   2226:     }
1.15      www      2227: }
1.254     www      2228: 
1.492     albertel 2229: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2230: 
                   2231: sub allowuploaded {
                   2232:     my ($srcurl,$url)=@_;
                   2233:     $url=&clutter(&declutter($url));
                   2234:     my $dir=$url;
                   2235:     $dir=~s/\/[^\/]+$//;
                   2236:     my %httpref=();
                   2237:     my $httpurl=&hreflocation('',$url);
                   2238:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2239:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2240: }
1.477     raeburn  2241: 
1.478     albertel 2242: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2243: # input: action, courseID, current domain, intended
1.637     raeburn  2244: #        path to file, source of file, instruction to parse file for objects,
                   2245: #        ref to hash for embedded objects,
                   2246: #        ref to hash for codebase of java objects.
1.1056.4.16  raeburn  2247: #        reference to scalar to accommodate mime type determined
                   2248: #          from File::MMagic if $parser = parse.
1.637     raeburn  2249: #
1.485     raeburn  2250: # output: url to file (if action was uploaddoc), 
                   2251: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2252: #
1.478     albertel 2253: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2254: # course.
1.477     raeburn  2255: #
1.478     albertel 2256: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2257: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2258: #          course's home server.
1.477     raeburn  2259: #
1.478     albertel 2260: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2261: #          be copied from $source (current location) to 
                   2262: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2263: #         and will then be copied to
                   2264: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2265: #         course's home server.
1.485     raeburn  2266: #
1.481     raeburn  2267: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2268: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2269: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2270: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2271: #         in course's home server.
1.637     raeburn  2272: #
1.477     raeburn  2273: 
                   2274: sub process_coursefile {
1.1056.4.16  raeburn  2275:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2276:         $mimetype)=@_;
1.477     raeburn  2277:     my $fetchresult;
1.638     albertel 2278:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2279:     if ($action eq 'propagate') {
1.638     albertel 2280:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2281: 			     $home);
1.481     raeburn  2282:     } else {
1.477     raeburn  2283:         my $fpath = '';
                   2284:         my $fname = $file;
1.478     albertel 2285:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2286:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2287:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2288:         if ($action eq 'copy') {
                   2289:             if ($source eq '') {
                   2290:                 $fetchresult = 'no source file';
                   2291:                 return $fetchresult;
                   2292:             } else {
                   2293:                 my $destination = $filepath.'/'.$fname;
                   2294:                 rename($source,$destination);
                   2295:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2296:                                  $home);
1.481     raeburn  2297:             }
                   2298:         } elsif ($action eq 'uploaddoc') {
                   2299:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2300:             print $fh $env{'form.'.$source};
1.481     raeburn  2301:             close($fh);
1.637     raeburn  2302:             if ($parser eq 'parse') {
1.1024    raeburn  2303:                 my $mm = new File::MMagic;
1.1056.4.16  raeburn  2304:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2305:                 if ($type eq 'text/html') {
1.1024    raeburn  2306:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2307:                     unless ($parse_result eq 'ok') {
                   2308:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2309:                     }
1.637     raeburn  2310:                 }
1.1056.4.16  raeburn  2311:                 if (ref($mimetype)) {
                   2312:                     $$mimetype = $type;
                   2313:                 }
1.637     raeburn  2314:             }
1.477     raeburn  2315:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2316:                                  $home);
1.481     raeburn  2317:             if ($fetchresult eq 'ok') {
                   2318:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2319:             } else {
                   2320:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2321:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2322:                 return '/adm/notfound.html';
                   2323:             }
1.477     raeburn  2324:         }
                   2325:     }
1.485     raeburn  2326:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2327:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2328:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2329:     }
                   2330:     return $fetchresult;
                   2331: }
                   2332: 
1.637     raeburn  2333: sub build_filepath {
                   2334:     my ($fpath) = @_;
                   2335:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2336:     unless ($fpath eq '') {
                   2337:         my @parts=split('/',$fpath);
                   2338:         foreach my $part (@parts) {
                   2339:             $filepath.= '/'.$part;
                   2340:             if ((-e $filepath)!=1) {
                   2341:                 mkdir($filepath,0777);
                   2342:             }
                   2343:         }
                   2344:     }
                   2345:     return $filepath;
                   2346: }
                   2347: 
                   2348: sub store_edited_file {
1.638     albertel 2349:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2350:     my $file = $primary_url;
                   2351:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2352:     my $fpath = '';
                   2353:     my $fname = $file;
                   2354:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2355:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2356:     my $filepath = &build_filepath($fpath);
                   2357:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2358:     print $fh $content;
                   2359:     close($fh);
1.638     albertel 2360:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2361:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2362: 			  $home);
1.637     raeburn  2363:     if ($$fetchresult eq 'ok') {
                   2364:         return '/uploaded/'.$fpath.'/'.$fname;
                   2365:     } else {
1.638     albertel 2366:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2367: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2368:         return '/adm/notfound.html';
                   2369:     }
                   2370: }
                   2371: 
1.531     albertel 2372: sub clean_filename {
1.831     albertel 2373:     my ($fname,$args)=@_;
1.315     www      2374: # Replace Windows backslashes by forward slashes
1.257     www      2375:     $fname=~s/\\/\//g;
1.831     albertel 2376:     if (!$args->{'keep_path'}) {
                   2377:         # Get rid of everything but the actual filename
                   2378: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2379:     }
1.315     www      2380: # Replace spaces by underscores
                   2381:     $fname=~s/\s+/\_/g;
                   2382: # Replace all other weird characters by nothing
1.831     albertel 2383:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2384: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2385: # numbers
                   2386:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2387:     return $fname;
                   2388: }
1.1051    raeburn  2389: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2390: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2391: # image with the same aspect ratio as the original, but with dimensions which do 
                   2392: # not exceed $resizewidth and $resizeheight.
                   2393:  
1.984     neumanie 2394: sub resizeImage {
1.1051    raeburn  2395:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2396:     my $ima = Image::Magick->new;
                   2397:     my $resized;
                   2398:     if (-e $img_path) {
                   2399:         $ima->Read($img_path);
                   2400:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2401:             my $width = $ima->Get('width');
                   2402:             my $height = $ima->Get('height');
                   2403:             if ($width > $resizewidth) {
                   2404: 	        my $factor = $width/$resizewidth;
                   2405:                 my $newheight = $height/$factor;
                   2406:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2407:                 $resized = 1;
                   2408:             }
                   2409:         }
                   2410:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2411:             my $width = $ima->Get('width');
                   2412:             my $height = $ima->Get('height');
                   2413:             if ($height > $resizeheight) {
                   2414:                 my $factor = $height/$resizeheight;
                   2415:                 my $newwidth = $width/$factor;
                   2416:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2417:                 $resized = 1;
                   2418:             }
                   2419:         }
                   2420:         if ($resized) {
                   2421:             $ima->Write($img_path);
                   2422:         }
                   2423:     }
                   2424:     return;
1.977     amueller 2425: }
                   2426: 
1.608     albertel 2427: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2428: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13  raeburn  2429: #                    the desired filename is in $env{"form.$formname.filename"}
                   2430: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2431: #                                    canceloverwrite, or ''.
                   2432: #                   if 'coursedoc': upload to the current course
                   2433: #                   if 'existingfile': write file to tmp/overwrites directory
                   2434: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2435: #                   $context is passed as argument to &finishuserfileupload 
1.686     albertel 2436: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2437: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2438: #        $allfiles - reference to hash for embedded objects
                   2439: #        $codebase - reference to hash for codebase of java objects
                   2440: #        $desuname - username for permanent storage of uploaded file
                   2441: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2442: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2443: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2444: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2445: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1056.4.16  raeburn  2446: #        $mimetype - reference to scalar to accommodate mime type determined
                   2447: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2448: # 
1.686     albertel 2449: # output: url of file in userspace, or error: <message> 
                   2450: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2451: 
1.531     albertel 2452: sub userfileupload {
1.1056.4.13  raeburn  2453:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1056.4.16  raeburn  2454:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2455:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2456:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2457:     $fname=&clean_filename($fname);
1.1056.4.13  raeburn  2458:     # See if there is anything left
1.257     www      2459:     unless ($fname) { return 'error: no uploaded file'; }
1.1056.4.13  raeburn  2460:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2461:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2462:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2463:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2464:         my $now = time;
1.1056.4.13  raeburn  2465:         my $filepath;
                   2466:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
                   2467:              $filepath = 'tmp/helprequests/'.$now;
                   2468:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2469:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2470:                          '_'.$env{'user.domain'}.'/pending';
                   2471:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2472:             my ($docuname,$docudom);
                   2473:             if ($destudom) {
                   2474:                 $docudom = $destudom;
                   2475:             } else {
                   2476:                 $docudom = $env{'user.domain'};
                   2477:             }
                   2478:             if ($destuname) {
                   2479:                 $docuname = $destuname;
                   2480:             } else {
                   2481:                 $docuname = $env{'user.name'};
                   2482:             }
                   2483:             if (exists($env{'form.group'})) {
                   2484:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2485:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2486:             }
                   2487:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2488:             if ($context eq 'canceloverwrite') {
                   2489:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2490:                 if (-e  $tempfile) {
                   2491:                     my @info = stat($tempfile);
                   2492:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2493:                         unlink($tempfile);
                   2494:                     }
                   2495:                 }
                   2496:                 return;
1.523     raeburn  2497:             }
                   2498:         }
1.1056.4.13  raeburn  2499:         # Create the directory if not present
1.741     raeburn  2500:         my @parts=split(/\//,$filepath);
                   2501:         my $fullpath = $perlvar{'lonDaemons'};
                   2502:         for (my $i=0;$i<@parts;$i++) {
                   2503:             $fullpath .= '/'.$parts[$i];
                   2504:             if ((-e $fullpath)!=1) {
                   2505:                 mkdir($fullpath,0777);
                   2506:             }
                   2507:         }
                   2508:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2509:         print $fh $env{'form.'.$formname};
                   2510:         close($fh);
1.1056.4.13  raeburn  2511:         if ($context eq 'existingfile') {
                   2512:             my @info = stat($fullpath.'/'.$fname);
                   2513:             return ($fullpath.'/'.$fname,$info[9]);
                   2514:         } else {
                   2515:             return $fullpath.'/'.$fname;
                   2516:         }
1.523     raeburn  2517:     }
1.995     raeburn  2518:     if ($subdir eq 'scantron') {
                   2519:         $fname = 'scantron_orig_'.$fname;
1.1056.4.14  raeburn  2520:     } else {
1.995     raeburn  2521:         $fname="$subdir/$fname";
                   2522:     }
1.1056.4.13  raeburn  2523:     if ($context eq 'coursedoc') {
1.638     albertel 2524: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2525: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2526:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2527:             return &finishuserfileupload($docuname,$docudom,
                   2528: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2529: 					 $codebase,$thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2530:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2531:         } else {
1.620     albertel 2532:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2533:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2534: 				       $fname,$formname,$parser,
1.1056.4.16  raeburn  2535: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2536:         }
1.719     banghart 2537:     } elsif (defined($destuname)) {
                   2538:         my $docuname=$destuname;
                   2539:         my $docudom=$destudom;
1.860     raeburn  2540: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2541: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2542:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2543:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2544:     } else {
1.638     albertel 2545:         my $docuname=$env{'user.name'};
                   2546:         my $docudom=$env{'user.domain'};
1.714     raeburn  2547:         if (exists($env{'form.group'})) {
                   2548:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2549:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2550:         }
1.860     raeburn  2551: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2552: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2553:                                      $thumbwidth,$thumbheight,
1.1056.4.16  raeburn  2554:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2555:     }
1.271     www      2556: }
                   2557: 
                   2558: sub finishuserfileupload {
1.860     raeburn  2559:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.16  raeburn  2560:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2561:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2562:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2563:   
1.860     raeburn  2564:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2565:     $file=$fname;
                   2566:     if ($fname=~m|/|) {
                   2567:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2568: 	$path.=$fnamepath.'/';
                   2569:     }
1.259     www      2570:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2571:     my $count;
                   2572:     for ($count=4;$count<=$#parts;$count++) {
                   2573:         $filepath.="/$parts[$count]";
                   2574:         if ((-e $filepath)!=1) {
                   2575: 	    mkdir($filepath,0777);
                   2576:         }
                   2577:     }
1.984     neumanie 2578: 
1.258     www      2579: # Save the file
                   2580:     {
1.701     albertel 2581: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2582: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2583: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2584: 	    return '/adm/notfound.html';
                   2585: 	}
1.1056.4.13  raeburn  2586:         if ($context eq 'overwrite') {
                   2587:             my $source =  $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
                   2588:             my $target = $filepath.'/'.$file;
                   2589:             if (-e $source) {
                   2590:                 my @info = stat($source);
                   2591:                 if ($info[9] eq $env{'form.timestamp'}) {
                   2592:                     unless (&File::Copy::move($source,$target)) {
                   2593:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2594:                         return "Moving from $source failed";
                   2595:                     }
                   2596:                 } else {
                   2597:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2598:                 }
                   2599:             } else {
                   2600:                 return "Temporary file: $source missing";
                   2601:             }
                   2602: 	} elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2603: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2604: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2605: 	    return '/adm/notfound.html';
                   2606: 	}
1.570     albertel 2607: 	close(FH);
1.1051    raeburn  2608:         if ($resizewidth && $resizeheight) {
                   2609:             my $mm = new File::MMagic;
                   2610:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2611:             if ($mime_type =~ m{^image/}) {
                   2612: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2613:             }  
1.977     amueller 2614: 	}
1.258     www      2615:     }
1.637     raeburn  2616:     if ($parser eq 'parse') {
1.1024    raeburn  2617:         my $mm = new File::MMagic;
1.1056.4.16  raeburn  2618:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2619:         if ($type eq 'text/html') {
1.1024    raeburn  2620:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2621:                                                        $allfiles,$codebase);
                   2622:             unless ($parse_result eq 'ok') {
                   2623:                 &logthis('Failed to parse '.$filepath.$file.
                   2624: 	   	         ' for embedded media: '.$parse_result); 
                   2625:             }
1.637     raeburn  2626:         }
1.1056.4.16  raeburn  2627:         if (ref($mimetype)) {
                   2628:             $$mimetype = $type;
                   2629:         }
1.637     raeburn  2630:     }
1.860     raeburn  2631:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2632:         my $input = $filepath.'/'.$file;
                   2633:         my $output = $filepath.'/'.'tn-'.$file;
                   2634:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2635:         system("convert -sample $thumbsize $input $output");
                   2636:         if (-e $filepath.'/'.'tn-'.$file) {
                   2637:             $fetchthumb  = 1; 
                   2638:         }
                   2639:     }
1.858     raeburn  2640:  
1.259     www      2641: # Notify homeserver to grep it
                   2642: #
1.984     neumanie 2643:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2644:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2645:     if ($fetchresult eq 'ok') {
1.860     raeburn  2646:         if ($fetchthumb) {
                   2647:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2648:             if ($thumbresult ne 'ok') {
                   2649:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2650:                          $docuhome.': '.$thumbresult);
                   2651:             }
                   2652:         }
1.259     www      2653: #
1.258     www      2654: # Return the URL to it
1.494     albertel 2655:         return '/uploaded/'.$path.$file;
1.263     www      2656:     } else {
1.494     albertel 2657:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2658: 		 ': '.$fetchresult);
1.263     www      2659:         return '/adm/notfound.html';
1.858     raeburn  2660:     }
1.493     albertel 2661: }
                   2662: 
1.637     raeburn  2663: sub extract_embedded_items {
1.961     raeburn  2664:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2665:     my @state = ();
                   2666:     my %javafiles = (
                   2667:                       codebase => '',
                   2668:                       code => '',
                   2669:                       archive => ''
                   2670:                     );
                   2671:     my %mediafiles = (
                   2672:                       src => '',
                   2673:                       movie => '',
                   2674:                      );
1.648     raeburn  2675:     my $p;
                   2676:     if ($content) {
                   2677:         $p = HTML::LCParser->new($content);
                   2678:     } else {
1.961     raeburn  2679:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2680:     }
1.641     albertel 2681:     while (my $t=$p->get_token()) {
1.640     albertel 2682: 	if ($t->[0] eq 'S') {
                   2683: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2684: 	    push(@state, $tagname);
1.648     raeburn  2685:             if (lc($tagname) eq 'allow') {
                   2686:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2687:             }
1.640     albertel 2688: 	    if (lc($tagname) eq 'img') {
                   2689: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2690: 	    }
1.886     albertel 2691: 	    if (lc($tagname) eq 'a') {
                   2692: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2693: 	    }
1.645     raeburn  2694:             if (lc($tagname) eq 'script') {
                   2695:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2696:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2697:                 } else {
                   2698:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2699:                 }
                   2700:             }
                   2701:             if (lc($tagname) eq 'link') {
                   2702:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2703:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2704:                 }
                   2705:             }
1.640     albertel 2706: 	    if (lc($tagname) eq 'object' ||
                   2707: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2708: 		foreach my $item (keys(%javafiles)) {
                   2709: 		    $javafiles{$item} = '';
                   2710: 		}
                   2711: 	    }
                   2712: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2713: 		my $name = lc($attr->{'name'});
                   2714: 		foreach my $item (keys(%javafiles)) {
                   2715: 		    if ($name eq $item) {
                   2716: 			$javafiles{$item} = $attr->{'value'};
                   2717: 			last;
                   2718: 		    }
                   2719: 		}
                   2720: 		foreach my $item (keys(%mediafiles)) {
                   2721: 		    if ($name eq $item) {
                   2722: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2723: 			last;
                   2724: 		    }
                   2725: 		}
                   2726: 	    }
                   2727: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2728: 		foreach my $item (keys(%javafiles)) {
                   2729: 		    if ($attr->{$item}) {
                   2730: 			$javafiles{$item} = $attr->{$item};
                   2731: 			last;
                   2732: 		    }
                   2733: 		}
                   2734: 		foreach my $item (keys(%mediafiles)) {
                   2735: 		    if ($attr->{$item}) {
                   2736: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2737: 			last;
                   2738: 		    }
                   2739: 		}
                   2740: 	    }
                   2741: 	} elsif ($t->[0] eq 'E') {
                   2742: 	    my ($tagname) = ($t->[1]);
                   2743: 	    if ($javafiles{'codebase'} ne '') {
                   2744: 		$javafiles{'codebase'} .= '/';
                   2745: 	    }  
                   2746: 	    if (lc($tagname) eq 'applet' ||
                   2747: 		lc($tagname) eq 'object' ||
                   2748: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2749: 		) {
                   2750: 		foreach my $item (keys(%javafiles)) {
                   2751: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2752: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2753: 			&add_filetype($allfiles,$file,$item);
                   2754: 		    }
                   2755: 		}
                   2756: 	    } 
                   2757: 	    pop @state;
                   2758: 	}
                   2759:     }
1.637     raeburn  2760:     return 'ok';
                   2761: }
                   2762: 
1.639     albertel 2763: sub add_filetype {
                   2764:     my ($allfiles,$file,$type)=@_;
                   2765:     if (exists($allfiles->{$file})) {
                   2766: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2767: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2768: 	}
                   2769:     } else {
                   2770: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2771:     }
                   2772: }
                   2773: 
1.493     albertel 2774: sub removeuploadedurl {
1.984     neumanie 2775:     my ($url)=@_;	
                   2776:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2777:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2778: }
                   2779: 
                   2780: sub removeuserfile {
                   2781:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2782:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2783:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2784:     if ($result eq 'ok') {	
1.798     raeburn  2785:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2786:             my $metafile = $fname.'.meta';
                   2787:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2788: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2789:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2790:             my $sqlresult = 
1.823     albertel 2791:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2792:                                         'portfolio_metadata',$group,
                   2793:                                         'delete');
1.798     raeburn  2794:         }
                   2795:     }
                   2796:     return $result;
1.257     www      2797: }
1.15      www      2798: 
1.530     albertel 2799: sub mkdiruserfile {
                   2800:     my ($docuname,$docudom,$dir)=@_;
                   2801:     my $home=&homeserver($docuname,$docudom);
                   2802:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2803: }
                   2804: 
1.531     albertel 2805: sub renameuserfile {
                   2806:     my ($docuname,$docudom,$old,$new)=@_;
                   2807:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2808:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2809:                         &escape("$old").':'.&escape("$new"),$home);
                   2810:     if ($result eq 'ok') {
                   2811:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2812:             my $oldmeta = $old.'.meta';
                   2813:             my $newmeta = $new.'.meta';
                   2814:             my $metaresult = 
                   2815:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2816: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2817:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2818:             my $sqlresult = 
1.823     albertel 2819:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2820:                                         'portfolio_metadata',$group,
                   2821:                                         'delete');
1.798     raeburn  2822:         }
                   2823:     }
                   2824:     return $result;
1.531     albertel 2825: }
                   2826: 
1.14      www      2827: # ------------------------------------------------------------------------- Log
                   2828: 
                   2829: sub log {
                   2830:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2831:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2832: }
                   2833: 
                   2834: # ------------------------------------------------------------------ Course Log
1.352     www      2835: #
                   2836: # This routine flushes several buffers of non-mission-critical nature
                   2837: #
1.157     www      2838: 
                   2839: sub flushcourselogs {
1.352     www      2840:     &logthis('Flushing log buffers');
                   2841: #
                   2842: # course logs
                   2843: # This is a log of all transactions in a course, which can be used
                   2844: # for data mining purposes
                   2845: #
                   2846: # It also collects the courseid database, which lists last transaction
                   2847: # times and course titles for all courseids
                   2848: #
                   2849:     my %courseidbuffer=();
1.921     raeburn  2850:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2851:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2852: 		          &escape($courselogs{$crsid}),
                   2853: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2854: 	    delete $courselogs{$crsid};
                   2855:         } else {
                   2856:             &logthis('Failed to flush log buffer for '.$crsid);
                   2857:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2858:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2859:                         " exceeded maximum size, deleting.</font>");
                   2860:                delete $courselogs{$crsid};
                   2861:             }
1.352     www      2862:         }
1.920     raeburn  2863:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2864:             'description' => $coursedescrbuf{$crsid},
                   2865:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2866:             'type'        => $coursetypebuf{$crsid},
                   2867:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2868:         };
1.191     harris41 2869:     }
1.352     www      2870: #
                   2871: # Write course id database (reverse lookup) to homeserver of courses 
                   2872: # Is used in pickcourse
                   2873: #
1.840     albertel 2874:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2875:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2876:                                     $courseidbuffer{$crs_home},
                   2877:                                     $crs_home,'timeonly');
1.352     www      2878:     }
                   2879: #
                   2880: # File accesses
                   2881: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2882: #
1.449     matthew  2883:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2884:         if ($entry =~ /___count$/) {
                   2885:             my ($dom,$name);
1.807     albertel 2886:             ($dom,$name,undef)=
1.811     albertel 2887: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2888:             if (! defined($dom) || $dom eq '' || 
                   2889:                 ! defined($name) || $name eq '') {
1.620     albertel 2890:                 my $cid = $env{'request.course.id'};
                   2891:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2892:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2893:             }
1.450     matthew  2894:             my $value = $accesshash{$entry};
                   2895:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2896:             my %temphash=($url => $value);
1.449     matthew  2897:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2898:             if ($result eq 'ok') {
                   2899:                 delete $accesshash{$entry};
                   2900:             } elsif ($result eq 'unknown_cmd') {
                   2901:                 # Target server has old code running on it.
1.450     matthew  2902:                 my %temphash=($entry => $value);
1.449     matthew  2903:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2904:                     delete $accesshash{$entry};
                   2905:                 }
                   2906:             }
                   2907:         } else {
1.811     albertel 2908:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2909:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2910:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2911:                 delete $accesshash{$entry};
                   2912:             }
1.185     www      2913:         }
1.191     harris41 2914:     }
1.352     www      2915: #
                   2916: # Roles
                   2917: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2918: #
1.800     albertel 2919:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2920:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2921: 	    split(/\:/,$entry);
                   2922:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2923:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2924:                 $rudom,$runame) eq 'ok') {
                   2925: 	    delete $userrolehash{$entry};
                   2926:         }
                   2927:     }
1.662     raeburn  2928: #
                   2929: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2930: #
                   2931:     my %domrolebuffer = ();
1.1000    raeburn  2932:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2933:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2934:         if ($domrolebuffer{$rudom}) {
                   2935:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2936:                       '='.&escape($domainrolehash{$entry});
                   2937:         } else {
                   2938:             $domrolebuffer{$rudom}.=&escape($entry).
                   2939:                       '='.&escape($domainrolehash{$entry});
                   2940:         }
                   2941:         delete $domainrolehash{$entry};
                   2942:     }
                   2943:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2944: 	my %servers = &get_servers($dom,'library');
                   2945: 	foreach my $tryserver (keys(%servers)) {
                   2946: 	    unless (&reply('domroleput:'.$dom.':'.
                   2947: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2948: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2949: 	    }
1.662     raeburn  2950:         }
                   2951:     }
1.186     www      2952:     $dumpcount++;
1.157     www      2953: }
                   2954: 
                   2955: sub courselog {
                   2956:     my $what=shift;
1.158     www      2957:     $what=time.':'.$what;
1.620     albertel 2958:     unless ($env{'request.course.id'}) { return ''; }
                   2959:     $coursedombuf{$env{'request.course.id'}}=
                   2960:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2961:     $coursenumbuf{$env{'request.course.id'}}=
                   2962:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2963:     $coursehombuf{$env{'request.course.id'}}=
                   2964:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2965:     $coursedescrbuf{$env{'request.course.id'}}=
                   2966:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2967:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2968:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2969:     $courseownerbuf{$env{'request.course.id'}}=
                   2970:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2971:     $coursetypebuf{$env{'request.course.id'}}=
                   2972:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2973:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2974: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2975:     } else {
1.620     albertel 2976: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2977:     }
1.620     albertel 2978:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2979: 	&flushcourselogs();
                   2980:     }
1.158     www      2981: }
                   2982: 
                   2983: sub courseacclog {
                   2984:     my $fnsymb=shift;
1.620     albertel 2985:     unless ($env{'request.course.id'}) { return ''; }
                   2986:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2987:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2988:         $what.=':POST';
1.583     matthew  2989:         # FIXME: Probably ought to escape things....
1.800     albertel 2990: 	foreach my $key (keys(%env)) {
                   2991:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2992:                 my $formitem = $1;
                   2993:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2994:                     $what.=':'.$formitem.'='.$env{$key};
                   2995:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2996:                     $what.=':'.$formitem.'='.$env{$key};
                   2997:                 }
1.158     www      2998:             }
1.191     harris41 2999:         }
1.583     matthew  3000:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3001:         # FIXME: We should not be depending on a form parameter that someone
                   3002:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3003:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3004:             $what.= ':POST';
                   3005:             # FIXME: Probably ought to escape things....
                   3006:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3007:                                  'crsdiscuss') {
1.620     albertel 3008:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3009:             }
                   3010:         }
1.158     www      3011:     }
                   3012:     &courselog($what);
1.149     www      3013: }
                   3014: 
1.185     www      3015: sub countacc {
                   3016:     my $url=&declutter(shift);
1.458     matthew  3017:     return if (! defined($url) || $url eq '');
1.620     albertel 3018:     unless ($env{'request.course.id'}) { return ''; }
                   3019:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3020:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3021:     $accesshash{$key}++;
1.185     www      3022: }
1.349     www      3023: 
1.361     www      3024: sub linklog {
                   3025:     my ($from,$to)=@_;
                   3026:     $from=&declutter($from);
                   3027:     $to=&declutter($to);
                   3028:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3029:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3030: }
                   3031:   
1.349     www      3032: sub userrolelog {
                   3033:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3034:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3035:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3036:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3037:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3038:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3039:        $userrolehash
                   3040:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3041:                     =$tend.':'.$tstart;
1.662     raeburn  3042:     }
1.898     albertel 3043:     if (($env{'request.role'} =~ /dc\./) &&
                   3044: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3045: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3046: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3047:          ($trole=~/^co/))) {
1.898     albertel 3048:        $userrolehash
                   3049:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3050:                     =$tend.':'.$tstart;
                   3051:     }
1.662     raeburn  3052:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3053:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3054:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3055:         ($trole=~/^sc/)) {
                   3056:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3057:        $domainrolehash
                   3058:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3059:                     = $tend.':'.$tstart;
                   3060:     }
1.351     www      3061: }
                   3062: 
1.957     raeburn  3063: sub courserolelog {
                   3064:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3065:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3066:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3067:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3068:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3069:         ($trole eq 'co')) {
1.957     raeburn  3070:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3071:             my $cdom = $1;
                   3072:             my $cnum = $2;
                   3073:             my $sec = $3;
                   3074:             my $namespace = 'rolelog';
                   3075:             my %storehash = (
                   3076:                                role    => $trole,
                   3077:                                start   => $tstart,
                   3078:                                end     => $tend,
                   3079:                                selfenroll => $selfenroll,
                   3080:                                context    => $context,
                   3081:                             );
                   3082:             if ($trole eq 'gr') {
                   3083:                 $namespace = 'groupslog';
                   3084:                 $storehash{'group'} = $sec;
                   3085:             } else {
                   3086:                 $storehash{'section'} = $sec;
                   3087:             }
                   3088:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3089:             if (($trole ne 'st') || ($sec ne '')) {
                   3090:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3091:             }
1.957     raeburn  3092:         }
                   3093:     }
                   3094:     return;
                   3095: }
                   3096: 
1.351     www      3097: sub get_course_adv_roles {
1.948     raeburn  3098:     my ($cid,$codes) = @_;
1.620     albertel 3099:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3100:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3101:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3102:     my %nothide=();
1.800     albertel 3103:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3104:         if ($user !~ /:/) {
                   3105: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3106:         } else {
                   3107:             $nothide{$user}=1;
                   3108:         }
1.470     www      3109:     }
1.351     www      3110:     my %returnhash=();
                   3111:     my %dumphash=
                   3112:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3113:     my $now=time;
1.997     raeburn  3114:     my %privileged;
1.1000    raeburn  3115:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3116: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3117:         if (($tstart) && ($tstart<0)) { next; }
                   3118:         if (($tend) && ($tend<$now)) { next; }
                   3119:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3120:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3121: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3122:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3123:             my %dompersonnel =
1.998     raeburn  3124:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3125:             $privileged{$domain} = {};
                   3126:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3127:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3128:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3129:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3130:                         $privileged{$udom}{$uname} = 1;
                   3131:                     }
                   3132:                 }
                   3133:             }
                   3134:         }
                   3135:         if ((exists($privileged{$domain}{$username})) && 
                   3136:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3137: 	if ($role eq 'cr') { next; }
1.948     raeburn  3138:         if ($codes) {
                   3139:             if ($section) { $role .= ':'.$section; }
                   3140:             if ($returnhash{$role}) {
                   3141:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3142:             } else {
                   3143:                 $returnhash{$role}=$username.':'.$domain;
                   3144:             }
1.351     www      3145:         } else {
1.988     raeburn  3146:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3147:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3148:             if ($returnhash{$key}) {
                   3149: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3150:             } else {
                   3151:                 $returnhash{$key}=$username.':'.$domain;
                   3152:             }
1.351     www      3153:         }
1.948     raeburn  3154:     }
1.400     www      3155:     return %returnhash;
                   3156: }
                   3157: 
                   3158: sub get_my_roles {
1.937     raeburn  3159:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3160:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3161:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3162:     my (%dumphash,%nothide);
1.858     raeburn  3163:     if ($context eq 'userroles') { 
1.1056.4.10  raeburn  3164:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3165:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3166:     } else {
                   3167:         %dumphash=
1.400     www      3168:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3169:         if ($hidepriv) {
                   3170:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3171:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3172:                 if ($user !~ /:/) {
                   3173:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3174:                 } else {
                   3175:                     $nothide{$user} = 1;
                   3176:                 }
                   3177:             }
                   3178:         }
1.858     raeburn  3179:     }
1.400     www      3180:     my %returnhash=();
                   3181:     my $now=time;
1.999     raeburn  3182:     my %privileged;
1.800     albertel 3183:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3184:         my ($role,$tend,$tstart);
                   3185:         if ($context eq 'userroles') {
                   3186: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3187:         } else {
                   3188:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3189:         }
1.400     www      3190:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3191:         my $status = 'active';
1.939     raeburn  3192:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3193:             $status = 'previous';
                   3194:         } 
                   3195:         if (($tstart) && ($now<$tstart)) {
                   3196:             $status = 'future';
                   3197:         }
                   3198:         if (ref($types) eq 'ARRAY') {
                   3199:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3200:                 next;
                   3201:             } 
                   3202:         } else {
                   3203:             if ($status ne 'active') {
                   3204:                 next;
                   3205:             }
                   3206:         }
1.867     raeburn  3207:         my ($rolecode,$username,$domain,$section,$area);
                   3208:         if ($context eq 'userroles') {
                   3209:             ($area,$rolecode) = split(/_/,$entry);
                   3210:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3211:         } else {
                   3212:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3213:         }
1.832     raeburn  3214:         if (ref($roledoms) eq 'ARRAY') {
                   3215:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3216:                 next;
                   3217:             }
                   3218:         }
                   3219:         if (ref($roles) eq 'ARRAY') {
                   3220:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3221:                 if ($role =~ /^cr\//) {
                   3222:                     if (!grep(/^cr$/,@{$roles})) {
                   3223:                         next;
                   3224:                     }
                   3225:                 } else {
                   3226:                     next;
                   3227:                 }
1.832     raeburn  3228:             }
1.867     raeburn  3229:         }
1.937     raeburn  3230:         if ($hidepriv) {
1.999     raeburn  3231:             if ($context eq 'userroles') {
                   3232:                 if ((&privileged($username,$domain)) &&
                   3233:                     (!$nothide{$username.':'.$domain})) {
                   3234:                     next;
                   3235:                 }
                   3236:             } else {
                   3237:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3238:                     my %dompersonnel =
                   3239:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3240:                     $privileged{$domain} = {};
                   3241:                     if (keys(%dompersonnel)) {
                   3242:                         foreach my $server (keys(%dompersonnel)) {
                   3243:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3244:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3245:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3246:                                     $privileged{$udom}{$uname} = $trole;
                   3247:                                 }
                   3248:                             }
                   3249:                         }
                   3250:                     }
                   3251:                 }
                   3252:                 if (exists($privileged{$domain}{$username})) {
                   3253:                     if (!$nothide{$username.':'.$domain}) {
                   3254:                         next;
                   3255:                     }
                   3256:                 }
1.937     raeburn  3257:             }
                   3258:         }
1.933     raeburn  3259:         if ($withsec) {
                   3260:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3261:                 $tstart.':'.$tend;
                   3262:         } else {
                   3263:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3264:         }
1.832     raeburn  3265:     }
1.373     www      3266:     return %returnhash;
1.399     www      3267: }
                   3268: 
                   3269: # ----------------------------------------------------- Frontpage Announcements
                   3270: #
                   3271: #
                   3272: 
                   3273: sub postannounce {
                   3274:     my ($server,$text)=@_;
1.844     albertel 3275:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3276:     unless ($text=~/\w/) { $text=''; }
                   3277:     return &reply('setannounce:'.&escape($text),$server);
                   3278: }
                   3279: 
                   3280: sub getannounce {
1.448     albertel 3281: 
                   3282:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3283: 	my $announcement='';
1.800     albertel 3284: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3285: 	close($fh);
1.399     www      3286: 	if ($announcement=~/\w/) { 
                   3287: 	    return 
                   3288:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3289:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3290: 	} else {
                   3291: 	    return '';
                   3292: 	}
                   3293:     } else {
                   3294: 	return '';
                   3295:     }
1.351     www      3296: }
1.353     www      3297: 
                   3298: # ---------------------------------------------------------- Course ID routines
                   3299: # Deal with domain's nohist_courseid.db files
                   3300: #
                   3301: 
                   3302: sub courseidput {
1.921     raeburn  3303:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3304:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3305:     my $outcome;
                   3306:     if ($caller eq 'timeonly') {
                   3307:         my $cids = '';
                   3308:         foreach my $item (keys(%$storehash)) {
                   3309:             $cids.=&escape($item).'&';
                   3310:         }
                   3311:         $cids=~s/\&$//;
                   3312:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3313:                           $coursehome);       
                   3314:     } else {
                   3315:         my $items = '';
                   3316:         foreach my $item (keys(%$storehash)) {
                   3317:             $items.= &escape($item).'='.
                   3318:                      &freeze_escape($$storehash{$item}).'&';
                   3319:         }
                   3320:         $items=~s/\&$//;
                   3321:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3322:                           $coursehome);
1.918     raeburn  3323:     }
                   3324:     if ($outcome eq 'unknown_cmd') {
                   3325:         my $what;
                   3326:         foreach my $cid (keys(%$storehash)) {
                   3327:             $what .= &escape($cid).'=';
1.921     raeburn  3328:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3329:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3330:             }
                   3331:             $what =~ s/\:$/&/;
                   3332:         }
                   3333:         $what =~ s/\&$//;  
                   3334:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3335:     } else {
                   3336:         return $outcome;
                   3337:     }
1.353     www      3338: }
                   3339: 
                   3340: sub courseiddump {
1.921     raeburn  3341:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3342:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3343:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3  raeburn  3344:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3345:     my $as_hash = 1;
                   3346:     my %returnhash;
                   3347:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3348:     my %libserv = &all_library();
                   3349:     foreach my $tryserver (keys(%libserv)) {
                   3350:         if ( (  $hostidflag == 1 
                   3351: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3352: 	     || (!defined($hostidflag)) ) {
                   3353: 
1.918     raeburn  3354: 	    if (($domfilter eq '') ||
                   3355: 		(&host_domain($tryserver) eq $domfilter)) {
                   3356:                 my $rep = 
                   3357:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3358:                          $sincefilter.':'.&escape($descfilter).':'.
                   3359:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3360:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3361:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3362:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3363:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3364:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3365:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3  raeburn  3366:                          &escape($creationcontext).':'.$domcloner,
                   3367:                          $tryserver);
1.918     raeburn  3368:                 my @pairs=split(/\&/,$rep);
                   3369:                 foreach my $item (@pairs) {
                   3370:                     my ($key,$value)=split(/\=/,$item,2);
                   3371:                     $key = &unescape($key);
                   3372:                     next if ($key =~ /^error: 2 /);
                   3373:                     my $result = &thaw_unescape($value);
                   3374:                     if (ref($result) eq 'HASH') {
                   3375:                         $returnhash{$key}=$result;
                   3376:                     } else {
1.921     raeburn  3377:                         my @responses = split(/:/,$value);
                   3378:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3379:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3380:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3381:                         }
1.1008    raeburn  3382:                     }
1.353     www      3383:                 }
                   3384:             }
                   3385:         }
                   3386:     }
                   3387:     return %returnhash;
                   3388: }
                   3389: 
1.1055    raeburn  3390: sub courselastaccess {
                   3391:     my ($cdom,$cnum,$hostidref) = @_;
                   3392:     my %returnhash;
                   3393:     if ($cdom && $cnum) {
                   3394:         my $chome = &homeserver($cnum,$cdom);
                   3395:         if ($chome ne 'no_host') {
                   3396:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3397:             &extract_lastaccess(\%returnhash,$rep);
                   3398:         }
                   3399:     } else {
                   3400:         if (!$cdom) { $cdom=''; }
                   3401:         my %libserv = &all_library();
                   3402:         foreach my $tryserver (keys(%libserv)) {
                   3403:             if (ref($hostidref) eq 'ARRAY') {
                   3404:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3405:             } 
                   3406:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3407:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3408:                 &extract_lastaccess(\%returnhash,$rep);
                   3409:             }
                   3410:         }
                   3411:     }
                   3412:     return %returnhash;
                   3413: }
                   3414: 
                   3415: sub extract_lastaccess {
                   3416:     my ($returnhash,$rep) = @_;
                   3417:     if (ref($returnhash) eq 'HASH') {
                   3418:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3419:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3420:                  $rep eq '') {
                   3421:             my @pairs=split(/\&/,$rep);
                   3422:             foreach my $item (@pairs) {
                   3423:                 my ($key,$value)=split(/\=/,$item,2);
                   3424:                 $key = &unescape($key);
                   3425:                 next if ($key =~ /^error: 2 /);
                   3426:                 $returnhash->{$key} = &thaw_unescape($value);
                   3427:             }
                   3428:         }
                   3429:     }
                   3430:     return;
                   3431: }
                   3432: 
1.658     raeburn  3433: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3434: 
                   3435: sub dcmailput {
1.685     raeburn  3436:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3437:     my $status = &Apache::lonnet::critical(
1.740     www      3438:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3439:        &escape($message),$server);
1.662     raeburn  3440:     return $status;
                   3441: }
                   3442: 
1.658     raeburn  3443: sub dcmaildump {
                   3444:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3445:     my %returnhash=();
1.846     albertel 3446: 
                   3447:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3448:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3449:                                                          &escape($enddate).':';
                   3450: 	my @esc_senders=map { &escape($_)} @$senders;
                   3451: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3452: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3453:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3454:             if (($key) && ($value)) {
                   3455:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3456:             }
                   3457:         }
                   3458:     }
                   3459:     return %returnhash;
                   3460: }
1.662     raeburn  3461: # ---------------------------------------------------------- Domain roles
                   3462: 
                   3463: sub get_domain_roles {
                   3464:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3465:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3466:         $startdate = '.';
                   3467:     }
1.1018    raeburn  3468:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3469:         $enddate = '.';
                   3470:     }
1.922     raeburn  3471:     my $rolelist;
                   3472:     if (ref($roles) eq 'ARRAY') {
                   3473:         $rolelist = join(':',@{$roles});
                   3474:     }
1.662     raeburn  3475:     my %personnel = ();
1.841     albertel 3476: 
                   3477:     my %servers = &get_servers($dom,'library');
                   3478:     foreach my $tryserver (keys(%servers)) {
                   3479: 	%{$personnel{$tryserver}}=();
                   3480: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3481: 					    &escape($startdate).':'.
                   3482: 					    &escape($enddate).':'.
                   3483: 					    &escape($rolelist), $tryserver))) {
                   3484: 	    my ($key,$value) = split(/\=/,$line,2);
                   3485: 	    if (($key) && ($value)) {
                   3486: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3487: 	    }
                   3488: 	}
1.662     raeburn  3489:     }
                   3490:     return %personnel;
                   3491: }
1.658     raeburn  3492: 
1.149     www      3493: # ----------------------------------------------------------- Check out an item
                   3494: 
1.504     albertel 3495: sub get_first_access {
                   3496:     my ($type,$argsymb)=@_;
1.790     albertel 3497:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3498:     if ($argsymb) { $symb=$argsymb; }
                   3499:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3500:     if ($type eq 'course') {
                   3501: 	$res='course';
                   3502:     } elsif ($type eq 'map') {
1.588     albertel 3503: 	$res=&symbread($map);
                   3504:     } else {
                   3505: 	$res=$symb;
                   3506:     }
                   3507:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3508:     return $times{"$courseid\0$res"};
1.504     albertel 3509: }
                   3510: 
                   3511: sub set_first_access {
                   3512:     my ($type)=@_;
1.790     albertel 3513:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3514:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3515:     if ($type eq 'course') {
                   3516: 	$res='course';
                   3517:     } elsif ($type eq 'map') {
1.588     albertel 3518: 	$res=&symbread($map);
                   3519:     } else {
                   3520: 	$res=$symb;
                   3521:     }
                   3522:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3523:     if (!$firstaccess) {
1.588     albertel 3524: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3525:     }
                   3526:     return 'already_set';
1.504     albertel 3527: }
                   3528: 
1.149     www      3529: sub checkout {
                   3530:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3531:     my $now=time;
                   3532:     my $lonhost=$perlvar{'lonHostID'};
                   3533:     my $infostr=&escape(
1.234     www      3534:                  'CHECKOUTTOKEN&'.
1.149     www      3535:                  $tuname.'&'.
                   3536:                  $tudom.'&'.
                   3537:                  $tcrsid.'&'.
                   3538:                  $symb.'&'.
                   3539: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3540:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3541:     if ($token=~/^error\:/) { 
1.672     albertel 3542:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3543:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3544:                  "</font>");
                   3545:         return ''; 
                   3546:     }
                   3547: 
1.149     www      3548:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3549:     $token=~tr/a-z/A-Z/;
                   3550: 
1.153     www      3551:     my %infohash=('resource.0.outtoken' => $token,
                   3552:                   'resource.0.checkouttime' => $now,
                   3553:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3554: 
                   3555:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3556:        return '';
1.151     www      3557:     } else {
1.672     albertel 3558:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3559:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3560:                  "</font>");
1.149     www      3561:     }    
                   3562: 
                   3563:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3564:                          &escape('Checkout '.$infostr.' - '.
                   3565:                                                  $token)) ne 'ok') {
                   3566: 	return '';
1.151     www      3567:     } else {
1.672     albertel 3568:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3569:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3570:                  "</font>");
1.149     www      3571:     }
1.151     www      3572:     return $token;
1.149     www      3573: }
                   3574: 
                   3575: # ------------------------------------------------------------ Check in an item
                   3576: 
                   3577: sub checkin {
                   3578:     my $token=shift;
1.150     www      3579:     my $now=time;
                   3580:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3581:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3582:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3583:     $dtoken=~s/\W/\_/g;
1.234     www      3584:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3585:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3586: 
1.154     www      3587:     unless (($tuname) && ($tudom)) {
                   3588:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3589:         return '';
                   3590:     }
                   3591:     
                   3592:     unless (&allowed('mgr',$tcrsid)) {
                   3593:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3594:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3595:         return '';
                   3596:     }
                   3597: 
1.153     www      3598:     my %infohash=('resource.0.intoken' => $token,
                   3599:                   'resource.0.checkintime' => $now,
                   3600:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3601: 
                   3602:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3603:        return '';
                   3604:     }    
                   3605: 
                   3606:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3607:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3608: 	return '';
                   3609:     }
                   3610: 
                   3611:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3612: }
                   3613: 
                   3614: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3615: 
                   3616: sub expirespread {
                   3617:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3618:     my $cid=$env{'request.course.id'}; 
1.110     www      3619:     if ($cid) {
                   3620:        my $now=time;
                   3621:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3622:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3623:                             $env{'course.'.$cid.'.num'}.
1.110     www      3624: 	        	    ':nohist_expirationdates:'.
                   3625:                             &escape($key).'='.$now,
1.620     albertel 3626:                             $env{'course.'.$cid.'.home'})
1.110     www      3627:     }
                   3628:     return 'ok';
1.14      www      3629: }
                   3630: 
1.109     www      3631: # ----------------------------------------------------- Devalidate Spreadsheets
                   3632: 
                   3633: sub devalidate {
1.325     www      3634:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3635:     my $cid=$env{'request.course.id'}; 
1.109     www      3636:     if ($cid) {
1.391     matthew  3637:         # delete the stored spreadsheets for
                   3638:         # - the student level sheet of this user in course's homespace
                   3639:         # - the assessment level sheet for this resource 
                   3640:         #   for this user in user's homespace
1.553     albertel 3641: 	# - current conditional state info
1.325     www      3642: 	my $key=$uname.':'.$udom.':';
1.109     www      3643:         my $status=
1.299     matthew  3644: 	    &del('nohist_calculatedsheets',
1.391     matthew  3645: 		 [$key.'studentcalc:'],
1.620     albertel 3646: 		 $env{'course.'.$cid.'.domain'},
                   3647: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3648: 		.' '.
                   3649: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3650: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3651:         unless ($status eq 'ok ok') {
                   3652:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3653:                     $uname.' at '.$udom.' for '.
1.109     www      3654: 		    $symb.': '.$status);
1.133     albertel 3655:         }
1.553     albertel 3656: 	&delenv('user.state.'.$cid);
1.109     www      3657:     }
                   3658: }
                   3659: 
1.265     albertel 3660: sub get_scalar {
                   3661:     my ($string,$end) = @_;
                   3662:     my $value;
                   3663:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3664: 	$value = $1;
                   3665:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3666: 	$value = $1;
                   3667:     }
                   3668:     return &unescape($value);
                   3669: }
                   3670: 
                   3671: sub array2str {
                   3672:   my (@array) = @_;
                   3673:   my $result=&arrayref2str(\@array);
                   3674:   $result=~s/^__ARRAY_REF__//;
                   3675:   $result=~s/__END_ARRAY_REF__$//;
                   3676:   return $result;
                   3677: }
                   3678: 
1.204     albertel 3679: sub arrayref2str {
                   3680:   my ($arrayref) = @_;
1.265     albertel 3681:   my $result='__ARRAY_REF__';
1.204     albertel 3682:   foreach my $elem (@$arrayref) {
1.265     albertel 3683:     if(ref($elem) eq 'ARRAY') {
                   3684:       $result.=&arrayref2str($elem).'&';
                   3685:     } elsif(ref($elem) eq 'HASH') {
                   3686:       $result.=&hashref2str($elem).'&';
                   3687:     } elsif(ref($elem)) {
                   3688:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3689:     } else {
                   3690:       $result.=&escape($elem).'&';
                   3691:     }
                   3692:   }
                   3693:   $result=~s/\&$//;
1.265     albertel 3694:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3695:   return $result;
                   3696: }
                   3697: 
1.168     albertel 3698: sub hash2str {
1.204     albertel 3699:   my (%hash) = @_;
                   3700:   my $result=&hashref2str(\%hash);
1.265     albertel 3701:   $result=~s/^__HASH_REF__//;
                   3702:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3703:   return $result;
                   3704: }
                   3705: 
                   3706: sub hashref2str {
                   3707:   my ($hashref)=@_;
1.265     albertel 3708:   my $result='__HASH_REF__';
1.800     albertel 3709:   foreach my $key (sort(keys(%$hashref))) {
                   3710:     if (ref($key) eq 'ARRAY') {
                   3711:       $result.=&arrayref2str($key).'=';
                   3712:     } elsif (ref($key) eq 'HASH') {
                   3713:       $result.=&hashref2str($key).'=';
                   3714:     } elsif (ref($key)) {
1.265     albertel 3715:       $result.='=';
1.800     albertel 3716:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3717:     } else {
1.1056.4.32  raeburn  3718:         if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3719:     }
                   3720: 
1.800     albertel 3721:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3722:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3723:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3724:       $result.=&hashref2str($hashref->{$key}).'&';
                   3725:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3726:        $result.='&';
1.800     albertel 3727:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3728:     } else {
1.800     albertel 3729:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3730:     }
                   3731:   }
1.168     albertel 3732:   $result=~s/\&$//;
1.265     albertel 3733:   $result .= '__END_HASH_REF__';
1.168     albertel 3734:   return $result;
                   3735: }
                   3736: 
                   3737: sub str2hash {
1.265     albertel 3738:     my ($string)=@_;
                   3739:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3740:     return %$hash;
                   3741: }
                   3742: 
                   3743: sub str2hashref {
1.168     albertel 3744:   my ($string) = @_;
1.265     albertel 3745: 
                   3746:   my %hash;
                   3747: 
                   3748:   if($string !~ /^__HASH_REF__/) {
                   3749:       if (! ($string eq '' || !defined($string))) {
                   3750: 	  $hash{'error'}='Not hash reference';
                   3751:       }
                   3752:       return (\%hash, $string);
                   3753:   }
                   3754: 
                   3755:   $string =~ s/^__HASH_REF__//;
                   3756: 
                   3757:   while($string !~ /^__END_HASH_REF__/) {
                   3758:       #key
                   3759:       my $key='';
                   3760:       if($string =~ /^__HASH_REF__/) {
                   3761:           ($key, $string)=&str2hashref($string);
                   3762:           if(defined($key->{'error'})) {
                   3763:               $hash{'error'}='Bad data';
                   3764:               return (\%hash, $string);
                   3765:           }
                   3766:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3767:           ($key, $string)=&str2arrayref($string);
                   3768:           if($key->[0] eq 'Array reference error') {
                   3769:               $hash{'error'}='Bad data';
                   3770:               return (\%hash, $string);
                   3771:           }
                   3772:       } else {
                   3773:           $string =~ s/^(.*?)=//;
1.267     albertel 3774: 	  $key=&unescape($1);
1.265     albertel 3775:       }
                   3776:       $string =~ s/^=//;
                   3777: 
                   3778:       #value
                   3779:       my $value='';
                   3780:       if($string =~ /^__HASH_REF__/) {
                   3781:           ($value, $string)=&str2hashref($string);
                   3782:           if(defined($value->{'error'})) {
                   3783:               $hash{'error'}='Bad data';
                   3784:               return (\%hash, $string);
                   3785:           }
                   3786:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3787:           ($value, $string)=&str2arrayref($string);
                   3788:           if($value->[0] eq 'Array reference error') {
                   3789:               $hash{'error'}='Bad data';
                   3790:               return (\%hash, $string);
                   3791:           }
                   3792:       } else {
                   3793: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3794:       }
                   3795:       $string =~ s/^&//;
                   3796: 
                   3797:       $hash{$key}=$value;
1.204     albertel 3798:   }
1.265     albertel 3799: 
                   3800:   $string =~ s/^__END_HASH_REF__//;
                   3801: 
                   3802:   return (\%hash, $string);
1.204     albertel 3803: }
                   3804: 
                   3805: sub str2array {
1.265     albertel 3806:     my ($string)=@_;
                   3807:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3808:     return @$array;
                   3809: }
                   3810: 
                   3811: sub str2arrayref {
1.204     albertel 3812:   my ($string) = @_;
1.265     albertel 3813:   my @array;
                   3814: 
                   3815:   if($string !~ /^__ARRAY_REF__/) {
                   3816:       if (! ($string eq '' || !defined($string))) {
                   3817: 	  $array[0]='Array reference error';
                   3818:       }
                   3819:       return (\@array, $string);
                   3820:   }
                   3821: 
                   3822:   $string =~ s/^__ARRAY_REF__//;
                   3823: 
                   3824:   while($string !~ /^__END_ARRAY_REF__/) {
                   3825:       my $value='';
                   3826:       if($string =~ /^__HASH_REF__/) {
                   3827:           ($value, $string)=&str2hashref($string);
                   3828:           if(defined($value->{'error'})) {
                   3829:               $array[0] ='Array reference error';
                   3830:               return (\@array, $string);
                   3831:           }
                   3832:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3833:           ($value, $string)=&str2arrayref($string);
                   3834:           if($value->[0] eq 'Array reference error') {
                   3835:               $array[0] ='Array reference error';
                   3836:               return (\@array, $string);
                   3837:           }
                   3838:       } else {
                   3839: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3840:       }
                   3841:       $string =~ s/^&//;
                   3842: 
                   3843:       push(@array, $value);
1.191     harris41 3844:   }
1.265     albertel 3845: 
                   3846:   $string =~ s/^__END_ARRAY_REF__//;
                   3847: 
                   3848:   return (\@array, $string);
1.168     albertel 3849: }
                   3850: 
1.167     albertel 3851: # -------------------------------------------------------------------Temp Store
                   3852: 
1.168     albertel 3853: sub tmpreset {
                   3854:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3855:   if (!$symb) {
                   3856:     $symb=&symbread();
1.620     albertel 3857:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3858:   }
                   3859:   $symb=escape($symb);
                   3860: 
1.620     albertel 3861:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3862:   $namespace=~s/\//\_/g;
                   3863:   $namespace=~s/\W//g;
                   3864: 
1.620     albertel 3865:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3866:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3867:   if ($domain eq 'public' && $stuname eq 'public') {
                   3868:       $stuname=$ENV{'REMOTE_ADDR'};
                   3869:   }
1.168     albertel 3870:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3871:   my %hash;
                   3872:   if (tie(%hash,'GDBM_File',
                   3873: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3874: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3875:     foreach my $key (keys(%hash)) {
1.180     albertel 3876:       if ($key=~ /:$symb/) {
1.168     albertel 3877: 	delete($hash{$key});
                   3878:       }
                   3879:     }
                   3880:   }
                   3881: }
                   3882: 
1.167     albertel 3883: sub tmpstore {
1.168     albertel 3884:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3885: 
                   3886:   if (!$symb) {
                   3887:     $symb=&symbread();
1.620     albertel 3888:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3889:   }
                   3890:   $symb=escape($symb);
                   3891: 
                   3892:   if (!$namespace) {
                   3893:     # I don't think we would ever want to store this for a course.
                   3894:     # it seems this will only be used if we don't have a course.
1.620     albertel 3895:     #$namespace=$env{'request.course.id'};
1.168     albertel 3896:     #if (!$namespace) {
1.620     albertel 3897:       $namespace=$env{'request.state'};
1.168     albertel 3898:     #}
                   3899:   }
                   3900:   $namespace=~s/\//\_/g;
                   3901:   $namespace=~s/\W//g;
1.620     albertel 3902:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3903:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3904:   if ($domain eq 'public' && $stuname eq 'public') {
                   3905:       $stuname=$ENV{'REMOTE_ADDR'};
                   3906:   }
1.168     albertel 3907:   my $now=time;
                   3908:   my %hash;
                   3909:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3910:   if (tie(%hash,'GDBM_File',
                   3911: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3912: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3913:     $hash{"version:$symb"}++;
                   3914:     my $version=$hash{"version:$symb"};
                   3915:     my $allkeys=''; 
                   3916:     foreach my $key (keys(%$storehash)) {
                   3917:       $allkeys.=$key.':';
1.591     albertel 3918:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3919:     }
                   3920:     $hash{"$version:$symb:timestamp"}=$now;
                   3921:     $allkeys.='timestamp';
                   3922:     $hash{"$version:keys:$symb"}=$allkeys;
                   3923:     if (untie(%hash)) {
                   3924:       return 'ok';
                   3925:     } else {
                   3926:       return "error:$!";
                   3927:     }
                   3928:   } else {
                   3929:     return "error:$!";
                   3930:   }
                   3931: }
1.167     albertel 3932: 
1.168     albertel 3933: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3934: 
1.168     albertel 3935: sub tmprestore {
                   3936:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3937: 
1.168     albertel 3938:   if (!$symb) {
                   3939:     $symb=&symbread();
1.620     albertel 3940:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3941:   }
                   3942:   $symb=escape($symb);
                   3943: 
1.620     albertel 3944:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3945: 
1.620     albertel 3946:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3947:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3948:   if ($domain eq 'public' && $stuname eq 'public') {
                   3949:       $stuname=$ENV{'REMOTE_ADDR'};
                   3950:   }
1.168     albertel 3951:   my %returnhash;
                   3952:   $namespace=~s/\//\_/g;
                   3953:   $namespace=~s/\W//g;
                   3954:   my %hash;
                   3955:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3956:   if (tie(%hash,'GDBM_File',
                   3957: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3958: 	  &GDBM_READER(),0640)) {
1.168     albertel 3959:     my $version=$hash{"version:$symb"};
                   3960:     $returnhash{'version'}=$version;
                   3961:     my $scope;
                   3962:     for ($scope=1;$scope<=$version;$scope++) {
                   3963:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3964:       my @keys=split(/:/,$vkeys);
                   3965:       my $key;
                   3966:       $returnhash{"$scope:keys"}=$vkeys;
                   3967:       foreach $key (@keys) {
1.591     albertel 3968: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3969: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3970:       }
                   3971:     }
1.168     albertel 3972:     if (!(untie(%hash))) {
                   3973:       return "error:$!";
                   3974:     }
                   3975:   } else {
                   3976:     return "error:$!";
                   3977:   }
                   3978:   return %returnhash;
1.167     albertel 3979: }
                   3980: 
1.9       www      3981: # ----------------------------------------------------------------------- Store
                   3982: 
                   3983: sub store {
1.124     www      3984:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3985:     my $home='';
                   3986: 
1.168     albertel 3987:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3988: 
1.213     www      3989:     $symb=&symbclean($symb);
1.122     albertel 3990:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3991: 
1.620     albertel 3992:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3993:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3994: 
                   3995:     &devalidate($symb,$stuname,$domain);
1.109     www      3996: 
                   3997:     $symb=escape($symb);
1.187     www      3998:     if (!$namespace) { 
1.620     albertel 3999:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4000:           return ''; 
                   4001:        } 
                   4002:     }
1.620     albertel 4003:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4004: 
                   4005:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4006:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4007: 
1.12      www      4008:     my $namevalue='';
1.800     albertel 4009:     foreach my $key (keys(%$storehash)) {
                   4010:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4011:     }
1.12      www      4012:     $namevalue=~s/\&$//;
1.187     www      4013:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4014:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4015: }
                   4016: 
1.47      www      4017: # -------------------------------------------------------------- Critical Store
                   4018: 
                   4019: sub cstore {
1.124     www      4020:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4021:     my $home='';
                   4022: 
1.168     albertel 4023:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4024: 
1.213     www      4025:     $symb=&symbclean($symb);
1.122     albertel 4026:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4027: 
1.620     albertel 4028:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4029:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4030: 
                   4031:     &devalidate($symb,$stuname,$domain);
1.109     www      4032: 
                   4033:     $symb=escape($symb);
1.187     www      4034:     if (!$namespace) { 
1.620     albertel 4035:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4036:           return ''; 
                   4037:        } 
                   4038:     }
1.620     albertel 4039:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4040: 
                   4041:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4042:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4043: 
1.47      www      4044:     my $namevalue='';
1.800     albertel 4045:     foreach my $key (keys(%$storehash)) {
                   4046:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4047:     }
1.47      www      4048:     $namevalue=~s/\&$//;
1.187     www      4049:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4050:     return critical
                   4051:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4052: }
                   4053: 
1.9       www      4054: # --------------------------------------------------------------------- Restore
                   4055: 
                   4056: sub restore {
1.124     www      4057:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4058:     my $home='';
                   4059: 
1.168     albertel 4060:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4061: 
1.122     albertel 4062:     if (!$symb) {
                   4063:       unless ($symb=escape(&symbread())) { return ''; }
                   4064:     } else {
1.213     www      4065:       $symb=&escape(&symbclean($symb));
1.122     albertel 4066:     }
1.188     www      4067:     if (!$namespace) { 
1.620     albertel 4068:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4069:           return ''; 
                   4070:        } 
                   4071:     }
1.620     albertel 4072:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4073:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4074:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4075:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4076: 
1.12      www      4077:     my %returnhash=();
1.800     albertel 4078:     foreach my $line (split(/\&/,$answer)) {
                   4079: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4080:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4081:     }
1.75      www      4082:     my $version;
                   4083:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4084:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4085:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4086:        }
1.75      www      4087:     }
1.13      www      4088:     return %returnhash;
1.34      www      4089: }
                   4090: 
                   4091: # ---------------------------------------------------------- Course Description
                   4092: 
                   4093: sub coursedescription {
1.731     albertel 4094:     my ($courseid,$args)=@_;
1.34      www      4095:     $courseid=~s/^\///;
1.49      www      4096:     $courseid=~s/\_/\//g;
1.34      www      4097:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4098:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4099:     my $normalid=$cdomain.'_'.$cnum;
                   4100:     # need to always cache even if we get errors otherwise we keep 
                   4101:     # trying and trying and trying to get the course description.
                   4102:     my %envhash=();
                   4103:     my %returnhash=();
1.731     albertel 4104:     
                   4105:     my $expiretime=600;
                   4106:     if ($env{'request.course.id'} eq $normalid) {
                   4107: 	$expiretime=120;
                   4108:     }
                   4109: 
                   4110:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4111:     if (!$args->{'freshen_cache'}
                   4112: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4113: 	foreach my $key (keys(%env)) {
                   4114: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4115: 	    my ($setting) = $1;
                   4116: 	    $returnhash{$setting} = $env{$key};
                   4117: 	}
                   4118: 	return %returnhash;
                   4119:     }
                   4120: 
                   4121:     # get the data agin
                   4122:     if (!$args->{'one_time'}) {
                   4123: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4124:     }
1.811     albertel 4125: 
1.34      www      4126:     if ($chome ne 'no_host') {
1.302     albertel 4127:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4128:        if (!exists($returnhash{'con_lost'})) {
                   4129:            $returnhash{'home'}= $chome;
                   4130: 	   $returnhash{'domain'} = $cdomain;
                   4131: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4132:            if (!defined($returnhash{'type'})) {
                   4133:                $returnhash{'type'} = 'Course';
                   4134:            }
1.130     albertel 4135:            while (my ($name,$value) = each %returnhash) {
1.53      www      4136:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4137:            }
1.270     www      4138:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      4139:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 4140: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      4141:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4142:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4143:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4144:        }
                   4145:     }
1.731     albertel 4146:     if (!$args->{'one_time'}) {
1.949     raeburn  4147: 	&appenv(\%envhash);
1.731     albertel 4148:     }
1.302     albertel 4149:     return %returnhash;
1.461     www      4150: }
                   4151: 
1.1056.4.5  raeburn  4152: sub update_released_required {
                   4153:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4154:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4155:         $cid = $env{'request.course.id'};
                   4156:         $cdom = $env{'course.'.$cid.'.domain'};
                   4157:         $cnum = $env{'course.'.$cid.'.num'};
                   4158:         $chome = $env{'course.'.$cid.'.home'};
                   4159:     }
                   4160:     if ($needsrelease) {
                   4161:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4162:         my $needsupdate;
                   4163:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4164:             $needsupdate = 1;
                   4165:         } else {
                   4166:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4167:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4168:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4169:                 $needsupdate = 1;
                   4170:             }
                   4171:         }
                   4172:         if ($needsupdate) {
                   4173:             my %needshash = (
                   4174:                              'internal.releaserequired' => $needsrelease,
                   4175:                             );
                   4176:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4177:             if ($putresult eq 'ok') {
                   4178:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4179:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4180:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4181:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4182:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4183:                 }
                   4184:             }
                   4185:         }
                   4186:     }
                   4187:     return;
                   4188: }
                   4189: 
1.461     www      4190: # -------------------------------------------------See if a user is privileged
                   4191: 
                   4192: sub privileged {
                   4193:     my ($username,$domain)=@_;
                   4194:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4195: 			&homeserver($username,$domain));
1.1033    raeburn  4196:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4197:         ($rolesdump =~ /^error:/)) {
                   4198:         return 0;
                   4199:     }
1.461     www      4200:     my $now=time;
                   4201:     if ($rolesdump ne '') {
1.800     albertel 4202:         foreach my $entry (split(/&/,$rolesdump)) {
                   4203: 	    if ($entry!~/^rolesdef_/) {
                   4204: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4205: 		$area=~s/\_\w\w$//;
                   4206: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4207: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4208: 		    my $active=1;
                   4209: 		    if ($tend) {
                   4210: 			if ($tend<$now) { $active=0; }
                   4211: 		    }
                   4212: 		    if ($tstart) {
                   4213: 			if ($tstart>$now) { $active=0; }
                   4214: 		    }
                   4215: 		    if ($active) { return 1; }
                   4216: 		}
                   4217: 	    }
                   4218: 	}
                   4219:     }
                   4220:     return 0;
1.9       www      4221: }
1.1       albertel 4222: 
1.103     harris41 4223: # -------------------------------------------------------- Get user privileges
1.11      www      4224: 
                   4225: sub rolesinit {
                   4226:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4227:     my $now=time;
                   4228:     my %userroles = ('user.login.time' => $now);
1.1056.4.10  raeburn  4229:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3  raeburn  4230:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4231:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1056.4.3  raeburn  4232:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4233:         return \%userroles;
                   4234:     }
1.11      www      4235:     my %allroles=();
1.678     raeburn  4236:     my %allgroups=();   
                   4237:     my $group_privs;
1.11      www      4238: 
                   4239:     if ($rolesdump ne '') {
1.800     albertel 4240:         foreach my $entry (split(/&/,$rolesdump)) {
                   4241: 	  if ($entry!~/^rolesdef_/) {
                   4242:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4243: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4244:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4245: 	    if ($role=~/^cr/) { 
1.807     albertel 4246: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4247: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4248: 		    ($tend,$tstart)=split('_',$trest);
                   4249: 		} else {
                   4250: 		    $trole=$role;
                   4251: 		}
1.678     raeburn  4252:             } elsif ($role =~ m|^gr/|) {
                   4253:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   4254:                 ($trole,$group_privs) = split(/\//,$trole);
                   4255:                 $group_privs = &unescape($group_privs);
1.587     albertel 4256: 	    } else {
                   4257: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4258: 	    }
1.743     albertel 4259: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4260: 					 $username);
                   4261: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4262:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4263:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4264:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4265: 		my $spec=$trole.'.'.$area;
                   4266: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4267: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4268:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4269:                 } elsif ($trole eq 'gr') {
                   4270:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4271: 		} else {
1.567     raeburn  4272:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4273: 		}
1.12      www      4274:             }
1.662     raeburn  4275:           }
1.191     harris41 4276:         }
1.743     albertel 4277:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4278:         $userroles{'user.adv'}    = $adv;
                   4279: 	$userroles{'user.author'} = $author;
1.620     albertel 4280:         $env{'user.adv'}=$adv;
1.11      www      4281:     }
1.743     albertel 4282:     return \%userroles;  
1.11      www      4283: }
                   4284: 
1.567     raeburn  4285: sub set_arearole {
                   4286:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4287: # log the associated role with the area
                   4288:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4289:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4290: }
                   4291: 
                   4292: sub custom_roleprivs {
                   4293:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4294:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4295:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4296:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4297:         my ($rdummy,$roledef)=
                   4298:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4299:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4300:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4301:             if (defined($syspriv)) {
1.1043    raeburn  4302:                 if ($trest =~ /^$match_community$/) {
                   4303:                     $syspriv =~ s/bre\&S//; 
                   4304:                 }
1.567     raeburn  4305:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4306:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4307:             }
                   4308:             if ($tdomain ne '') {
                   4309:                 if (defined($dompriv)) {
                   4310:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4311:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4312:                 }
                   4313:                 if (($trest ne '') && (defined($coursepriv))) {
                   4314:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4315:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4316:                 }
                   4317:             }
                   4318:         }
                   4319:     }
                   4320: }
                   4321: 
1.678     raeburn  4322: sub group_roleprivs {
                   4323:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4324:     my $access = 1;
                   4325:     my $now = time;
                   4326:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4327:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4328:     if ($access) {
1.811     albertel 4329:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4330:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4331:     }
                   4332: }
1.567     raeburn  4333: 
                   4334: sub standard_roleprivs {
                   4335:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4336:     if (defined($pr{$trole.':s'})) {
                   4337:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4338:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4339:     }
                   4340:     if ($tdomain ne '') {
                   4341:         if (defined($pr{$trole.':d'})) {
                   4342:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4343:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4344:         }
                   4345:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4346:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4347:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4348:         }
                   4349:     }
                   4350: }
                   4351: 
                   4352: sub set_userprivs {
1.1056.4.2  raeburn  4353:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4354:     my $author=0;
                   4355:     my $adv=0;
1.678     raeburn  4356:     my %grouproles = ();
                   4357:     if (keys(%{$allgroups}) > 0) {
1.1056.4.2  raeburn  4358:         my @groupkeys;
1.1000    raeburn  4359:         foreach my $role (keys(%{$allroles})) {
1.1056.4.2  raeburn  4360:             push(@groupkeys,$role);
                   4361:         }
                   4362:         if (ref($groups_roles) eq 'HASH') {
                   4363:             foreach my $key (keys(%{$groups_roles})) {
                   4364:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4365:                     push(@groupkeys,$key);
                   4366:                 }
                   4367:             }
                   4368:         }
                   4369:         if (@groupkeys > 0) {
                   4370:             foreach my $role (@groupkeys) {
                   4371:                 my ($trole,$area,$sec,$extendedarea);
                   4372:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4373:                     $trole = $1;
                   4374:                     $area = $2;
                   4375:                     $sec = $3;
                   4376:                     $extendedarea = $area.$sec;
                   4377:                     if (exists($$allgroups{$area})) {
                   4378:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4379:                             my $spec = $trole.'.'.$extendedarea;
                   4380:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4381:                                                 $$allgroups{$area}{$group};
1.1056.4.2  raeburn  4382:                         }
1.678     raeburn  4383:                     }
                   4384:                 }
                   4385:             }
                   4386:         }
                   4387:     }
1.800     albertel 4388:     foreach my $group (keys(%grouproles)) {
                   4389:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4390:     }
1.800     albertel 4391:     foreach my $role (keys(%{$allroles})) {
                   4392:         my %thesepriv;
1.941     raeburn  4393:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4394:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4395:             if ($item ne '') {
                   4396:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4397:                 if ($restrictions eq '') {
                   4398:                     $thesepriv{$privilege}='F';
                   4399:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4400:                     $thesepriv{$privilege}.=$restrictions;
                   4401:                 }
                   4402:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4403:             }
                   4404:         }
                   4405:         my $thesestr='';
1.800     albertel 4406:         foreach my $priv (keys(%thesepriv)) {
                   4407: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4408: 	}
                   4409:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4410:     }
                   4411:     return ($author,$adv);
                   4412: }
                   4413: 
1.994     raeburn  4414: sub role_status {
1.1002    raeburn  4415:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4416:     my @pwhere = ();
                   4417:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4418:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4419:         unless (!defined($$role) || $$role eq '') {
                   4420:             $$where=join('.',@pwhere);
                   4421:             $$trolecode=$$role.'.'.$$where;
                   4422:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4423:             $$tstatus='is';
                   4424:             if ($$tstart && $$tstart>$then) {
                   4425:                 $$tstatus='future';
1.1034    raeburn  4426:                 if ($$tstart<$now) {
                   4427:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4428:                         if (($$where ne '') && ($$role ne '')) {
1.1056.4.2  raeburn  4429:                             my (%allroles,%allgroups,$group_privs,
                   4430:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4431:                             my %userroles = (
                   4432:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4433:                             );
1.1056.4.2  raeburn  4434:                             @rolecodes = ('cm');
1.1002    raeburn  4435:                             my $spec=$$role.'.'.$$where;
                   4436:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4437:                             if ($$role =~ /^cr\//) {
                   4438:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2  raeburn  4439:                                 push(@rolecodes,'cr');
1.1002    raeburn  4440:                             } elsif ($$role eq 'gr') {
1.1056.4.2  raeburn  4441:                                 push(@rolecodes,$$role);
1.1002    raeburn  4442:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4443:                                                     $env{'user.name'});
1.1056.4.2  raeburn  4444:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4445:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4446:                                 $group_privs = &unescape($group_privs);
                   4447:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2  raeburn  4448:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
                   4449:                                 if (keys(%course_roles) > 0) {
                   4450:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
                   4451:                                     if ($tdomain ne '' && $tnum ne '') {
                   4452:                                         foreach my $key (keys(%course_roles)) {
                   4453:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
                   4454:                                                 my $crsrole = $1;
                   4455:                                                 my $crssec = $2;
                   4456:                                                 if ($crsrole =~ /^cr/) {
                   4457:                                                     unless (grep(/^cr$/,@rolecodes)) {
                   4458:                                                         push(@rolecodes,'cr');
                   4459:                                                     }
                   4460:                                                 } else {
                   4461:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
                   4462:                                                         push(@rolecodes,$crsrole);
                   4463:                                                     }
                   4464:                                                 }
                   4465:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
                   4466:                                                 if ($crssec ne '') {
                   4467:                                                     $rolekey .= '/'.$crssec;
                   4468:                                                 }
                   4469:                                                 $rolekey .= './';
                   4470:                                                 $groups_roles{$rolekey} = \@rolecodes;
                   4471:                                             }
                   4472:                                         }
                   4473:                                     }
                   4474:                                 }
1.1002    raeburn  4475:                             } else {
1.1056.4.2  raeburn  4476:                                 push(@rolecodes,$$role);
1.1002    raeburn  4477:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4478:                             }
1.1056.4.2  raeburn  4479:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4480:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4481:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4482:                         }
                   4483:                     }
1.1034    raeburn  4484:                     $$tstatus = 'is';
1.1002    raeburn  4485:                 }
1.994     raeburn  4486:             }
                   4487:             if ($$tend) {
                   4488:                 if ($$tend<$then) {
                   4489:                     $$tstatus='expired';
                   4490:                 } elsif ($$tend<$now) {
                   4491:                     $$tstatus='will_not';
                   4492:                 }
                   4493:             }
                   4494:         }
                   4495:     }
                   4496: }
                   4497: 
                   4498: sub check_adhoc_privs {
1.1056.4.12  raeburn  4499:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4500:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4501:     if ($env{$cckey}) {
                   4502:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4503:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4504:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12  raeburn  4505:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4506:         }
                   4507:     } else {
1.1056.4.12  raeburn  4508:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4509:     }
                   4510: }
                   4511: 
                   4512: sub set_adhoc_privileges {
                   4513: # role can be cc or ca
1.1056.4.12  raeburn  4514:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4515:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4516:     my $spec = $role.'.'.$area;
                   4517:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4518:                                   $env{'user.name'});
                   4519:     my %ccrole = ();
                   4520:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4521:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4522:     &appenv(\%userroles,[$role,'cm']);
                   4523:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12  raeburn  4524:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4525:         &appenv( {'request.role'        => $spec,
                   4526:                   'request.role.domain' => $dcdom,
                   4527:                   'request.course.sec'  => ''
                   4528:                  }
                   4529:                );
                   4530:         my $tadv=0;
                   4531:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4532:         &appenv({'request.role.adv'    => $tadv});
                   4533:     }
1.994     raeburn  4534: }
                   4535: 
1.12      www      4536: # --------------------------------------------------------------- get interface
                   4537: 
                   4538: sub get {
1.131     albertel 4539:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4540:    my $items='';
1.800     albertel 4541:    foreach my $item (@$storearr) {
                   4542:        $items.=&escape($item).'&';
1.191     harris41 4543:    }
1.12      www      4544:    $items=~s/\&$//;
1.620     albertel 4545:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4546:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4547:    my $uhome=&homeserver($uname,$udomain);
                   4548: 
1.133     albertel 4549:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4550:    my @pairs=split(/\&/,$rep);
1.273     albertel 4551:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4552:      return @pairs;
                   4553:    }
1.15      www      4554:    my %returnhash=();
1.42      www      4555:    my $i=0;
1.800     albertel 4556:    foreach my $item (@$storearr) {
                   4557:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4558:       $i++;
1.191     harris41 4559:    }
1.15      www      4560:    return %returnhash;
1.27      www      4561: }
                   4562: 
                   4563: # --------------------------------------------------------------- del interface
                   4564: 
                   4565: sub del {
1.133     albertel 4566:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4567:    my $items='';
1.800     albertel 4568:    foreach my $item (@$storearr) {
                   4569:        $items.=&escape($item).'&';
1.191     harris41 4570:    }
1.984     neumanie 4571: 
1.27      www      4572:    $items=~s/\&$//;
1.620     albertel 4573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4574:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4575:    my $uhome=&homeserver($uname,$udomain);
                   4576:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4577: }
                   4578: 
                   4579: # -------------------------------------------------------------- dump interface
                   4580: 
                   4581: sub dump {
1.1056.4.10  raeburn  4582:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4583:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4584:     if (!$uname) { $uname=$env{'user.name'}; }
                   4585:     my $uhome=&homeserver($uname,$udomain);
                   4586:     if ($regexp) {
                   4587: 	$regexp=&escape($regexp);
                   4588:     } else {
                   4589: 	$regexp='.';
                   4590:     }
1.1056.4.10  raeburn  4591:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4592:     my @pairs=split(/\&/,$rep);
                   4593:     my %returnhash=();
                   4594:     foreach my $item (@pairs) {
                   4595: 	my ($key,$value)=split(/=/,$item,2);
                   4596: 	$key = &unescape($key);
                   4597: 	next if ($key =~ /^error: 2 /);
                   4598: 	$returnhash{$key}=&thaw_unescape($value);
                   4599:     }
                   4600:     return %returnhash;
1.407     www      4601: }
                   4602: 
1.717     albertel 4603: # --------------------------------------------------------- dumpstore interface
                   4604: 
                   4605: sub dumpstore {
                   4606:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4607:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4608:    if (!$uname) { $uname=$env{'user.name'}; }
                   4609:    my $uhome=&homeserver($uname,$udomain);
                   4610:    if ($regexp) {
                   4611:        $regexp=&escape($regexp);
                   4612:    } else {
                   4613:        $regexp='.';
                   4614:    }
                   4615:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4616:    my @pairs=split(/\&/,$rep);
                   4617:    my %returnhash=();
                   4618:    foreach my $item (@pairs) {
                   4619:        my ($key,$value)=split(/=/,$item,2);
                   4620:        next if ($key =~ /^error: 2 /);
                   4621:        $returnhash{$key}=&thaw_unescape($value);
                   4622:    }
                   4623:    return %returnhash;
1.717     albertel 4624: }
                   4625: 
1.407     www      4626: # -------------------------------------------------------------- keys interface
                   4627: 
                   4628: sub getkeys {
                   4629:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4630:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4631:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4632:    my $uhome=&homeserver($uname,$udomain);
                   4633:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4634:    my @keyarray=();
1.800     albertel 4635:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4636:       next if ($key =~ /^error: 2 /);
1.800     albertel 4637:       push(@keyarray,&unescape($key));
1.407     www      4638:    }
                   4639:    return @keyarray;
1.318     matthew  4640: }
                   4641: 
1.319     matthew  4642: # --------------------------------------------------------------- currentdump
                   4643: sub currentdump {
1.328     matthew  4644:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4645:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4646:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4647:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4648:    my $uhome = &homeserver($sname,$sdom);
                   4649:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4650:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4651:    #
1.318     matthew  4652:    my %returnhash=();
1.319     matthew  4653:    #
                   4654:    if ($rep eq "unknown_cmd") { 
                   4655:        # an old lond will not know currentdump
                   4656:        # Do a dump and make it look like a currentdump
1.822     albertel 4657:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4658:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4659:        my %hash = @tmp;
                   4660:        @tmp=();
1.424     matthew  4661:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4662:    } else {
                   4663:        my @pairs=split(/\&/,$rep);
1.800     albertel 4664:        foreach my $pair (@pairs) {
                   4665:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4666:            my ($symb,$param) = split(/:/,$key);
                   4667:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4668:                                                         &thaw_unescape($value);
1.319     matthew  4669:        }
1.191     harris41 4670:    }
1.12      www      4671:    return %returnhash;
1.424     matthew  4672: }
                   4673: 
                   4674: sub convert_dump_to_currentdump{
                   4675:     my %hash = %{shift()};
                   4676:     my %returnhash;
                   4677:     # Code ripped from lond, essentially.  The only difference
                   4678:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4679:     # we might run in to problems with parameter names =~ /^v\./
                   4680:     while (my ($key,$value) = each(%hash)) {
                   4681:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4682: 	$symb  = &unescape($symb);
                   4683: 	$param = &unescape($param);
1.424     matthew  4684:         next if ($v eq 'version' || $symb eq 'keys');
                   4685:         next if (exists($returnhash{$symb}) &&
                   4686:                  exists($returnhash{$symb}->{$param}) &&
                   4687:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4688:         $returnhash{$symb}->{$param}=$value;
                   4689:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4690:     }
                   4691:     #
                   4692:     # Remove all of the keys in the hashes which keep track of
                   4693:     # the version of the parameter.
                   4694:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4695:         # use a foreach because we are going to delete from the hash.
                   4696:         foreach my $key (keys(%$param_hash)) {
                   4697:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4698:         }
                   4699:     }
                   4700:     return \%returnhash;
1.12      www      4701: }
                   4702: 
1.627     albertel 4703: # ------------------------------------------------------ critical inc interface
                   4704: 
                   4705: sub cinc {
                   4706:     return &inc(@_,'critical');
                   4707: }
                   4708: 
1.449     matthew  4709: # --------------------------------------------------------------- inc interface
                   4710: 
                   4711: sub inc {
1.627     albertel 4712:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4713:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4714:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4715:     my $uhome=&homeserver($uname,$udomain);
                   4716:     my $items='';
                   4717:     if (! ref($store)) {
                   4718:         # got a single value, so use that instead
                   4719:         $items = &escape($store).'=&';
                   4720:     } elsif (ref($store) eq 'SCALAR') {
                   4721:         $items = &escape($$store).'=&';        
                   4722:     } elsif (ref($store) eq 'ARRAY') {
                   4723:         $items = join('=&',map {&escape($_);} @{$store});
                   4724:     } elsif (ref($store) eq 'HASH') {
                   4725:         while (my($key,$value) = each(%{$store})) {
                   4726:             $items.= &escape($key).'='.&escape($value).'&';
                   4727:         }
                   4728:     }
                   4729:     $items=~s/\&$//;
1.627     albertel 4730:     if ($critical) {
                   4731: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4732:     } else {
                   4733: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4734:     }
1.449     matthew  4735: }
                   4736: 
1.12      www      4737: # --------------------------------------------------------------- put interface
                   4738: 
                   4739: sub put {
1.134     albertel 4740:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4742:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4743:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4744:    my $items='';
1.800     albertel 4745:    foreach my $item (keys(%$storehash)) {
                   4746:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4747:    }
1.12      www      4748:    $items=~s/\&$//;
1.134     albertel 4749:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4750: }
                   4751: 
1.631     albertel 4752: # ------------------------------------------------------------ newput interface
                   4753: 
                   4754: sub newput {
                   4755:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4756:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4757:    if (!$uname) { $uname=$env{'user.name'}; }
                   4758:    my $uhome=&homeserver($uname,$udomain);
                   4759:    my $items='';
                   4760:    foreach my $key (keys(%$storehash)) {
                   4761:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4762:    }
                   4763:    $items=~s/\&$//;
                   4764:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4765: }
                   4766: 
                   4767: # ---------------------------------------------------------  putstore interface
                   4768: 
1.524     raeburn  4769: sub putstore {
1.715     albertel 4770:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4771:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4772:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4773:    my $uhome=&homeserver($uname,$udomain);
                   4774:    my $items='';
1.715     albertel 4775:    foreach my $key (keys(%$storehash)) {
                   4776:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4777:    }
1.715     albertel 4778:    $items=~s/\&$//;
1.716     albertel 4779:    my $esc_symb=&escape($symb);
                   4780:    my $esc_v=&escape($version);
1.715     albertel 4781:    my $reply =
1.716     albertel 4782:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4783: 	      $uhome);
                   4784:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4785:        # gfall back to way things use to be done
1.715     albertel 4786:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4787: 			    $uname);
1.524     raeburn  4788:    }
1.715     albertel 4789:    return $reply;
                   4790: }
                   4791: 
                   4792: sub old_putstore {
1.716     albertel 4793:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4794:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4795:     if (!$uname) { $uname=$env{'user.name'}; }
                   4796:     my $uhome=&homeserver($uname,$udomain);
                   4797:     my %newstorehash;
1.800     albertel 4798:     foreach my $item (keys(%$storehash)) {
                   4799: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4800: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4801:     }
                   4802:     my $items='';
                   4803:     my %allitems = ();
1.800     albertel 4804:     foreach my $item (keys(%newstorehash)) {
                   4805: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4806: 	    my $key = $1.':keys:'.$2;
                   4807: 	    $allitems{$key} .= $3.':';
                   4808: 	}
1.800     albertel 4809: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4810:     }
1.800     albertel 4811:     foreach my $item (keys(%allitems)) {
                   4812: 	$allitems{$item} =~ s/\:$//;
                   4813: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4814:     }
                   4815:     $items=~s/\&$//;
                   4816:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4817: }
                   4818: 
1.47      www      4819: # ------------------------------------------------------ critical put interface
                   4820: 
                   4821: sub cput {
1.134     albertel 4822:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4823:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4824:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4825:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4826:    my $items='';
1.800     albertel 4827:    foreach my $item (keys(%$storehash)) {
                   4828:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4829:    }
1.47      www      4830:    $items=~s/\&$//;
1.134     albertel 4831:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4832: }
                   4833: 
                   4834: # -------------------------------------------------------------- eget interface
                   4835: 
                   4836: sub eget {
1.133     albertel 4837:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4838:    my $items='';
1.800     albertel 4839:    foreach my $item (@$storearr) {
                   4840:        $items.=&escape($item).'&';
1.191     harris41 4841:    }
1.12      www      4842:    $items=~s/\&$//;
1.620     albertel 4843:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4844:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4845:    my $uhome=&homeserver($uname,$udomain);
                   4846:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4847:    my @pairs=split(/\&/,$rep);
                   4848:    my %returnhash=();
1.42      www      4849:    my $i=0;
1.800     albertel 4850:    foreach my $item (@$storearr) {
                   4851:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4852:       $i++;
1.191     harris41 4853:    }
1.12      www      4854:    return %returnhash;
                   4855: }
                   4856: 
1.667     albertel 4857: # ------------------------------------------------------------ tmpput interface
                   4858: sub tmpput {
1.802     raeburn  4859:     my ($storehash,$server,$context)=@_;
1.667     albertel 4860:     my $items='';
1.800     albertel 4861:     foreach my $item (keys(%$storehash)) {
                   4862: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4863:     }
                   4864:     $items=~s/\&$//;
1.802     raeburn  4865:     if (defined($context)) {
                   4866:         $items .= ':'.&escape($context);
                   4867:     }
1.667     albertel 4868:     return &reply("tmpput:$items",$server);
                   4869: }
                   4870: 
                   4871: # ------------------------------------------------------------ tmpget interface
                   4872: sub tmpget {
1.688     albertel 4873:     my ($token,$server)=@_;
                   4874:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4875:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4876:     my %returnhash;
                   4877:     foreach my $item (split(/\&/,$rep)) {
                   4878: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4879:         next if ($key =~ /^error: 2 /);
1.667     albertel 4880: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4881:     }
                   4882:     return %returnhash;
                   4883: }
                   4884: 
1.688     albertel 4885: # ------------------------------------------------------------ tmpget interface
                   4886: sub tmpdel {
                   4887:     my ($token,$server)=@_;
                   4888:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4889:     return &reply("tmpdel:$token",$server);
                   4890: }
                   4891: 
1.765     albertel 4892: # -------------------------------------------------- portfolio access checking
                   4893: 
                   4894: sub portfolio_access {
1.766     albertel 4895:     my ($requrl) = @_;
1.765     albertel 4896:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4897:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4898:     if ($result) {
                   4899:         my %setters;
                   4900:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4901:             my ($startblock,$endblock) =
                   4902:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4903:             if ($startblock && $endblock) {
                   4904:                 return 'B';
                   4905:             }
                   4906:         } else {
                   4907:             my ($startblock,$endblock) =
                   4908:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4909:             if ($startblock && $endblock) {
                   4910:                 return 'B';
                   4911:             }
                   4912:         }
                   4913:     }
1.765     albertel 4914:     if ($result eq 'ok') {
1.766     albertel 4915:        return 'F';
1.765     albertel 4916:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4917:        return 'A';
1.765     albertel 4918:     }
1.766     albertel 4919:     return '';
1.765     albertel 4920: }
                   4921: 
                   4922: sub get_portfolio_access {
1.767     albertel 4923:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4924: 
                   4925:     if (!ref($access_hash)) {
                   4926: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4927: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4928: 						   $file_name);
                   4929: 	$access_hash = $access_controls{$file_name};
                   4930:     }
                   4931: 
1.765     albertel 4932:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4933:     my $now = time;
                   4934:     if (ref($access_hash) eq 'HASH') {
                   4935:         foreach my $key (keys(%{$access_hash})) {
                   4936:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4937:             if ($start > $now) {
                   4938:                 next;
                   4939:             }
                   4940:             if ($end && $end<$now) {
                   4941:                 next;
                   4942:             }
                   4943:             if ($scope eq 'public') {
                   4944:                 $public = $key;
                   4945:                 last;
                   4946:             } elsif ($scope eq 'guest') {
                   4947:                 $guest = $key;
                   4948:             } elsif ($scope eq 'domains') {
                   4949:                 push(@domains,$key);
                   4950:             } elsif ($scope eq 'users') {
                   4951:                 push(@users,$key);
                   4952:             } elsif ($scope eq 'course') {
                   4953:                 push(@courses,$key);
                   4954:             } elsif ($scope eq 'group') {
                   4955:                 push(@groups,$key);
                   4956:             }
                   4957:         }
                   4958:         if ($public) {
                   4959:             return 'ok';
                   4960:         }
                   4961:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4962:             if ($guest) {
                   4963:                 return $guest;
                   4964:             }
                   4965:         } else {
                   4966:             if (@domains > 0) {
                   4967:                 foreach my $domkey (@domains) {
                   4968:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4969:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4970:                             return 'ok';
                   4971:                         }
                   4972:                     }
                   4973:                 }
                   4974:             }
                   4975:             if (@users > 0) {
                   4976:                 foreach my $userkey (@users) {
1.865     raeburn  4977:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4978:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4979:                             if (ref($item) eq 'HASH') {
                   4980:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4981:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4982:                                     return 'ok';
                   4983:                                 }
                   4984:                             }
                   4985:                         }
                   4986:                     } 
1.765     albertel 4987:                 }
                   4988:             }
                   4989:             my %roleshash;
                   4990:             my @courses_and_groups = @courses;
                   4991:             push(@courses_and_groups,@groups); 
                   4992:             if (@courses_and_groups > 0) {
                   4993:                 my (%allgroups,%allroles); 
                   4994:                 my ($start,$end,$role,$sec,$group);
                   4995:                 foreach my $envkey (%env) {
1.1056.4.1  raeburn  4996:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4997:                         my $cid = $2.'_'.$3; 
                   4998:                         if ($1 eq 'gr') {
                   4999:                             $group = $4;
                   5000:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5001:                         } else {
                   5002:                             if ($4 eq '') {
                   5003:                                 $sec = 'none';
                   5004:                             } else {
                   5005:                                 $sec = $4;
                   5006:                             }
                   5007:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5008:                         }
1.811     albertel 5009:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5010:                         my $cid = $2.'_'.$3;
                   5011:                         if ($4 eq '') {
                   5012:                             $sec = 'none';
                   5013:                         } else {
                   5014:                             $sec = $4;
                   5015:                         }
                   5016:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5017:                     }
                   5018:                 }
                   5019:                 if (keys(%allroles) == 0) {
                   5020:                     return;
                   5021:                 }
                   5022:                 foreach my $key (@courses_and_groups) {
                   5023:                     my %content = %{$$access_hash{$key}};
                   5024:                     my $cnum = $content{'number'};
                   5025:                     my $cdom = $content{'domain'};
                   5026:                     my $cid = $cdom.'_'.$cnum;
                   5027:                     if (!exists($allroles{$cid})) {
                   5028:                         next;
                   5029:                     }    
                   5030:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5031:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5032:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5033:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5034:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5035:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5036:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5037:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5038:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5039:                                         if (grep/^all$/,@sections) {
                   5040:                                             return 'ok';
                   5041:                                         } else {
                   5042:                                             if (grep/^$sec$/,@sections) {
                   5043:                                                 return 'ok';
                   5044:                                             }
                   5045:                                         }
                   5046:                                     }
                   5047:                                 }
                   5048:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5049:                                     if (grep/^none$/,@groups) {
                   5050:                                         return 'ok';
                   5051:                                     }
                   5052:                                 } else {
                   5053:                                     if (grep/^all$/,@groups) {
                   5054:                                         return 'ok';
                   5055:                                     } 
                   5056:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5057:                                         if (grep/^$group$/,@groups) {
                   5058:                                             return 'ok';
                   5059:                                         }
                   5060:                                     }
                   5061:                                 } 
                   5062:                             }
                   5063:                         }
                   5064:                     }
                   5065:                 }
                   5066:             }
                   5067:             if ($guest) {
                   5068:                 return $guest;
                   5069:             }
                   5070:         }
                   5071:     }
                   5072:     return;
                   5073: }
                   5074: 
                   5075: sub course_group_datechecker {
                   5076:     my ($dates,$now,$status) = @_;
                   5077:     my ($start,$end) = split(/\./,$dates);
                   5078:     if (!$start && !$end) {
                   5079:         return 'ok';
                   5080:     }
                   5081:     if (grep/^active$/,@{$status}) {
                   5082:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5083:             return 'ok';
                   5084:         }
                   5085:     }
                   5086:     if (grep/^previous$/,@{$status}) {
                   5087:         if ($end > $now ) {
                   5088:             return 'ok';
                   5089:         }
                   5090:     }
                   5091:     if (grep/^future$/,@{$status}) {
                   5092:         if ($start > $now) {
                   5093:             return 'ok';
                   5094:         }
                   5095:     }
                   5096:     return; 
                   5097: }
                   5098: 
                   5099: sub parse_portfolio_url {
                   5100:     my ($url) = @_;
                   5101: 
                   5102:     my ($type,$udom,$unum,$group,$file_name);
                   5103:     
1.823     albertel 5104:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5105: 	$type = 1;
                   5106:         $udom = $1;
                   5107:         $unum = $2;
                   5108:         $file_name = $3;
1.823     albertel 5109:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5110: 	$type = 2;
                   5111:         $udom = $1;
                   5112:         $unum = $2;
                   5113:         $group = $3;
                   5114:         $file_name = $3.'/'.$4;
                   5115:     }
                   5116:     if (wantarray) {
                   5117: 	return ($type,$udom,$unum,$file_name,$group);
                   5118:     }
                   5119:     return $type;
                   5120: }
                   5121: 
                   5122: sub is_portfolio_url {
                   5123:     my ($url) = @_;
                   5124:     return scalar(&parse_portfolio_url($url));
                   5125: }
                   5126: 
1.798     raeburn  5127: sub is_portfolio_file {
                   5128:     my ($file) = @_;
1.820     raeburn  5129:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5130:         return 1;
                   5131:     }
                   5132:     return;
                   5133: }
                   5134: 
1.976     raeburn  5135: sub usertools_access {
1.1056.4.9  raeburn  5136:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985     raeburn  5137:     my ($access,%tools);
                   5138:     if ($context eq '') {
                   5139:         $context = 'tools';
                   5140:     }
                   5141:     if ($context eq 'requestcourses') {
                   5142:         %tools = (
                   5143:                       official   => 1,
                   5144:                       unofficial => 1,
1.1006    raeburn  5145:                       community  => 1,
1.985     raeburn  5146:                  );
                   5147:     } else {
                   5148:         %tools = (
                   5149:                       aboutme   => 1,
                   5150:                       blog      => 1,
                   5151:                       portfolio => 1,
                   5152:                  );
                   5153:     }
1.976     raeburn  5154:     return if (!defined($tools{$tool}));
                   5155: 
                   5156:     if ((!defined($udom)) || (!defined($uname))) {
                   5157:         $udom = $env{'user.domain'};
                   5158:         $uname = $env{'user.name'};
                   5159:     }
                   5160: 
1.978     raeburn  5161:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5162:         if ($action ne 'reload') {
1.985     raeburn  5163:             if ($context eq 'requestcourses') {
                   5164:                 return $env{'environment.canrequest.'.$tool};
                   5165:             } else {
                   5166:                 return $env{'environment.availabletools.'.$tool};
                   5167:             }
                   5168:         }
1.976     raeburn  5169:     }
                   5170: 
                   5171:     my ($toolstatus,$inststatus);
                   5172: 
1.985     raeburn  5173:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5174:          ($action ne 'reload')) {
                   5175:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5176:         $inststatus = $env{'environment.inststatus'};
                   5177:     } else {
1.1056.4.9  raeburn  5178:         if (ref($userenvref) eq 'HASH') {
                   5179:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5180:             $inststatus = $userenvref->{'inststatus'};
                   5181:         } else {
                   5182:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5183:             $toolstatus = $userenv{$context.'.'.$tool};
                   5184:             $inststatus = $userenv{'inststatus'};
                   5185:         }
1.976     raeburn  5186:     }
                   5187: 
                   5188:     if ($toolstatus ne '') {
                   5189:         if ($toolstatus) {
                   5190:             $access = 1;
                   5191:         } else {
                   5192:             $access = 0;
                   5193:         }
                   5194:         return $access;
                   5195:     }
                   5196: 
1.1056.4.9  raeburn  5197:     my ($is_adv,%domdef);
                   5198:     if (ref($is_advref) eq 'HASH') {
                   5199:         $is_adv = $is_advref->{'is_adv'};
                   5200:     } else {
                   5201:         $is_adv = &is_advanced_user($udom,$uname);
                   5202:     }
                   5203:     if (ref($domdefref) eq 'HASH') {
                   5204:         %domdef = %{$domdefref};
                   5205:     } else {
                   5206:         %domdef = &get_domain_defaults($udom);
                   5207:     }
1.976     raeburn  5208:     if (ref($domdef{$tool}) eq 'HASH') {
                   5209:         if ($is_adv) {
                   5210:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5211:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5212:                     $access = 1;
                   5213:                 } else {
                   5214:                     $access = 0;
                   5215:                 }
                   5216:                 return $access;
                   5217:             }
                   5218:         }
                   5219:         if ($inststatus ne '') {
                   5220:             my ($hasaccess,$hasnoaccess);
                   5221:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5222:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5223:                     if ($domdef{$tool}{$affiliation}) {
                   5224:                         $hasaccess = 1;
                   5225:                     } else {
                   5226:                         $hasnoaccess = 1;
                   5227:                     }
                   5228:                 }
                   5229:             }
                   5230:             if ($hasaccess || $hasnoaccess) {
                   5231:                 if ($hasaccess) {
                   5232:                     $access = 1;
                   5233:                 } elsif ($hasnoaccess) {
                   5234:                     $access = 0; 
                   5235:                 }
                   5236:                 return $access;
                   5237:             }
                   5238:         } else {
                   5239:             if ($domdef{$tool}{'default'} ne '') {
                   5240:                 if ($domdef{$tool}{'default'}) {
                   5241:                     $access = 1;
                   5242:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5243:                     $access = 0;
                   5244:                 }
                   5245:                 return $access;
                   5246:             }
                   5247:         }
                   5248:     } else {
1.985     raeburn  5249:         if ($context eq 'tools') {
                   5250:             $access = 1;
                   5251:         } else {
                   5252:             $access = 0;
                   5253:         }
1.976     raeburn  5254:         return $access;
                   5255:     }
                   5256: }
                   5257: 
1.1050    raeburn  5258: sub is_course_owner {
                   5259:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5260:     if (($udom eq '') || ($uname eq '')) {
                   5261:         $udom = $env{'user.domain'};
                   5262:         $uname = $env{'user.name'};
                   5263:     }
                   5264:     unless (($udom eq '') || ($uname eq '')) {
                   5265:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5266:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5267:                 return 1;
                   5268:             } else {
                   5269:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5270:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5271:                     return 1;
                   5272:                 }
                   5273:             }
                   5274:         }
                   5275:     }
                   5276:     return;
                   5277: }
                   5278: 
1.976     raeburn  5279: sub is_advanced_user {
                   5280:     my ($udom,$uname) = @_;
1.1056.4.10  raeburn  5281:     if ($udom ne '' && $uname ne '') {
                   5282:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5283:             return $env{'user.adv'};
                   5284:         }
                   5285:     }
1.976     raeburn  5286:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5287:     my %allroles;
                   5288:     my $is_adv;
                   5289:     foreach my $role (keys(%roleshash)) {
                   5290:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5291:         my $area = '/'.$tdomain.'/'.$trest;
                   5292:         if ($sec ne '') {
                   5293:             $area .= '/'.$sec;
                   5294:         }
                   5295:         if (($area ne '') && ($trole ne '')) {
                   5296:             my $spec=$trole.'.'.$area;
                   5297:             if ($trole =~ /^cr\//) {
                   5298:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5299:             } elsif ($trole ne 'gr') {
                   5300:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5301:             }
                   5302:         }
                   5303:     }
                   5304:     foreach my $role (keys(%allroles)) {
                   5305:         last if ($is_adv);
                   5306:         foreach my $item (split(/:/,$allroles{$role})) {
                   5307:             if ($item ne '') {
                   5308:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5309:                 if ($privilege eq 'adv') {
                   5310:                     $is_adv = 1;
                   5311:                     last;
                   5312:                 }
                   5313:             }
                   5314:         }
                   5315:     }
                   5316:     return $is_adv;
                   5317: }
1.798     raeburn  5318: 
1.1035    raeburn  5319: sub check_can_request {
1.1036    raeburn  5320:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5321:     my $canreq = 0;
                   5322:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5323:     my @options = ('approval','validate','autolimit');
                   5324:     my $optregex = join('|',@options);
                   5325:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5326:         foreach my $type (@{$types}) {
                   5327:             if (&usertools_access($env{'user.name'},
                   5328:                                   $env{'user.domain'},
                   5329:                                   $type,undef,'requestcourses')) {
                   5330:                 $canreq ++;
1.1036    raeburn  5331:                 if (ref($request_domains) eq 'HASH') {
                   5332:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5333:                 }
1.1035    raeburn  5334:                 if ($dom eq $env{'user.domain'}) {
                   5335:                     $can_request->{$type} = 1;
                   5336:                 }
                   5337:             }
                   5338:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5339:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5340:                 if (@curr > 0) {
1.1036    raeburn  5341:                     foreach my $item (@curr) {
                   5342:                         if (ref($request_domains) eq 'HASH') {
                   5343:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5344:                             if ($otherdom ne '') {
                   5345:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5346:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5347:                                         push(@{$request_domains->{$type}},$otherdom);
                   5348:                                     }
                   5349:                                 } else {
                   5350:                                     push(@{$request_domains->{$type}},$otherdom);
                   5351:                                 }
                   5352:                             }
                   5353:                         }
                   5354:                     }
                   5355:                     unless($dom eq $env{'user.domain'}) {
                   5356:                         $canreq ++;
1.1035    raeburn  5357:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5358:                             $can_request->{$type} = 1;
                   5359:                         }
                   5360:                     }
                   5361:                 }
                   5362:             }
                   5363:         }
                   5364:     }
                   5365:     return $canreq;
                   5366: }
                   5367: 
1.341     www      5368: # ---------------------------------------------- Custom access rule evaluation
                   5369: 
                   5370: sub customaccess {
                   5371:     my ($priv,$uri)=@_;
1.807     albertel 5372:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5373:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5374:     $udom = &LONCAPA::clean_domain($udom);
                   5375:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5376:     my $access=0;
1.800     albertel 5377:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5378: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5379: 	if ($type eq 'user') {
                   5380: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5381: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5382: 		if ($tdom) {
                   5383: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5384: 		}
1.896     albertel 5385: 		if ($tuname) {
                   5386: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5387: 		}
                   5388: 		$access=($effect eq 'allow');
                   5389: 		last;
                   5390: 	    }
                   5391: 	} else {
                   5392: 	    if ($role) {
                   5393: 		if ($role ne $urole) { next; }
                   5394: 	    }
                   5395: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5396: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5397: 		if ($tdom) {
                   5398: 		    if ($tdom ne $udom) { next; }
                   5399: 		}
                   5400: 		if ($tcrs) {
                   5401: 		    if ($tcrs ne $ucrs) { next; }
                   5402: 		}
                   5403: 		if ($tsec) {
                   5404: 		    if ($tsec ne $usec) { next; }
                   5405: 		}
                   5406: 		$access=($effect eq 'allow');
                   5407: 		last;
                   5408: 	    }
                   5409: 	    if ($realm eq '' && $role eq '') {
                   5410: 		$access=($effect eq 'allow');
                   5411: 	    }
1.402     bowersj2 5412: 	}
1.341     www      5413:     }
                   5414:     return $access;
                   5415: }
                   5416: 
1.103     harris41 5417: # ------------------------------------------------- Check for a user privilege
1.12      www      5418: 
                   5419: sub allowed {
1.810     raeburn  5420:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5421:     my $ver_orguri=$uri;
1.439     www      5422:     $uri=&deversion($uri);
1.152     www      5423:     my $orguri=$uri;
1.52      www      5424:     $uri=&declutter($uri);
1.809     raeburn  5425: 
1.810     raeburn  5426:     if ($priv eq 'evb') {
                   5427: # Evade communication block restrictions for specified role in a course
                   5428:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5429:             return $1;
                   5430:         } else {
                   5431:             return;
                   5432:         }
                   5433:     }
                   5434: 
1.620     albertel 5435:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5436: # Free bre access to adm and meta resources
1.775     albertel 5437:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5438: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5439: 	&& ($priv eq 'bre')) {
1.14      www      5440: 	return 'F';
1.159     www      5441:     }
                   5442: 
1.545     banghart 5443: # Free bre access to user's own portfolio contents
1.714     raeburn  5444:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5445:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5446: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5447:         my %setters;
                   5448:         my ($startblock,$endblock) = 
                   5449:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5450:         if ($startblock && $endblock) {
                   5451:             return 'B';
                   5452:         } else {
                   5453:             return 'F';
                   5454:         }
1.545     banghart 5455:     }
                   5456: 
1.762     raeburn  5457: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5458:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5459:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5460:         if (exists($env{'request.course.id'})) {
                   5461:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5462:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5463:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5464:                 my $courseprivid=$env{'request.course.id'};
                   5465:                 $courseprivid=~s/\_/\//;
                   5466:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5467:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5468:                     return $1; 
1.762     raeburn  5469:                 } else {
                   5470:                     if ($env{'request.course.sec'}) {
                   5471:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5472:                     }
                   5473:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5474:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5475:                         return $2;
                   5476:                     }
1.714     raeburn  5477:                 }
                   5478:             }
                   5479:         }
                   5480:     }
                   5481: 
1.159     www      5482: # Free bre to public access
                   5483: 
                   5484:     if ($priv eq 'bre') {
1.238     www      5485:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5486: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5487:            return 'F'; 
                   5488:         }
1.238     www      5489:         if ($copyright eq 'priv') {
                   5490:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5491: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5492: 		return '';
                   5493:             }
                   5494:         }
                   5495:         if ($copyright eq 'domain') {
                   5496:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5497: 	    unless (($env{'user.domain'} eq $1) ||
                   5498:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5499: 		return '';
                   5500:             }
1.262     matthew  5501:         }
1.620     albertel 5502:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5503:             # Library role, so allow browsing of resources in this domain.
                   5504:             return 'F';
1.238     www      5505:         }
1.341     www      5506:         if ($copyright eq 'custom') {
                   5507: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5508:         }
1.14      www      5509:     }
1.264     matthew  5510:     # Domain coordinator is trying to create a course
1.620     albertel 5511:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5512:         # uri is the requested domain in this case.
                   5513:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5514:         # a role of dc for the domain in question.
1.620     albertel 5515:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5516:     }
1.29      www      5517: 
1.52      www      5518:     my $thisallowed='';
                   5519:     my $statecond=0;
                   5520:     my $courseprivid='';
                   5521: 
1.1039    raeburn  5522:     my $ownaccess;
1.1043    raeburn  5523:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5524:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5525:         if ($uri eq '') {
                   5526:             $ownaccess = 1;
                   5527:         } else {
                   5528:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5529:                 my $udom = $env{'user.domain'};
                   5530:                 my $uname = $env{'user.name'};
                   5531:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5532:                     $ownaccess = 1;
1.1040    raeburn  5533:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5534:                     unless ($uri =~ m{\.\./}) {
                   5535:                         $ownaccess = 1;
                   5536:                     }
                   5537:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5538:                     my $now = time;
                   5539:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5540:                         my $adom = $1;
                   5541:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5542:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5543:                                 my ($start,$end) = split('.',$env{$key});
                   5544:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5545:                                     $ownaccess = 1;
                   5546:                                     last;
                   5547:                                 }
                   5548:                             }
                   5549:                         }
                   5550:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5551:                         my $adom = $1;
                   5552:                         my $aname = $2;
1.1042    raeburn  5553:                         foreach my $role ('ca','aa') { 
                   5554:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5555:                                 my ($start,$end) =
                   5556:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5557:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5558:                                     $ownaccess = 1;
                   5559:                                     last;
                   5560:                                 }
1.1039    raeburn  5561:                             }
                   5562:                         }
                   5563:                     }
                   5564:                 }
                   5565:             }
                   5566:         }
                   5567:     }
                   5568: 
1.52      www      5569: # Course
                   5570: 
1.620     albertel 5571:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5572:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5573:             $thisallowed.=$1;
                   5574:         }
1.52      www      5575:     }
1.29      www      5576: 
1.52      www      5577: # Domain
                   5578: 
1.620     albertel 5579:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5580:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5581:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5582:             $thisallowed.=$1;
                   5583:         }
1.12      www      5584:     }
1.52      www      5585: 
                   5586: # Course: uri itself is a course
1.66      www      5587:     my $courseuri=$uri;
                   5588:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5589:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5590: 
1.620     albertel 5591:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5592:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5593:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5594:             $thisallowed.=$1;
                   5595:         }
1.12      www      5596:     }
1.29      www      5597: 
1.665     albertel 5598: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5599: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5600:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5601: 	$thisallowed='';
1.671     raeburn  5602:         my ($match)=&is_on_map($uri);
                   5603:         if ($match) {
                   5604:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5605:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5606:                 $thisallowed.=$1;
                   5607:             }
                   5608:         } else {
1.705     albertel 5609:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5610:             if ($refuri) {
                   5611:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5612:                     $thisallowed='F';
1.671     raeburn  5613:                 } else {
                   5614:                     $refuri=&declutter($refuri);
                   5615:                     my ($match) = &is_on_map($refuri);
                   5616:                     if ($match) {
                   5617:                         $thisallowed='F';
                   5618:                     }
1.669     raeburn  5619:                 }
1.671     raeburn  5620:             }
                   5621:         }
1.314     www      5622:     }
1.492     albertel 5623: 
1.766     albertel 5624:     if ($priv eq 'bre'
                   5625: 	&& $thisallowed ne 'F' 
                   5626: 	&& $thisallowed ne '2'
                   5627: 	&& &is_portfolio_url($uri)) {
                   5628: 	$thisallowed = &portfolio_access($uri);
                   5629:     }
                   5630:     
1.52      www      5631: # Full access at system, domain or course-wide level? Exit.
1.29      www      5632:     if ($thisallowed=~/F/) {
                   5633: 	return 'F';
                   5634:     }
                   5635: 
1.52      www      5636: # If this is generating or modifying users, exit with special codes
1.29      www      5637: 
1.643     www      5638:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5639: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5640: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5641: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5642: 	    unless ($auname) { return $thisallowed; }
                   5643: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5644: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5645: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5646: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5647: 	}
1.52      www      5648: 	return $thisallowed;
                   5649:     }
                   5650: #
1.103     harris41 5651: # Gathered so far: system, domain and course wide privileges
1.52      www      5652: #
                   5653: # Course: See if uri or referer is an individual resource that is part of 
                   5654: # the course
                   5655: 
1.620     albertel 5656:     if ($env{'request.course.id'}) {
1.232     www      5657: 
1.620     albertel 5658:        $courseprivid=$env{'request.course.id'};
                   5659:        if ($env{'request.course.sec'}) {
                   5660:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5661:        }
                   5662:        $courseprivid=~s/\_/\//;
                   5663:        my $checkreferer=1;
1.232     www      5664:        my ($match,$cond)=&is_on_map($uri);
                   5665:        if ($match) {
                   5666:            $statecond=$cond;
1.620     albertel 5667:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5668:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5669:                $thisallowed.=$1;
                   5670:                $checkreferer=0;
                   5671:            }
1.29      www      5672:        }
1.83      www      5673:        
1.148     www      5674:        if ($checkreferer) {
1.620     albertel 5675: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5676:             unless ($refuri) {
1.800     albertel 5677:                 foreach my $key (keys(%env)) {
                   5678: 		    if ($key=~/^httpref\..*\*/) {
                   5679: 			my $pattern=$key;
1.156     www      5680:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5681:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5682:                         $pattern=~s/\//\\\//g;
1.152     www      5683:                         if ($orguri=~/$pattern/) {
1.800     albertel 5684: 			    $refuri=$env{$key};
1.148     www      5685:                         }
                   5686:                     }
1.191     harris41 5687:                 }
1.148     www      5688:             }
1.232     www      5689: 
1.148     www      5690:          if ($refuri) { 
1.152     www      5691: 	  $refuri=&declutter($refuri);
1.232     www      5692:           my ($match,$cond)=&is_on_map($refuri);
                   5693:             if ($match) {
                   5694:               my $refstatecond=$cond;
1.620     albertel 5695:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5696:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5697:                   $thisallowed.=$1;
1.53      www      5698:                   $uri=$refuri;
                   5699:                   $statecond=$refstatecond;
1.52      www      5700:               }
                   5701:           }
1.148     www      5702:         }
1.29      www      5703:        }
1.52      www      5704:    }
1.29      www      5705: 
1.52      www      5706: #
1.103     harris41 5707: # Gathered now: all privileges that could apply, and condition number
1.52      www      5708: # 
                   5709: #
                   5710: # Full or no access?
                   5711: #
1.29      www      5712: 
1.52      www      5713:     if ($thisallowed=~/F/) {
                   5714: 	return 'F';
                   5715:     }
1.29      www      5716: 
1.52      www      5717:     unless ($thisallowed) {
                   5718:         return '';
                   5719:     }
1.29      www      5720: 
1.52      www      5721: # Restrictions exist, deal with them
                   5722: #
                   5723: #   C:according to course preferences
                   5724: #   R:according to resource settings
                   5725: #   L:unless locked
                   5726: #   X:according to user session state
                   5727: #
                   5728: 
                   5729: # Possibly locked functionality, check all courses
1.54      www      5730: # Locks might take effect only after 10 minutes cache expiration for other
                   5731: # courses, and 2 minutes for current course
1.52      www      5732: 
                   5733:     my $envkey;
                   5734:     if ($thisallowed=~/L/) {
1.1000    raeburn  5735:         foreach $envkey (keys(%env)) {
1.54      www      5736:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5737:                my $courseid=$2;
                   5738:                my $roleid=$1.'.'.$2;
1.92      www      5739:                $courseid=~s/^\///;
1.54      www      5740:                my $expiretime=600;
1.620     albertel 5741:                if ($env{'request.role'} eq $roleid) {
1.54      www      5742: 		  $expiretime=120;
                   5743:                }
                   5744: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5745:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5746:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5747: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5748:                }
1.620     albertel 5749:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5750:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5751: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5752:                        &log($env{'user.domain'},$env{'user.name'},
                   5753:                             $env{'user.home'},
1.57      www      5754:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5755:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5756:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5757: 		       return '';
                   5758:                    }
                   5759:                }
1.620     albertel 5760:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5761:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5762: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5763:                        &log($env{'user.domain'},$env{'user.name'},
                   5764:                             $env{'user.home'},
1.57      www      5765:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5766:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5767:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5768: 		       return '';
                   5769:                    }
                   5770:                }
                   5771: 	   }
1.29      www      5772:        }
1.52      www      5773:     }
                   5774:    
                   5775: #
                   5776: # Rest of the restrictions depend on selected course
                   5777: #
                   5778: 
1.620     albertel 5779:     unless ($env{'request.course.id'}) {
1.766     albertel 5780: 	if ($thisallowed eq 'A') {
                   5781: 	    return 'A';
1.814     raeburn  5782:         } elsif ($thisallowed eq 'B') {
                   5783:             return 'B';
1.766     albertel 5784: 	} else {
                   5785: 	    return '1';
                   5786: 	}
1.52      www      5787:     }
1.29      www      5788: 
1.52      www      5789: #
                   5790: # Now user is definitely in a course
                   5791: #
1.53      www      5792: 
                   5793: 
                   5794: # Course preferences
                   5795: 
                   5796:    if ($thisallowed=~/C/) {
1.620     albertel 5797:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5798:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5799:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5800: 	   =~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5801:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5802: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5803: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5804: 			$env{'request.course.id'});
                   5805: 	   }
1.237     www      5806:            return '';
                   5807:        }
                   5808: 
1.620     albertel 5809:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5810: 	   =~/\Q$unamedom\E/) {
1.1056.4.22  raeburn  5811:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5812: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5813: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5814: 			$env{'request.course.id'});
                   5815: 	   }
1.54      www      5816:            return '';
                   5817:        }
1.53      www      5818:    }
                   5819: 
                   5820: # Resource preferences
                   5821: 
                   5822:    if ($thisallowed=~/R/) {
1.620     albertel 5823:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5824:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1056.4.22  raeburn  5825:            if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689     albertel 5826: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5827: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5828: 	   }
                   5829: 	   return '';
1.54      www      5830:        }
1.53      www      5831:    }
1.30      www      5832: 
1.246     www      5833: # Restricted by state or randomout?
1.30      www      5834: 
1.52      www      5835:    if ($thisallowed=~/X/) {
1.620     albertel 5836:       if ($env{'acc.randomout'}) {
1.579     albertel 5837: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5838:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5839:             return ''; 
                   5840:          }
1.247     www      5841:       }
                   5842:       if (&condval($statecond)) {
1.52      www      5843: 	 return '2';
                   5844:       } else {
                   5845:          return '';
                   5846:       }
                   5847:    }
1.30      www      5848: 
1.766     albertel 5849:     if ($thisallowed eq 'A') {
                   5850: 	return 'A';
1.814     raeburn  5851:     } elsif ($thisallowed eq 'B') {
                   5852:         return 'B';
1.766     albertel 5853:     }
1.52      www      5854:    return 'F';
1.232     www      5855: }
                   5856: 
1.710     albertel 5857: sub split_uri_for_cond {
                   5858:     my $uri=&deversion(&declutter(shift));
                   5859:     my @uriparts=split(/\//,$uri);
                   5860:     my $filename=pop(@uriparts);
                   5861:     my $pathname=join('/',@uriparts);
                   5862:     return ($pathname,$filename);
                   5863: }
1.232     www      5864: # --------------------------------------------------- Is a resource on the map?
                   5865: 
                   5866: sub is_on_map {
1.710     albertel 5867:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5868:     #Trying to find the conditional for the file
1.620     albertel 5869:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5870: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5871:     if ($match) {
1.289     bowersj2 5872: 	return (1,$1);
                   5873:     } else {
1.434     www      5874: 	return (0,0);
1.289     bowersj2 5875:     }
1.12      www      5876: }
                   5877: 
1.427     www      5878: # --------------------------------------------------------- Get symb from alias
                   5879: 
                   5880: sub get_symb_from_alias {
                   5881:     my $symb=shift;
                   5882:     my ($map,$resid,$url)=&decode_symb($symb);
                   5883: # Already is a symb
                   5884:     if ($url) { return $symb; }
                   5885: # Must be an alias
                   5886:     my $aliassymb='';
                   5887:     my %bighash;
1.620     albertel 5888:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5889:                             &GDBM_READER(),0640)) {
                   5890:         my $rid=$bighash{'mapalias_'.$symb};
                   5891: 	if ($rid) {
                   5892: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5893: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5894: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5895: 	}
                   5896:         untie %bighash;
                   5897:     }
                   5898:     return $aliassymb;
                   5899: }
                   5900: 
1.12      www      5901: # ----------------------------------------------------------------- Define Role
                   5902: 
                   5903: sub definerole {
                   5904:   if (allowed('mcr','/')) {
                   5905:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5906:     foreach my $role (split(':',$sysrole)) {
                   5907: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5908:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5909:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5910: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5911:                return "refused:s:$crole&$cqual"; 
                   5912:             }
                   5913:         }
1.191     harris41 5914:     }
1.800     albertel 5915:     foreach my $role (split(':',$domrole)) {
                   5916: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5917:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5918:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5919: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5920:                return "refused:d:$crole&$cqual"; 
                   5921:             }
                   5922:         }
1.191     harris41 5923:     }
1.800     albertel 5924:     foreach my $role (split(':',$courole)) {
                   5925: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5926:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5927:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5928: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5929:                return "refused:c:$crole&$cqual"; 
                   5930:             }
                   5931:         }
1.191     harris41 5932:     }
1.620     albertel 5933:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5934:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5935: 	        "rolesdef_$rolename=".
                   5936:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5937:     return reply($command,$env{'user.home'});
1.12      www      5938:   } else {
                   5939:     return 'refused';
                   5940:   }
1.105     harris41 5941: }
                   5942: 
                   5943: # ---------------- Make a metadata query against the network of library servers
                   5944: 
                   5945: sub metadata_query {
1.244     matthew  5946:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5947:     my %rhash;
1.845     albertel 5948:     my %libserv = &all_library();
1.244     matthew  5949:     my @server_list = (defined($server_array) ? @$server_array
                   5950:                                               : keys(%libserv) );
                   5951:     for my $server (@server_list) {
1.118     harris41 5952: 	unless ($custom or $customshow) {
                   5953: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5954: 	    $rhash{$server}=$reply;
                   5955: 	}
                   5956: 	else {
                   5957: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5958: 			     &escape($custom).':'.&escape($customshow),
                   5959: 			     $server);
                   5960: 	    $rhash{$server}=$reply;
                   5961: 	}
1.112     harris41 5962:     }
1.118     harris41 5963:     return \%rhash;
1.240     www      5964: }
                   5965: 
                   5966: # ----------------------------------------- Send log queries and wait for reply
                   5967: 
                   5968: sub log_query {
                   5969:     my ($uname,$udom,$query,%filters)=@_;
                   5970:     my $uhome=&homeserver($uname,$udom);
                   5971:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5972:     my $uhost=&hostname($uhome);
1.800     albertel 5973:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5974:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5975:                        $uhome);
1.479     albertel 5976:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5977:     return get_query_reply($queryid);
                   5978: }
                   5979: 
1.818     raeburn  5980: # -------------------------- Update MySQL table for portfolio file
                   5981: 
                   5982: sub update_portfolio_table {
1.821     raeburn  5983:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5984:     if ($group ne '') {
                   5985:         $file_name =~s /^\Q$group\E//;
                   5986:     }
1.818     raeburn  5987:     my $homeserver = &homeserver($uname,$udom);
                   5988:     my $queryid=
1.821     raeburn  5989:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5990:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5991:     my $reply = &get_query_reply($queryid);
                   5992:     return $reply;
                   5993: }
                   5994: 
1.899     raeburn  5995: # -------------------------- Update MySQL allusers table
                   5996: 
                   5997: sub update_allusers_table {
                   5998:     my ($uname,$udom,$names) = @_;
                   5999:     my $homeserver = &homeserver($uname,$udom);
                   6000:     my $queryid=
                   6001:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6002:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6003:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6004:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6005:                'generation='.&escape($names->{'generation'}).'%%'.
                   6006:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6007:                'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4  raeburn  6008:     return;
1.899     raeburn  6009: }
                   6010: 
1.508     raeburn  6011: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6012: 
                   6013: sub fetch_enrollment_query {
1.511     raeburn  6014:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6015:     my $homeserver;
1.547     raeburn  6016:     my $maxtries = 1;
1.508     raeburn  6017:     if ($context eq 'automated') {
                   6018:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6019:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6020:     } else {
                   6021:         $homeserver = &homeserver($cnum,$dom);
                   6022:     }
1.838     albertel 6023:     my $host=&hostname($homeserver);
1.506     raeburn  6024:     my $cmd = '';
1.1000    raeburn  6025:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6026:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6027:     }
                   6028:     $cmd =~ s/%%$//;
                   6029:     $cmd = &escape($cmd);
                   6030:     my $query = 'fetchenrollment';
1.620     albertel 6031:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6032:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6033:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6034:         return 'error: '.$queryid;
                   6035:     }
1.506     raeburn  6036:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6037:     my $tries = 1;
                   6038:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6039:         $reply = &get_query_reply($queryid);
                   6040:         $tries ++;
                   6041:     }
1.526     raeburn  6042:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6043:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6044:     } else {
1.901     albertel 6045:         my @responses = split(/:/,$reply);
1.515     raeburn  6046:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6047:             foreach my $line (@responses) {
                   6048:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6049:                 $$replyref{$key} = $value;
                   6050:             }
                   6051:         } else {
1.506     raeburn  6052:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 6053:             foreach my $line (@responses) {
                   6054:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6055:                 $$replyref{$key} = $value;
                   6056:                 if ($value > 0) {
1.800     albertel 6057:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6058:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6059:                         my $destname = $pathname.'/'.$filename;
                   6060:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6061:                         if ($xml_classlist =~ /^error/) {
                   6062:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6063:                         } else {
1.506     raeburn  6064:                             if ( open(FILE,">$destname") ) {
                   6065:                                 print FILE &unescape($xml_classlist);
                   6066:                                 close(FILE);
1.526     raeburn  6067:                             } else {
                   6068:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6069:                             }
                   6070:                         }
                   6071:                     }
                   6072:                 }
                   6073:             }
                   6074:         }
                   6075:         return 'ok';
                   6076:     }
                   6077:     return 'error';
                   6078: }
                   6079: 
1.242     www      6080: sub get_query_reply {
                   6081:     my $queryid=shift;
1.240     www      6082:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   6083:     my $reply='';
                   6084:     for (1..100) {
                   6085: 	sleep 2;
                   6086:         if (-e $replyfile.'.end') {
1.448     albertel 6087: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6088: 		$reply = join('',<$fh>);
                   6089: 		close($fh);
1.240     www      6090: 	   } else { return 'error: reply_file_error'; }
1.242     www      6091:            return &unescape($reply);
                   6092: 	}
1.240     www      6093:     }
1.242     www      6094:     return 'timeout:'.$queryid;
1.240     www      6095: }
                   6096: 
                   6097: sub courselog_query {
1.241     www      6098: #
                   6099: # possible filters:
                   6100: # url: url or symb
                   6101: # username
                   6102: # domain
                   6103: # action: view, submit, grade
                   6104: # start: timestamp
                   6105: # end: timestamp
                   6106: #
1.240     www      6107:     my (%filters)=@_;
1.620     albertel 6108:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6109:     if ($filters{'url'}) {
                   6110: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6111:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6112:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6113:     }
1.620     albertel 6114:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6115:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6116:     return &log_query($cname,$cdom,'courselog',%filters);
                   6117: }
                   6118: 
                   6119: sub userlog_query {
1.858     raeburn  6120: #
                   6121: # possible filters:
                   6122: # action: log check role
                   6123: # start: timestamp
                   6124: # end: timestamp
                   6125: #
1.240     www      6126:     my ($uname,$udom,%filters)=@_;
                   6127:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6128: }
                   6129: 
1.506     raeburn  6130: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6131: 
                   6132: sub auto_run {
1.508     raeburn  6133:     my ($cnum,$cdom) = @_;
1.876     raeburn  6134:     my $response = 0;
                   6135:     my $settings;
                   6136:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6137:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6138:         $settings = $domconfig{'autoenroll'};
                   6139:         if ($settings->{'run'} eq '1') {
                   6140:             $response = 1;
                   6141:         }
                   6142:     } else {
1.934     raeburn  6143:         my $homeserver;
                   6144:         if (&is_course($cdom,$cnum)) {
                   6145:             $homeserver = &homeserver($cnum,$cdom);
                   6146:         } else {
                   6147:             $homeserver = &domain($cdom,'primary');
                   6148:         }
                   6149:         if ($homeserver ne 'no_host') {
                   6150:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6151:         }
1.876     raeburn  6152:     }
1.506     raeburn  6153:     return $response;
                   6154: }
1.776     albertel 6155: 
1.506     raeburn  6156: sub auto_get_sections {
1.508     raeburn  6157:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6158:     my $homeserver;
                   6159:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6160:         $homeserver = &homeserver($cnum,$cdom);
                   6161:     }
                   6162:     if (!defined($homeserver)) { 
                   6163:         if ($cdom =~ /^$match_domain$/) {
                   6164:             $homeserver = &domain($cdom,'primary');
                   6165:         }
                   6166:     }
                   6167:     my @secs;
                   6168:     if (defined($homeserver)) {
                   6169:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6170:         unless ($response eq 'refused') {
                   6171:             @secs = split(/:/,$response);
                   6172:         }
1.506     raeburn  6173:     }
                   6174:     return @secs;
                   6175: }
1.776     albertel 6176: 
1.506     raeburn  6177: sub auto_new_course {
1.1056.4.19  raeburn  6178:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6179:     my $homeserver = &homeserver($cnum,$cdom);
1.1056.4.19  raeburn  6180:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6181:     return $response;
                   6182: }
1.776     albertel 6183: 
1.506     raeburn  6184: sub auto_validate_courseID {
1.508     raeburn  6185:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6186:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6187:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6188:     return $response;
                   6189: }
1.776     albertel 6190: 
1.1007    raeburn  6191: sub auto_validate_instcode {
1.1020    raeburn  6192:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6193:     my ($homeserver,$response);
                   6194:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6195:         $homeserver = &homeserver($cnum,$cdom);
                   6196:     }
                   6197:     if (!defined($homeserver)) {
                   6198:         if ($cdom =~ /^$match_domain$/) {
                   6199:             $homeserver = &domain($cdom,'primary');
                   6200:         }
                   6201:     }
1.1056.4.2  raeburn  6202:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6203:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6204:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6205:     return ($outcome,$description);
1.1007    raeburn  6206: }
                   6207: 
1.506     raeburn  6208: sub auto_create_password {
1.873     raeburn  6209:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6210:     my ($homeserver,$response);
1.506     raeburn  6211:     my $create_passwd = 0;
                   6212:     my $authchk = '';
1.873     raeburn  6213:     if ($udom =~ /^$match_domain$/) {
                   6214:         $homeserver = &domain($udom,'primary');
                   6215:     }
                   6216:     if ($homeserver eq '') {
                   6217:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6218:             $homeserver = &homeserver($cnum,$cdom);
                   6219:         }
                   6220:     }
                   6221:     if ($homeserver eq '') {
                   6222:         $authchk = 'nodomain';
1.506     raeburn  6223:     } else {
1.873     raeburn  6224:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6225:         if ($response eq 'refused') {
                   6226:             $authchk = 'refused';
                   6227:         } else {
1.901     albertel 6228:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6229:         }
1.506     raeburn  6230:     }
                   6231:     return ($authparam,$create_passwd,$authchk);
                   6232: }
                   6233: 
1.706     raeburn  6234: sub auto_photo_permission {
                   6235:     my ($cnum,$cdom,$students) = @_;
                   6236:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6237:     my ($outcome,$perm_reqd,$conditions) = 
                   6238: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6239:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6240: 	return (undef,undef);
                   6241:     }
1.706     raeburn  6242:     return ($outcome,$perm_reqd,$conditions);
                   6243: }
                   6244: 
                   6245: sub auto_checkphotos {
                   6246:     my ($uname,$udom,$pid) = @_;
                   6247:     my $homeserver = &homeserver($uname,$udom);
                   6248:     my ($result,$resulttype);
                   6249:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6250: 				   &escape($uname).':'.&escape($pid),
                   6251: 				   $homeserver));
1.709     albertel 6252:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6253: 	return (undef,undef);
                   6254:     }
1.706     raeburn  6255:     if ($outcome) {
                   6256:         ($result,$resulttype) = split(/:/,$outcome);
                   6257:     } 
                   6258:     return ($result,$resulttype);
                   6259: }
                   6260: 
                   6261: sub auto_photochoice {
                   6262:     my ($cnum,$cdom) = @_;
                   6263:     my $homeserver = &homeserver($cnum,$cdom);
                   6264:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6265: 						       &escape($cdom),
                   6266: 						       $homeserver)));
1.709     albertel 6267:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6268: 	return (undef,undef);
                   6269:     }
1.706     raeburn  6270:     return ($update,$comment);
                   6271: }
                   6272: 
                   6273: sub auto_photoupdate {
                   6274:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6275:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6276:     my $host=&hostname($homeserver);
1.706     raeburn  6277:     my $cmd = '';
                   6278:     my $maxtries = 1;
1.800     albertel 6279:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6280:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6281:     }
                   6282:     $cmd =~ s/%%$//;
                   6283:     $cmd = &escape($cmd);
                   6284:     my $query = 'institutionalphotos';
                   6285:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6286:     unless ($queryid=~/^\Q$host\E\_/) {
                   6287:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6288:         return 'error: '.$queryid;
                   6289:     }
                   6290:     my $reply = &get_query_reply($queryid);
                   6291:     my $tries = 1;
                   6292:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6293:         $reply = &get_query_reply($queryid);
                   6294:         $tries ++;
                   6295:     }
                   6296:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6297:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6298:     } else {
                   6299:         my @responses = split(/:/,$reply);
                   6300:         my $outcome = shift(@responses); 
                   6301:         foreach my $item (@responses) {
                   6302:             my ($key,$value) = split(/=/,$item);
                   6303:             $$photo{$key} = $value;
                   6304:         }
                   6305:         return $outcome;
                   6306:     }
                   6307:     return 'error';
                   6308: }
                   6309: 
1.521     raeburn  6310: sub auto_instcode_format {
1.793     albertel 6311:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6312: 	$cat_order) = @_;
1.521     raeburn  6313:     my $courses = '';
1.772     raeburn  6314:     my @homeservers;
1.521     raeburn  6315:     if ($caller eq 'global') {
1.841     albertel 6316: 	my %servers = &get_servers($codedom,'library');
                   6317: 	foreach my $tryserver (keys(%servers)) {
                   6318: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6319: 		push(@homeservers,$tryserver);
                   6320: 	    }
1.584     raeburn  6321:         }
1.1022    raeburn  6322:     } elsif ($caller eq 'requests') {
                   6323:         if ($codedom =~ /^$match_domain$/) {
                   6324:             my $chome = &domain($codedom,'primary');
                   6325:             unless ($chome eq 'no_host') {
                   6326:                 push(@homeservers,$chome);
                   6327:             }
                   6328:         }
1.521     raeburn  6329:     } else {
1.772     raeburn  6330:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6331:     }
1.793     albertel 6332:     foreach my $code (keys(%{$instcodes})) {
                   6333:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6334:     }
                   6335:     chop($courses);
1.772     raeburn  6336:     my $ok_response = 0;
                   6337:     my $response;
                   6338:     while (@homeservers > 0 && $ok_response == 0) {
                   6339:         my $server = shift(@homeservers); 
                   6340:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6341:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6342:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6343: 		split(/:/,$response);
1.772     raeburn  6344:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6345:             push(@{$codetitles},&str2array($codetitles_str));
                   6346:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6347:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6348:             $ok_response = 1;
                   6349:         }
                   6350:     }
                   6351:     if ($ok_response) {
1.521     raeburn  6352:         return 'ok';
1.772     raeburn  6353:     } else {
                   6354:         return $response;
1.521     raeburn  6355:     }
                   6356: }
                   6357: 
1.792     raeburn  6358: sub auto_instcode_defaults {
                   6359:     my ($domain,$returnhash,$code_order) = @_;
                   6360:     my @homeservers;
1.841     albertel 6361: 
                   6362:     my %servers = &get_servers($domain,'library');
                   6363:     foreach my $tryserver (keys(%servers)) {
                   6364: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6365: 	    push(@homeservers,$tryserver);
                   6366: 	}
1.792     raeburn  6367:     }
1.841     albertel 6368: 
1.792     raeburn  6369:     my $response;
1.841     albertel 6370:     foreach my $server (@homeservers) {
1.792     raeburn  6371:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6372:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6373: 	
                   6374: 	foreach my $pair (split(/\&/,$response)) {
                   6375: 	    my ($name,$value)=split(/\=/,$pair);
                   6376: 	    if ($name eq 'code_order') {
                   6377: 		@{$code_order} = split(/\&/,&unescape($value));
                   6378: 	    } else {
                   6379: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6380: 	    }
                   6381: 	}
                   6382: 	return 'ok';
1.792     raeburn  6383:     }
1.841     albertel 6384: 
                   6385:     return $response;
1.1003    raeburn  6386: }
                   6387: 
                   6388: sub auto_possible_instcodes {
1.1007    raeburn  6389:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6390:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6391:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6392:         return;
                   6393:     }
1.1003    raeburn  6394:     my (@homeservers,$uhome);
                   6395:     if (defined(&domain($domain,'primary'))) {
                   6396:         $uhome=&domain($domain,'primary');
                   6397:         push(@homeservers,&domain($domain,'primary'));
                   6398:     } else {
                   6399:         my %servers = &get_servers($domain,'library');
                   6400:         foreach my $tryserver (keys(%servers)) {
                   6401:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6402:                 push(@homeservers,$tryserver);
                   6403:             }
                   6404:         }
                   6405:     }
                   6406:     my $response;
                   6407:     foreach my $server (@homeservers) {
                   6408:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6409:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6410:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6411:             split(':',$response);
                   6412:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6413:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6414:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6415:             my ($name,$value)=split('=',$item);
                   6416:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6417:         }
                   6418:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6419:             my ($name,$value)=split('=',$item);
                   6420:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6421:         }
                   6422:         return 'ok';
                   6423:     }
                   6424:     return $response;
                   6425: }
1.792     raeburn  6426: 
1.1010    raeburn  6427: sub auto_courserequest_checks {
                   6428:     my ($dom) = @_;
1.1020    raeburn  6429:     my ($homeserver,%validations);
                   6430:     if ($dom =~ /^$match_domain$/) {
                   6431:         $homeserver = &domain($dom,'primary');
                   6432:     }
                   6433:     unless ($homeserver eq 'no_host') {
                   6434:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6435:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6436:             my @items = split(/&/,$response);
                   6437:             foreach my $item (@items) {
                   6438:                 my ($key,$value) = split('=',$item);
                   6439:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6440:             }
                   6441:         }
                   6442:     }
1.1010    raeburn  6443:     return %validations; 
                   6444: }
                   6445: 
1.1020    raeburn  6446: sub auto_courserequest_validation {
                   6447:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6448:     my ($homeserver,$response);
                   6449:     if ($dom =~ /^$match_domain$/) {
                   6450:         $homeserver = &domain($dom,'primary');
                   6451:     }
                   6452:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6453:           
1.1020    raeburn  6454:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6455:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6456:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6457:                                     $homeserver));
                   6458:     }
                   6459:     return $response;
                   6460: }
                   6461: 
1.777     albertel 6462: sub auto_validate_class_sec {
1.918     raeburn  6463:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6464:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6465:     my $ownerlist;
                   6466:     if (ref($owners) eq 'ARRAY') {
                   6467:         $ownerlist = join(',',@{$owners});
                   6468:     } else {
                   6469:         $ownerlist = $owners;
                   6470:     }
1.773     raeburn  6471:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6472:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6473:     return $response;
                   6474: }
                   6475: 
1.679     raeburn  6476: # ------------------------------------------------------- Course Group routines
                   6477: 
                   6478: sub get_coursegroups {
1.809     raeburn  6479:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6480:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6481: }
                   6482: 
1.679     raeburn  6483: sub modify_coursegroup {
                   6484:     my ($cdom,$cnum,$groupsettings) = @_;
                   6485:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6486: }
                   6487: 
1.809     raeburn  6488: sub toggle_coursegroup_status {
                   6489:     my ($cdom,$cnum,$group,$action) = @_;
                   6490:     my ($from_namespace,$to_namespace);
                   6491:     if ($action eq 'delete') {
                   6492:         $from_namespace = 'coursegroups';
                   6493:         $to_namespace = 'deleted_groups';
                   6494:     } else {
                   6495:         $from_namespace = 'deleted_groups';
                   6496:         $to_namespace = 'coursegroups';
                   6497:     }
                   6498:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6499:     if (my $tmp = &error(%curr_group)) {
                   6500:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6501:         return ('read error',$tmp);
                   6502:     } else {
                   6503:         my %savedsettings = %curr_group; 
1.809     raeburn  6504:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6505:         my $deloutcome;
                   6506:         if ($result eq 'ok') {
1.809     raeburn  6507:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6508:         } else {
                   6509:             return ('write error',$result);
                   6510:         }
                   6511:         if ($deloutcome eq 'ok') {
                   6512:             return 'ok';
                   6513:         } else {
                   6514:             return ('delete error',$deloutcome);
                   6515:         }
                   6516:     }
                   6517: }
                   6518: 
1.679     raeburn  6519: sub modify_group_roles {
1.957     raeburn  6520:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6521:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6522:     my $role = 'gr/'.&escape($userprivs);
                   6523:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6524:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6525:     if ($result eq 'ok') {
                   6526:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6527:     }
1.679     raeburn  6528:     return $result;
                   6529: }
                   6530: 
                   6531: sub modify_coursegroup_membership {
                   6532:     my ($cdom,$cnum,$membership) = @_;
                   6533:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6534:     return $result;
                   6535: }
                   6536: 
1.682     raeburn  6537: sub get_active_groups {
                   6538:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6539:     my $now = time;
                   6540:     my %groups = ();
                   6541:     foreach my $key (keys(%env)) {
1.811     albertel 6542:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6543:             my ($start,$end) = split(/\./,$env{$key});
                   6544:             if (($end!=0) && ($end<$now)) { next; }
                   6545:             if (($start!=0) && ($start>$now)) { next; }
                   6546:             if ($1 eq $cdom && $2 eq $cnum) {
                   6547:                 $groups{$3} = $env{$key} ;
                   6548:             }
                   6549:         }
                   6550:     }
                   6551:     return %groups;
                   6552: }
                   6553: 
1.683     raeburn  6554: sub get_group_membership {
                   6555:     my ($cdom,$cnum,$group) = @_;
                   6556:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6557: }
                   6558: 
                   6559: sub get_users_groups {
                   6560:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6561:     my @usersgroups;
1.683     raeburn  6562:     my $cachetime=1800;
                   6563: 
                   6564:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6565:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6566:     if (defined($cached)) {
1.734     albertel 6567:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6568:     } else {  
                   6569:         $grouplist = '';
1.816     raeburn  6570:         my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10  raeburn  6571:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6572:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6573:         my $access_end = $env{'course.'.$courseid.
                   6574:                               '.default_enrollment_end_date'};
                   6575:         my $now = time;
                   6576:         foreach my $key (keys(%roleshash)) {
                   6577:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6578:                 my $group = $1;
                   6579:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6580:                     my $start = $2;
                   6581:                     my $end = $1;
                   6582:                     if ($start == -1) { next; } # deleted from group
                   6583:                     if (($start!=0) && ($start>$now)) { next; }
                   6584:                     if (($end!=0) && ($end<$now)) {
                   6585:                         if ($access_end && $access_end < $now) {
                   6586:                             if ($access_end - $end < 86400) {
                   6587:                                 push(@usersgroups,$group);
1.733     raeburn  6588:                             }
                   6589:                         }
1.817     raeburn  6590:                         next;
1.733     raeburn  6591:                     }
1.817     raeburn  6592:                     push(@usersgroups,$group);
1.683     raeburn  6593:                 }
                   6594:             }
                   6595:         }
1.817     raeburn  6596:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6597:         $grouplist = join(':',@usersgroups);
                   6598:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6599:     }
1.733     raeburn  6600:     return @usersgroups;
1.683     raeburn  6601: }
                   6602: 
                   6603: sub devalidate_getgroups_cache {
                   6604:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6605:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6606: 
1.683     raeburn  6607:     my $hashid="$udom:$uname:$courseid";
                   6608:     &devalidate_cache_new('getgroups',$hashid);
                   6609: }
                   6610: 
1.12      www      6611: # ------------------------------------------------------------------ Plain Text
                   6612: 
                   6613: sub plaintext {
1.988     raeburn  6614:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6615:     if ($short =~ m{^cr/}) {
1.758     albertel 6616: 	return (split('/',$short))[-1];
                   6617:     }
1.742     raeburn  6618:     if (!defined($cid)) {
                   6619:         $cid = $env{'request.course.id'};
                   6620:     }
                   6621:     my %rolenames = (
1.1008    raeburn  6622:                       Course    => 'std',
                   6623:                       Community => 'alt1',
1.742     raeburn  6624:                     );
1.1037    raeburn  6625:     if ($cid ne '') {
                   6626:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6627:             unless ($forcedefault) {
                   6628:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6629:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6630:                 return &Apache::lonlocal::mt($roletext);
                   6631:             }
                   6632:         }
                   6633:     }
                   6634:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6635:         (defined($rolenames{$type})) && 
                   6636:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6637:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6638:     } elsif ($cid ne '') {
                   6639:         my $crstype = $env{'course.'.$cid.'.type'};
                   6640:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6641:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6642:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6643:         }
1.742     raeburn  6644:     }
1.1037    raeburn  6645:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6646: }
                   6647: 
                   6648: # ----------------------------------------------------------------- Assign Role
                   6649: 
                   6650: sub assignrole {
1.957     raeburn  6651:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6652:         $context)=@_;
1.21      www      6653:     my $mrole;
                   6654:     if ($role =~ /^cr\//) {
1.393     www      6655:         my $cwosec=$url;
1.811     albertel 6656:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6657: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6658:            my $refused = 1;
                   6659:            if ($context eq 'requestcourses') {
                   6660:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6661:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6662:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6663:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6664:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6665:                            if ($crsenv{'internal.courseowner'} eq
                   6666:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6667:                                $refused = '';
                   6668:                            }
                   6669:                        }
                   6670:                    }
                   6671:                }
                   6672:            }
                   6673:            if ($refused) {
                   6674:                &logthis('Refused custom assignrole: '.
                   6675:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6676:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6677:                return 'refused';
                   6678:            }
1.104     www      6679:         }
1.21      www      6680:         $mrole='cr';
1.678     raeburn  6681:     } elsif ($role =~ /^gr\//) {
                   6682:         my $cwogrp=$url;
1.811     albertel 6683:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6684:         unless (&allowed('mdg',$cwogrp)) {
                   6685:             &logthis('Refused group assignrole: '.
                   6686:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6687:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6688:             return 'refused';
                   6689:         }
                   6690:         $mrole='gr';
1.21      www      6691:     } else {
1.82      www      6692:         my $cwosec=$url;
1.811     albertel 6693:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6694:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6695:             my $refused;
                   6696:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6697:                 if (!(&allowed('c'.$role,$url))) {
                   6698:                     $refused = 1;
                   6699:                 }
                   6700:             } else {
                   6701:                 $refused = 1;
                   6702:             }
1.947     raeburn  6703:             if ($refused) {
1.1045    raeburn  6704:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6705:                 if (!$selfenroll && $context eq 'course') {
                   6706:                     my %crsenv;
                   6707:                     if ($role eq 'cc' || $role eq 'co') {
                   6708:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6709:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6710:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6711:                                 if ($crsenv{'internal.courseowner'} eq 
                   6712:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6713:                                     $refused = '';
                   6714:                                 }
                   6715:                             }
                   6716:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6717:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6718:                                 if ($crsenv{'internal.courseowner'} eq 
                   6719:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6720:                                     $refused = '';
                   6721:                                 }
                   6722:                             }
                   6723:                         }
                   6724:                     }
                   6725:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6726:                     $refused = '';
1.1017    raeburn  6727:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6728:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6729:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6730:                         my $wrongcc;
                   6731:                         if ($cnum =~ /^$match_community$/) {
                   6732:                             $wrongcc = 1 if ($role eq 'cc');
                   6733:                         } else {
                   6734:                             $wrongcc = 1 if ($role eq 'co');
                   6735:                         }
                   6736:                         unless ($wrongcc) {
                   6737:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6738:                             if ($crsenv{'internal.courseowner'} eq 
                   6739:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6740:                                 $refused = '';
                   6741:                             }
1.1017    raeburn  6742:                         }
                   6743:                     }
                   6744:                 }
                   6745:                 if ($refused) {
1.947     raeburn  6746:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6747:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6748: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6749:                     return 'refused';
                   6750:                 }
1.932     raeburn  6751:             }
1.1056.4.30  raeburn  6752:         } elsif ($role eq 'au') {
                   6753:             if ($url ne '/'.$udom.'/') {
                   6754:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   6755:                          ' to assign author role for '.$uname.':'.$udom.
                   6756:                          ' in domain: '.$url.' refused (wrong domain).');
                   6757:                 return 'refused';
                   6758:             }
1.104     www      6759:         }
1.21      www      6760:         $mrole=$role;
                   6761:     }
1.620     albertel 6762:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6763:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6764:     if ($end) { $command.='_'.$end; }
1.21      www      6765:     if ($start) {
                   6766: 	if ($end) { 
1.81      www      6767:            $command.='_'.$start; 
1.21      www      6768:         } else {
1.81      www      6769:            $command.='_0_'.$start;
1.21      www      6770:         }
                   6771:     }
1.739     raeburn  6772:     my $origstart = $start;
                   6773:     my $origend = $end;
1.957     raeburn  6774:     my $delflag;
1.357     www      6775: # actually delete
                   6776:     if ($deleteflag) {
1.373     www      6777: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6778: # modify command to delete the role
1.620     albertel 6779:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6780:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6781: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6782: # set start and finish to negative values for userrolelog
                   6783:            $start=-1;
                   6784:            $end=-1;
1.957     raeburn  6785:            $delflag = 1;
1.357     www      6786:         }
                   6787:     }
                   6788: # send command
1.349     www      6789:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6790: # log new user role if status is ok
1.349     www      6791:     if ($answer eq 'ok') {
1.663     raeburn  6792: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6793: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6794:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6795:         unless ($role =~ /^gr/) {
                   6796:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6797:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6798:         }
1.1053    raeburn  6799:         if ($role eq 'cc') {
                   6800:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   6801:         }
1.349     www      6802:     }
                   6803:     return $answer;
1.169     harris41 6804: }
                   6805: 
1.1053    raeburn  6806: sub autoupdate_coowners {
                   6807:     my ($url,$end,$start,$uname,$udom) = @_;
                   6808:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   6809:     if (($cdom ne '') && ($cnum ne '')) {
                   6810:         my $now = time;
                   6811:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   6812:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   6813:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   6814:             my $instcode = $coursehash{'internal.coursecode'};
                   6815:             if ($instcode ne '') {
1.1056    raeburn  6816:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   6817:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  6818:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  6819:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   6820:                         if ($result eq 'valid') {
                   6821:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  6822:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6823:                                     push(@newcoowners,$coowner);
                   6824:                                 }
                   6825:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   6826:                                     push(@newcoowners,$uname.':'.$udom);
                   6827:                                 }
                   6828:                                 @newcoowners = sort(@newcoowners);
                   6829:                             } else {
                   6830:                                 push(@newcoowners,$uname.':'.$udom);
                   6831:                             }
                   6832:                         } else {
                   6833:                             if ($coursehash{'internal.co-owners'}) {
                   6834:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   6835:                                     unless ($coowner eq $uname.':'.$udom) {
                   6836:                                         push(@newcoowners,$coowner);
                   6837:                                     }
                   6838:                                 }
                   6839:                                 unless (@newcoowners > 0) {
                   6840:                                     $delcoowners = 1;
                   6841:                                     $coowners = '';
                   6842:                                 }
                   6843:                             }
                   6844:                         }
                   6845:                         if (@newcoowners || $delcoowners) {
                   6846:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   6847:                                             $delcoowners,@newcoowners);
                   6848:                         }
                   6849:                     }
                   6850:                 }
                   6851:             }
                   6852:         }
                   6853:     }
                   6854: }
                   6855: 
                   6856: sub store_coowners {
                   6857:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   6858:     my $cid = $cdom.'_'.$cnum;
                   6859:     my ($coowners,$delresult,$putresult);
                   6860:     if (@newcoowners) {
                   6861:         $coowners = join(',',@newcoowners);
                   6862:         my %coownershash = (
                   6863:                             'internal.co-owners' => $coowners,
                   6864:                            );
                   6865:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   6866:         if ($putresult eq 'ok') {
                   6867:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   6868:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   6869:             }
                   6870:         }
                   6871:     }
                   6872:     if ($delcoowners) {
                   6873:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   6874:         if ($delresult eq 'ok') {
                   6875:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   6876:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   6877:             }
                   6878:         }
                   6879:     }
                   6880:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   6881:         my %crsinfo =
                   6882:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6883:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   6884:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   6885:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   6886:         }
                   6887:     }
                   6888: }
                   6889: 
1.169     harris41 6890: # -------------------------------------------------- Modify user authentication
1.197     www      6891: # Overrides without validation
                   6892: 
1.169     harris41 6893: sub modifyuserauth {
                   6894:     my ($udom,$uname,$umode,$upass)=@_;
                   6895:     my $uhome=&homeserver($uname,$udom);
1.197     www      6896:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6897:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6898:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6899:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6900:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6901: 		     &escape($upass),$uhome);
1.620     albertel 6902:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6903:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6904:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6905:     &log($udom,,$uname,$uhome,
1.620     albertel 6906:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6907:                                      $env{'user.name'}.', '.$umode.
1.197     www      6908:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6909:     unless ($reply eq 'ok') {
1.197     www      6910:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6911: 	return 'error: '.$reply;
                   6912:     }   
1.170     harris41 6913:     return 'ok';
1.80      www      6914: }
                   6915: 
1.81      www      6916: # --------------------------------------------------------------- Modify a user
1.80      www      6917: 
1.81      www      6918: sub modifyuser {
1.206     matthew  6919:     my ($udom,    $uname, $uid,
                   6920:         $umode,   $upass, $first,
                   6921:         $middle,  $last,  $gene,
1.1056.4.1  raeburn  6922:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 6923:     $udom= &LONCAPA::clean_domain($udom);
                   6924:     $uname=&LONCAPA::clean_username($uname);
1.1056.4.1  raeburn  6925:     my $showcandelete = 'none';
                   6926:     if (ref($candelete) eq 'ARRAY') {
                   6927:         if (@{$candelete} > 0) {
                   6928:             $showcandelete = join(', ',@{$candelete});
                   6929:         }
                   6930:     }
1.81      www      6931:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6932:              $umode.', '.$first.', '.$middle.', '.
1.1056.4.1  raeburn  6933:              $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  6934:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6935:                                      ' desiredhome not specified'). 
1.620     albertel 6936:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6937:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6938:     my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4  raeburn  6939:     my $newuser;
                   6940:     if ($uhome eq 'no_host') {
                   6941:         $newuser = 1;
                   6942:     }
1.80      www      6943: # ----------------------------------------------------------------- Create User
1.406     albertel 6944:     if (($uhome eq 'no_host') && 
                   6945: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6946:         my $unhome='';
1.844     albertel 6947:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6948:             $unhome = $desiredhome;
1.620     albertel 6949: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6950: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6951:         } else { # load balancing routine for determining $unhome
1.81      www      6952:             my $loadm=10000000;
1.841     albertel 6953: 	    my %servers = &get_servers($udom,'library');
                   6954: 	    foreach my $tryserver (keys(%servers)) {
                   6955: 		my $answer=reply('load',$tryserver);
                   6956: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6957: 		    $loadm=$answer;
                   6958: 		    $unhome=$tryserver;
                   6959: 		}
1.80      www      6960: 	    }
                   6961:         }
                   6962:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6963: 	    return 'error: unable to find a home server for '.$uname.
                   6964:                    ' in domain '.$udom;
1.80      www      6965:         }
                   6966:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6967:                          &escape($upass),$unhome);
                   6968: 	unless ($reply eq 'ok') {
                   6969:             return 'error: '.$reply;
                   6970:         }   
1.230     stredwic 6971:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6972:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6973: 	    return 'error: unable verify users home machine.';
1.80      www      6974:         }
1.209     matthew  6975:     }   # End of creation of new user
1.80      www      6976: # ---------------------------------------------------------------------- Add ID
                   6977:     if ($uid) {
                   6978:        $uid=~tr/A-Z/a-z/;
                   6979:        my %uidhash=&idrget($udom,$uname);
1.196     www      6980:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6981:          && (!$forceid)) {
1.80      www      6982: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6983: 	      return 'error: user id "'.$uid.'" does not match '.
                   6984:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6985:           }
                   6986:        } else {
                   6987: 	  &idput($udom,($uname => $uid));
                   6988:        }
                   6989:     }
                   6990: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6991:     my @tmp=&get('environment',
1.899     raeburn  6992: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6993:                     'permanentemail','inststatus'],
1.134     albertel 6994: 		   $udom,$uname);
1.1056.4.4  raeburn  6995:     my (%names,%oldnames);
1.313     matthew  6996:     if ($tmp[0] =~ m/^error:.*/) { 
                   6997:         %names=(); 
                   6998:     } else {
                   6999:         %names = @tmp;
1.1056.4.4  raeburn  7000:         %oldnames = %names;
1.313     matthew  7001:     }
1.1056.4.6  raeburn  7002: #
1.1056.4.1  raeburn  7003: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7004: # of users did not contain them), do not overwrite existing values
                   7005: # unless field is in $candelete array ref.  
                   7006: #
                   7007: 
                   7008:     my @fields = ('firstname','middlename','lastname','generation',
                   7009:                   'permanentemail','id');
                   7010:     my %newvalues;
                   7011:     if (ref($candelete) eq 'ARRAY') {
                   7012:         foreach my $field (@fields) {
                   7013:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7014:                 if ($field eq 'firstname') {
                   7015:                     $names{$field} = $first;
                   7016:                 } elsif ($field eq 'middlename') {
                   7017:                     $names{$field} = $middle;
                   7018:                 } elsif ($field eq 'lastname') {
                   7019:                     $names{$field} = $last;
                   7020:                 } elsif ($field eq 'generation') { 
                   7021:                     $names{$field} = $gene;
                   7022:                 } elsif ($field eq 'permanentemail') {
                   7023:                     $names{$field} = $email;
                   7024:                 } elsif ($field eq 'id') {
                   7025:                     $names{$field}  = $uid;
                   7026:                 }
                   7027:             }
                   7028:         }
                   7029:     }
1.388     www      7030:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7031:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7032:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7033:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7034:     if ($email) {
                   7035:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7036:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7037:     }
1.899     raeburn  7038:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7039:     if (defined($inststatus)) {
                   7040:         $names{'inststatus'} = '';
                   7041:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7042:         if (ref($usertypes) eq 'HASH') {
                   7043:             my @okstatuses; 
                   7044:             foreach my $item (split(/:/,$inststatus)) {
                   7045:                 if (defined($usertypes->{$item})) {
                   7046:                     push(@okstatuses,$item);  
                   7047:                 }
                   7048:             }
                   7049:             if (@okstatuses) {
                   7050:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7051:             }
                   7052:         }
                   7053:     }
1.1056.4.4  raeburn  7054:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7055:                  $umode.', '.$first.', '.$middle.', '.
1.1056.4.4  raeburn  7056:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7057:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7058:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7059:     } else {
                   7060:         $logmsg .= ' during self creation';
                   7061:     }
1.1056.4.4  raeburn  7062:     my $changed;
                   7063:     if ($newuser) {
                   7064:         $changed = 1;
                   7065:     } else {
                   7066:         foreach my $field (@fields) {
                   7067:             if ($names{$field} ne $oldnames{$field}) {
                   7068:                 $changed = 1;
                   7069:                 last;
                   7070:             }
                   7071:         }
                   7072:     }
                   7073:     unless ($changed) {
                   7074:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7075:         &logthis($logmsg);
                   7076:         return 'ok';
                   7077:     }
                   7078:     my $reply = &put('environment', \%names, $udom,$uname);
                   7079:     if ($reply ne 'ok') {
                   7080:         return 'error: '.$reply;
                   7081:     }
1.1056.4.11  raeburn  7082:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7083:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7084:     }
1.1056.4.4  raeburn  7085:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7086:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7087:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7088:     &logthis($logmsg);
1.134     albertel 7089:     return 'ok';
1.80      www      7090: }
                   7091: 
1.81      www      7092: # -------------------------------------------------------------- Modify student
1.80      www      7093: 
1.81      www      7094: sub modifystudent {
                   7095:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7096:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7097:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7098:     if (!$cid) {
1.620     albertel 7099: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7100: 	    return 'not_in_class';
                   7101: 	}
1.80      www      7102:     }
                   7103: # --------------------------------------------------------------- Make the user
1.81      www      7104:     my $reply=&modifyuser
1.209     matthew  7105: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7106:          $desiredhome,$email,$inststatus);
1.80      www      7107:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7108:     # This will cause &modify_student_enrollment to get the uid from the
                   7109:     # students environment
                   7110:     $uid = undef if (!$forceid);
1.455     albertel 7111:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7112: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7113:     return $reply;
                   7114: }
                   7115: 
                   7116: sub modify_student_enrollment {
1.957     raeburn  7117:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7118:     my ($cdom,$cnum,$chome);
                   7119:     if (!$cid) {
1.620     albertel 7120: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7121: 	    return 'not_in_class';
                   7122: 	}
1.620     albertel 7123: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7124: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7125:     } else {
                   7126: 	($cdom,$cnum)=split(/_/,$cid);
                   7127:     }
1.620     albertel 7128:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7129:     if (!$chome) {
1.457     raeburn  7130: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7131:     }
1.455     albertel 7132:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7133:     # Make sure the user exists
1.81      www      7134:     my $uhome=&homeserver($uname,$udom);
                   7135:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7136: 	return 'error: no such user';
                   7137:     }
1.297     matthew  7138:     # Get student data if we were not given enough information
                   7139:     if (!defined($first)  || $first  eq '' || 
                   7140:         !defined($last)   || $last   eq '' || 
                   7141:         !defined($uid)    || $uid    eq '' || 
                   7142:         !defined($middle) || $middle eq '' || 
                   7143:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7144:         # They did not supply us with enough data to enroll the student, so
                   7145:         # we need to pick up more information.
1.297     matthew  7146:         my %tmp = &get('environment',
1.294     matthew  7147:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7148:                        ,$udom,$uname);
                   7149: 
1.800     albertel 7150:         #foreach my $key (keys(%tmp)) {
                   7151:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7152:         #}
1.294     matthew  7153:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7154:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7155:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7156:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7157:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7158:     }
1.556     albertel 7159:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7160:     my $reply=cput('classlist',
                   7161: 		   {"$uname:$udom" => 
1.515     raeburn  7162: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7163: 		   $cdom,$cnum);
1.81      www      7164:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7165: 	return 'error: '.$reply;
1.652     albertel 7166:     } else {
                   7167: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7168:     }
1.297     matthew  7169:     # Add student role to user
1.83      www      7170:     my $uurl='/'.$cid;
1.81      www      7171:     $uurl=~s/\_/\//g;
                   7172:     if ($usec) {
                   7173: 	$uurl.='/'.$usec;
                   7174:     }
1.957     raeburn  7175:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7176: }
                   7177: 
1.556     albertel 7178: sub format_name {
                   7179:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7180:     my $name;
                   7181:     if ($first ne 'lastname') {
                   7182: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7183:     } else {
                   7184: 	if ($lastname=~/\S/) {
                   7185: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7186: 	    $name=~s/\s+,/,/;
                   7187: 	} else {
                   7188: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7189: 	}
                   7190:     }
                   7191:     $name=~s/^\s+//;
                   7192:     $name=~s/\s+$//;
                   7193:     $name=~s/\s+/ /g;
                   7194:     return $name;
                   7195: }
                   7196: 
1.84      www      7197: # ------------------------------------------------- Write to course preferences
                   7198: 
                   7199: sub writecoursepref {
                   7200:     my ($courseid,%prefs)=@_;
                   7201:     $courseid=~s/^\///;
                   7202:     $courseid=~s/\_/\//g;
                   7203:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7204:     my $chome=homeserver($cnum,$cdomain);
                   7205:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7206: 	return 'error: no such course';
                   7207:     }
                   7208:     my $cstring='';
1.800     albertel 7209:     foreach my $pref (keys(%prefs)) {
                   7210: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7211:     }
1.84      www      7212:     $cstring=~s/\&$//;
                   7213:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7214: }
                   7215: 
                   7216: # ---------------------------------------------------------- Make/modify course
                   7217: 
                   7218: sub createcourse {
1.741     raeburn  7219:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7220:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7221:     $url=&declutter($url);
                   7222:     my $cid='';
1.1028    raeburn  7223:     if ($context eq 'requestcourses') {
                   7224:         my $can_create = 0;
                   7225:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7226:         if ($udom eq $ownerdom) {
                   7227:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7228:                                   $context)) {
                   7229:                 $can_create = 1;
                   7230:             }
                   7231:         } else {
                   7232:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7233:                                            $category);
                   7234:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7235:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7236:                 if (@curr > 0) {
                   7237:                     my @options = qw(approval validate autolimit);
                   7238:                     my $optregex = join('|',@options);
                   7239:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7240:                         $can_create = 1;
                   7241:                     }
                   7242:                 }
                   7243:             }
                   7244:         }
                   7245:         if ($can_create) {
                   7246:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7247:                 unless (&allowed('ccc',$udom)) {
                   7248:                     return 'refused'; 
                   7249:                 }
1.1017    raeburn  7250:             }
                   7251:         } else {
                   7252:             return 'refused';
                   7253:         }
1.1028    raeburn  7254:     } elsif (!&allowed('ccc',$udom)) {
                   7255:         return 'refused';
1.84      www      7256:     }
1.1011    raeburn  7257: # --------------------------------------------------------------- Get Unique ID
                   7258:     my $uname;
                   7259:     if ($cnum =~ /^$match_courseid$/) {
                   7260:         my $chome=&homeserver($cnum,$udom,'true');
                   7261:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7262:             $uname = $cnum;
                   7263:         } else {
1.1038    raeburn  7264:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7265:         }
                   7266:     } else {
1.1038    raeburn  7267:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7268:     }
                   7269:     return $uname if ($uname =~ /^error/);
                   7270: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7271:     if (!defined($course_server)) {
                   7272:         if (defined(&domain($udom,'primary'))) {
                   7273:             $course_server = &domain($udom,'primary');
                   7274:         } else {
                   7275:             $course_server = $env{'user.home'}; 
                   7276:         }
                   7277:     }
                   7278:     my %host_servers =
                   7279:         &Apache::lonnet::get_servers($udom,'library');
                   7280:     unless ($host_servers{$course_server}) {
                   7281:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7282:     }
1.84      www      7283: # ------------------------------------------------------------- Make the course
                   7284:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7285:                       $course_server);
1.84      www      7286:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7287:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7288:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7289: 	return 'error: no such course';
                   7290:     }
1.271     www      7291: # ----------------------------------------------------------------- Course made
1.516     raeburn  7292: # log existence
1.1029    raeburn  7293:     my $now = time;
1.918     raeburn  7294:     my $newcourse = {
                   7295:                     $udom.'_'.$uname => {
1.921     raeburn  7296:                                      description => $description,
                   7297:                                      inst_code   => $inst_code,
                   7298:                                      owner       => $course_owner,
                   7299:                                      type        => $crstype,
1.1029    raeburn  7300:                                      creator     => $env{'user.name'}.':'.
                   7301:                                                     $env{'user.domain'},
                   7302:                                      created     => $now,
                   7303:                                      context     => $context,
1.918     raeburn  7304:                                                 },
                   7305:                     };
1.921     raeburn  7306:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7307: # set toplevel url
1.271     www      7308:     my $topurl=$url;
                   7309:     unless ($nonstandard) {
                   7310: # ------------------------------------------ For standard courses, make top url
                   7311:         my $mapurl=&clutter($url);
1.278     www      7312:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7313:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7314: <map>
                   7315: <resource id="1" type="start"></resource>
                   7316: <resource id="2" src="$mapurl"></resource>
                   7317: <resource id="3" type="finish"></resource>
                   7318: <link index="1" from="1" to="2"></link>
                   7319: <link index="2" from="2" to="3"></link>
                   7320: </map>
                   7321: ENDINITMAP
                   7322:         $topurl=&declutter(
1.638     albertel 7323:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7324:                           );
                   7325:     }
                   7326: # ----------------------------------------------------------- Write preferences
1.84      www      7327:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7328:                      ('description'              => $description,
                   7329:                       'url'                      => $topurl,
                   7330:                       'internal.creator'         => $env{'user.name'}.':'.
                   7331:                                                     $env{'user.domain'},
                   7332:                       'internal.created'         => $now,
                   7333:                       'internal.creationcontext' => $context)
                   7334:                     );
1.84      www      7335:     return '/'.$udom.'/'.$uname;
                   7336: }
                   7337: 
1.1011    raeburn  7338: # ------------------------------------------------------------------- Create ID
                   7339: sub generate_coursenum {
1.1038    raeburn  7340:     my ($udom,$crstype) = @_;
1.1011    raeburn  7341:     my $domdesc = &domain($udom);
                   7342:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7343:     my $first;
                   7344:     if ($crstype eq 'Community') {
                   7345:         $first = '0';
                   7346:     } else {
                   7347:         $first = int(1+rand(9)); 
                   7348:     } 
                   7349:     my $uname=$first.
1.1011    raeburn  7350:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7351:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7352:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7353: # ----------------------------------------------- Make sure that does not exist
                   7354:     my $uhome=&homeserver($uname,$udom,'true');
                   7355:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7356:         if ($crstype eq 'Community') {
                   7357:             $first = '0';
                   7358:         } else {
                   7359:             $first = int(1+rand(9));
                   7360:         }
                   7361:         $uname=$first.
1.1011    raeburn  7362:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7363:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7364:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7365:         $uhome=&homeserver($uname,$udom,'true');
                   7366:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7367:             return 'error: unable to generate unique course-ID';
                   7368:         }
                   7369:     }
                   7370:     return $uname;
                   7371: }
                   7372: 
1.813     albertel 7373: sub is_course {
                   7374:     my ($cdom,$cnum) = @_;
                   7375:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7376: 				undef,'.');
1.813     albertel 7377:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7378:         return 1;
                   7379:     }
                   7380:     return 0;
                   7381: }
                   7382: 
1.1015    raeburn  7383: sub store_userdata {
                   7384:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7385:     my $result;
1.1016    raeburn  7386:     if ($datakey ne '') {
1.1013    raeburn  7387:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7388:             if ($udom eq '' || $uname eq '') {
                   7389:                 $udom = $env{'user.domain'};
                   7390:                 $uname = $env{'user.name'};
                   7391:             }
                   7392:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7393:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7394:                 $result = 'error: no_host';
                   7395:             } else {
                   7396:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7397:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7398: 
                   7399:                 my $namevalue='';
                   7400:                 foreach my $key (keys(%{$storehash})) {
                   7401:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7402:                 }
                   7403:                 $namevalue=~s/\&$//;
1.1056.4.24  raeburn  7404:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7405:                                   $namevalue,$uhome);
1.1013    raeburn  7406:             }
                   7407:         } else {
                   7408:             $result = 'error: data to store was not a hash reference'; 
                   7409:         }
                   7410:     } else {
                   7411:         $result= 'error: invalid requestkey'; 
                   7412:     }
                   7413:     return $result;
                   7414: }
                   7415: 
1.21      www      7416: # ---------------------------------------------------------- Assign Custom Role
                   7417: 
                   7418: sub assigncustomrole {
1.957     raeburn  7419:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7420:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7421:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7422: }
                   7423: 
                   7424: # ----------------------------------------------------------------- Revoke Role
                   7425: 
                   7426: sub revokerole {
1.957     raeburn  7427:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7428:     my $now=time;
1.965     raeburn  7429:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7430: }
                   7431: 
                   7432: # ---------------------------------------------------------- Revoke Custom Role
                   7433: 
                   7434: sub revokecustomrole {
1.957     raeburn  7435:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7436:     my $now=time;
1.357     www      7437:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7438:            $deleteflag,$selfenroll,$context);
1.17      www      7439: }
                   7440: 
1.533     banghart 7441: # ------------------------------------------------------------ Disk usage
1.535     albertel 7442: sub diskusage {
1.955     raeburn  7443:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7444:     $directorypath =~ s/\/$//;
                   7445:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7446:                        .&escape($getpropath).':'.&escape($uname).':'
                   7447:                        .&escape($udom),homeserver($uname,$udom));
                   7448:     if ($listing eq 'unknown_cmd') {
                   7449:         if ($getpropath) {
                   7450:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7451:         }
                   7452:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7453:     }
1.514     albertel 7454:     return $listing;
1.512     banghart 7455: }
                   7456: 
1.566     banghart 7457: sub is_locked {
1.1056.4.17  raeburn  7458:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7459:     my @check;
                   7460:     my $is_locked;
1.1056.4.14  raeburn  7461:     push(@check,$file_name);
1.613     albertel 7462:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7463: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7464:     my ($tmp)=keys(%locked);
                   7465:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7466:     
1.566     banghart 7467:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7468:         $is_locked = 'false';
                   7469:         foreach my $entry (@{$locked{$file_name}}) {
1.1056.4.17  raeburn  7470:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7471:                $is_locked = 'true';
1.1056.4.17  raeburn  7472:                if (ref($which) eq 'ARRAY') {
                   7473:                    push(@{$which},$entry);
                   7474:                } else {
                   7475:                    last;
                   7476:                }
1.745     raeburn  7477:            }
                   7478:        }
1.566     banghart 7479:     } else {
                   7480:         $is_locked = 'false';
                   7481:     }
1.1056.4.14  raeburn  7482:     return $is_locked;
1.566     banghart 7483: }
                   7484: 
1.759     albertel 7485: sub declutter_portfile {
                   7486:     my ($file) = @_;
1.833     albertel 7487:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7488:     return $file;
                   7489: }
                   7490: 
1.559     banghart 7491: # ------------------------------------------------------------- Mark as Read Only
                   7492: 
                   7493: sub mark_as_readonly {
                   7494:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7495:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7496:     my ($tmp)=keys(%current_permissions);
                   7497:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7498:     foreach my $file (@{$files}) {
1.759     albertel 7499: 	$file = &declutter_portfile($file);
1.561     banghart 7500:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7501:     }
1.613     albertel 7502:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7503:     return;
                   7504: }
                   7505: 
1.572     banghart 7506: # ------------------------------------------------------------Save Selected Files
                   7507: 
                   7508: sub save_selected_files {
                   7509:     my ($user, $path, @files) = @_;
                   7510:     my $filename = $user."savedfiles";
1.573     banghart 7511:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7512:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7513:     foreach my $file (@files) {
1.620     albertel 7514:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7515:     }
                   7516:     foreach my $file (@other_files) {
1.574     banghart 7517:         print (OUT $file."\n");
1.572     banghart 7518:     }
1.574     banghart 7519:     close (OUT);
1.572     banghart 7520:     return 'ok';
                   7521: }
                   7522: 
1.574     banghart 7523: sub clear_selected_files {
                   7524:     my ($user) = @_;
                   7525:     my $filename = $user."savedfiles";
                   7526:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7527:     print (OUT undef);
                   7528:     close (OUT);
                   7529:     return ("ok");    
                   7530: }
                   7531: 
1.572     banghart 7532: sub files_in_path {
                   7533:     my ($user, $path) = @_;
                   7534:     my $filename = $user."savedfiles";
                   7535:     my %return_files;
1.574     banghart 7536:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 7537:     while (my $line_in = <IN>) {
1.574     banghart 7538:         chomp ($line_in);
                   7539:         my @paths_and_file = split (m!/!, $line_in);
                   7540:         my $file_part = pop (@paths_and_file);
                   7541:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7542:         $path_part.='/';
                   7543:         my $path_and_file = $path_part.$file_part;
                   7544:         if ($path_part eq $path) {
                   7545:             $return_files{$file_part}= 'selected';
                   7546:         }
                   7547:     }
1.574     banghart 7548:     close (IN);
                   7549:     return (\%return_files);
1.572     banghart 7550: }
                   7551: 
                   7552: # called in portfolio select mode, to show files selected NOT in current directory
                   7553: sub files_not_in_path {
                   7554:     my ($user, $path) = @_;
                   7555:     my $filename = $user."savedfiles";
                   7556:     my @return_files;
                   7557:     my $path_part;
1.800     albertel 7558:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   7559:     while (my $line = <IN>) {
1.572     banghart 7560:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7561:         my @paths_and_file = split(m|/|, $line);
                   7562:         my $file_part = pop(@paths_and_file);
                   7563:         chomp($file_part);
                   7564:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7565:         $path_part .= '/';
                   7566:         my $path_and_file = $path_part.$file_part;
                   7567:         if ($path_part ne $path) {
1.800     albertel 7568:             push(@return_files, ($path_and_file));
1.572     banghart 7569:         }
                   7570:     }
1.800     albertel 7571:     close(OUT);
1.574     banghart 7572:     return (@return_files);
1.572     banghart 7573: }
                   7574: 
1.745     raeburn  7575: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7576: 
1.745     raeburn  7577: sub get_portfile_permissions {
                   7578:     my ($domain,$user) = @_;
1.613     albertel 7579:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7580:     my ($tmp)=keys(%current_permissions);
                   7581:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7582:     return \%current_permissions;
                   7583: }
                   7584: 
                   7585: #---------------------------------------------Get portfolio file access controls
                   7586: 
1.749     raeburn  7587: sub get_access_controls {
1.745     raeburn  7588:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7589:     my %access;
                   7590:     my $real_file = $file;
                   7591:     $file =~ s/\.meta$//;
1.745     raeburn  7592:     if (defined($file)) {
1.749     raeburn  7593:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7594:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7595:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7596:             }
                   7597:         }
1.745     raeburn  7598:     } else {
1.749     raeburn  7599:         foreach my $key (keys(%{$current_permissions})) {
                   7600:             if ($key =~ /\0accesscontrol$/) {
                   7601:                 if (defined($group)) {
                   7602:                     if ($key !~ m-^\Q$group\E/-) {
                   7603:                         next;
                   7604:                     }
                   7605:                 }
                   7606:                 my ($fullpath) = split(/\0/,$key);
                   7607:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7608:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7609:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7610:                     }
                   7611:                 }
                   7612:             }
                   7613:         }
                   7614:     }
                   7615:     return %access;
                   7616: }
                   7617: 
                   7618: sub modify_access_controls {
                   7619:     my ($file_name,$changes,$domain,$user)=@_;
                   7620:     my ($outcome,$deloutcome);
                   7621:     my %store_permissions;
                   7622:     my %new_values;
                   7623:     my %new_control;
                   7624:     my %translation;
                   7625:     my @deletions = ();
                   7626:     my $now = time;
                   7627:     if (exists($$changes{'activate'})) {
                   7628:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7629:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7630:             my $numnew = scalar(@newitems);
                   7631:             for (my $i=0; $i<$numnew; $i++) {
                   7632:                 my $newkey = $newitems[$i];
                   7633:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7634:                 if ($newkey =~ /^\d+:/) { 
                   7635:                     $newkey =~ s/^(\d+)/$newid/;
                   7636:                     $translation{$1} = $newid;
                   7637:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7638:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7639:                     $translation{$1} = $newid;
                   7640:                 }
1.749     raeburn  7641:                 $new_values{$file_name."\0".$newkey} = 
                   7642:                                           $$changes{'activate'}{$newitems[$i]};
                   7643:                 $new_control{$newkey} = $now;
                   7644:             }
                   7645:         }
                   7646:     }
                   7647:     my %todelete;
                   7648:     my %changed_items;
                   7649:     foreach my $action ('delete','update') {
                   7650:         if (exists($$changes{$action})) {
                   7651:             if (ref($$changes{$action}) eq 'HASH') {
                   7652:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7653:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7654:                     if ($action eq 'delete') { 
                   7655:                         $todelete{$itemnum} = 1;
                   7656:                     } else {
                   7657:                         $changed_items{$itemnum} = $key;
                   7658:                     }
                   7659:                 }
1.745     raeburn  7660:             }
                   7661:         }
1.749     raeburn  7662:     }
                   7663:     # get lock on access controls for file.
                   7664:     my $lockhash = {
                   7665:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7666:                                                        ':'.$env{'user.domain'},
                   7667:                    }; 
                   7668:     my $tries = 0;
                   7669:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7670:    
                   7671:     while (($gotlock ne 'ok') && $tries <3) {
                   7672:         $tries ++;
                   7673:         sleep 1;
                   7674:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7675:     }
                   7676:     if ($gotlock eq 'ok') {
                   7677:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7678:         my ($tmp)=keys(%curr_permissions);
                   7679:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7680:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7681:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7682:             if (ref($curr_controls) eq 'HASH') {
                   7683:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7684:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7685:                     if (defined($todelete{$itemnum})) {
                   7686:                         push(@deletions,$file_name."\0".$control_item);
                   7687:                     } else {
                   7688:                         if (defined($changed_items{$itemnum})) {
                   7689:                             $new_control{$changed_items{$itemnum}} = $now;
                   7690:                             push(@deletions,$file_name."\0".$control_item);
                   7691:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7692:                         } else {
                   7693:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7694:                         }
                   7695:                     }
1.745     raeburn  7696:                 }
                   7697:             }
                   7698:         }
1.970     raeburn  7699:         my ($group);
                   7700:         if (&is_course($domain,$user)) {
                   7701:             ($group,my $file) = split(/\//,$file_name,2);
                   7702:         }
1.749     raeburn  7703:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7704:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7705:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7706:         #  remove lock
                   7707:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7708:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7709:         my $sqlresult =
1.970     raeburn  7710:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7711:                                     $group);
1.749     raeburn  7712:     } else {
                   7713:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7714:     }
1.749     raeburn  7715:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7716: }
                   7717: 
1.827     raeburn  7718: sub make_public_indefinitely {
                   7719:     my ($requrl) = @_;
                   7720:     my $now = time;
                   7721:     my $action = 'activate';
                   7722:     my $aclnum = 0;
                   7723:     if (&is_portfolio_url($requrl)) {
                   7724:         my (undef,$udom,$unum,$file_name,$group) =
                   7725:             &parse_portfolio_url($requrl);
                   7726:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7727:         my %access_controls = &get_access_controls($current_perms,
                   7728:                                                    $group,$file_name);
                   7729:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7730:             my ($num,$scope,$end,$start) = 
                   7731:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7732:             if ($scope eq 'public') {
                   7733:                 if ($start <= $now && $end == 0) {
                   7734:                     $action = 'none';
                   7735:                 } else {
                   7736:                     $action = 'update';
                   7737:                     $aclnum = $num;
                   7738:                 }
                   7739:                 last;
                   7740:             }
                   7741:         }
                   7742:         if ($action eq 'none') {
                   7743:              return 'ok';
                   7744:         } else {
                   7745:             my %changes;
                   7746:             my $newend = 0;
                   7747:             my $newstart = $now;
                   7748:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7749:             $changes{$action}{$newkey} = {
                   7750:                 type => 'public',
                   7751:                 time => {
                   7752:                     start => $newstart,
                   7753:                     end   => $newend,
                   7754:                 },
                   7755:             };
                   7756:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7757:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7758:             return $outcome;
                   7759:         }
                   7760:     } else {
                   7761:         return 'invalid';
                   7762:     }
                   7763: }
                   7764: 
1.745     raeburn  7765: #------------------------------------------------------Get Marked as Read Only
                   7766: 
                   7767: sub get_marked_as_readonly {
                   7768:     my ($domain,$user,$what,$group) = @_;
                   7769:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7770:     my @readonly_files;
1.629     banghart 7771:     my $cmp1=$what;
                   7772:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7773:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7774:         if (defined($group)) {
                   7775:             if ($file_name !~ m-^\Q$group\E/-) {
                   7776:                 next;
                   7777:             }
                   7778:         }
1.561     banghart 7779:         if (ref($value) eq "ARRAY"){
                   7780:             foreach my $stored_what (@{$value}) {
1.629     banghart 7781:                 my $cmp2=$stored_what;
1.759     albertel 7782:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7783:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7784:                 }
1.629     banghart 7785:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7786:                     push(@readonly_files, $file_name);
1.745     raeburn  7787:                     last;
1.563     banghart 7788:                 } elsif (!defined($what)) {
                   7789:                     push(@readonly_files, $file_name);
1.745     raeburn  7790:                     last;
1.561     banghart 7791:                 }
                   7792:             }
1.745     raeburn  7793:         }
1.561     banghart 7794:     }
                   7795:     return @readonly_files;
                   7796: }
1.577     banghart 7797: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7798: 
1.577     banghart 7799: sub get_marked_as_readonly_hash {
1.745     raeburn  7800:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7801:     my %readonly_files;
1.745     raeburn  7802:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7803:         if (defined($group)) {
                   7804:             if ($file_name !~ m-^\Q$group\E/-) {
                   7805:                 next;
                   7806:             }
                   7807:         }
1.577     banghart 7808:         if (ref($value) eq "ARRAY"){
                   7809:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7810:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7811:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7812:                         if ($lock_descriptor eq 'graded') {
                   7813:                             $readonly_files{$file_name} = 'graded';
                   7814:                         } elsif ($lock_descriptor eq 'handback') {
                   7815:                             $readonly_files{$file_name} = 'handback';
                   7816:                         } else {
                   7817:                             if (!exists($readonly_files{$file_name})) {
                   7818:                                 $readonly_files{$file_name} = 'locked';
                   7819:                             }
                   7820:                         }
1.745     raeburn  7821:                     }
1.750     banghart 7822:                 } 
1.577     banghart 7823:             }
                   7824:         } 
                   7825:     }
                   7826:     return %readonly_files;
                   7827: }
1.559     banghart 7828: # ------------------------------------------------------------ Unmark as Read Only
                   7829: 
                   7830: sub unmark_as_readonly {
1.629     banghart 7831:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7832:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7833:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7834:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7835:     my $symb_crs = $what;
                   7836:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7837:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7838:     my ($tmp)=keys(%current_permissions);
                   7839:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7840:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7841:     foreach my $file (@readonly_files) {
1.759     albertel 7842: 	my $clean_file = &declutter_portfile($file);
                   7843: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7844: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7845:         my @new_locks;
                   7846:         my @del_keys;
                   7847:         if (ref($current_locks) eq "ARRAY"){
                   7848:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7849:                 my $compare=$locker;
1.749     raeburn  7850:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7851:                     $compare=join('',@{$locker});
1.746     raeburn  7852:                     if ($compare ne $symb_crs) {
                   7853:                         push(@new_locks, $locker);
                   7854:                     }
1.563     banghart 7855:                 }
                   7856:             }
1.650     albertel 7857:             if (scalar(@new_locks) > 0) {
1.563     banghart 7858:                 $current_permissions{$file} = \@new_locks;
                   7859:             } else {
                   7860:                 push(@del_keys, $file);
1.613     albertel 7861:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7862:                 delete($current_permissions{$file});
1.563     banghart 7863:             }
                   7864:         }
1.561     banghart 7865:     }
1.613     albertel 7866:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7867:     return;
                   7868: }
1.512     banghart 7869: 
1.17      www      7870: # ------------------------------------------------------------ Directory lister
                   7871: 
                   7872: sub dirlist {
1.955     raeburn  7873:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7874:     $uri=~s/^\///;
                   7875:     $uri=~s/\/$//;
1.253     stredwic 7876:     my ($udom, $uname);
1.955     raeburn  7877:     if ($getuserdir) {
1.253     stredwic 7878:         $udom = $userdomain;
                   7879:         $uname = $username;
1.955     raeburn  7880:     } else {
                   7881:         (undef,$udom,$uname)=split(/\//,$uri);
                   7882:         if(defined($userdomain)) {
                   7883:             $udom = $userdomain;
                   7884:         }
                   7885:         if(defined($username)) {
                   7886:             $uname = $username;
                   7887:         }
1.253     stredwic 7888:     }
1.955     raeburn  7889:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7890: 
1.955     raeburn  7891:     $dirRoot = $perlvar{'lonDocRoot'};
                   7892:     if (defined($getpropath)) {
                   7893:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7894:         $dirRoot =~ s/\/$//;
1.955     raeburn  7895:     } elsif (defined($getuserdir)) {
                   7896:         my $subdir=$uname.'__';
                   7897:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7898:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7899:                    ."/$udom/$subdir/$uname";
                   7900:     } elsif (defined($alternateRoot)) {
                   7901:         $dirRoot = $alternateRoot;
1.751     banghart 7902:     }
1.253     stredwic 7903: 
                   7904:     if($udom) {
                   7905:         if($uname) {
1.955     raeburn  7906:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7907:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7908:                               .':'.&escape($uname).':'.&escape($udom),
                   7909:                               &homeserver($uname,$udom));
                   7910:             if ($listing eq 'unknown_cmd') {
                   7911:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7912:                                   &homeserver($uname,$udom));
                   7913:             } else {
                   7914:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7915:             }
1.605     matthew  7916:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7917:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7918: 				  &homeserver($uname,$udom));
1.605     matthew  7919:                 @listing_results = split(/:/,$listing);
                   7920:             } else {
                   7921:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7922:             }
                   7923:             return @listing_results;
1.955     raeburn  7924:         } elsif(!$alternateRoot) {
1.800     albertel 7925:             my %allusers;
1.841     albertel 7926: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7927:  	    foreach my $tryserver (keys(%servers)) {
                   7928:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7929:                                   &escape($udom),$tryserver);
                   7930:                 if ($listing eq 'unknown_cmd') {
                   7931: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7932: 				      $udom, $tryserver);
                   7933:                 } else {
                   7934:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7935:                 }
1.841     albertel 7936: 		if ($listing eq 'unknown_cmd') {
                   7937: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7938: 				      $udom, $tryserver);
                   7939: 		    @listing_results = split(/:/,$listing);
                   7940: 		} else {
                   7941: 		    @listing_results =
                   7942: 			map { &unescape($_); } split(/:/,$listing);
                   7943: 		}
                   7944: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7945: 		    $listing_results[0] ne 'empty'       &&
                   7946: 		    $listing_results[0] ne 'con_lost') {
                   7947: 		    foreach my $line (@listing_results) {
                   7948: 			my ($entry) = split(/&/,$line,2);
                   7949: 			$allusers{$entry} = 1;
                   7950: 		    }
                   7951: 		}
1.253     stredwic 7952:             }
                   7953:             my $alluserstr='';
1.800     albertel 7954:             foreach my $user (sort(keys(%allusers))) {
                   7955:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7956:             }
                   7957:             $alluserstr=~s/:$//;
                   7958:             return split(/:/,$alluserstr);
                   7959:         } else {
1.800     albertel 7960:             return ('missing user name');
1.253     stredwic 7961:         }
1.955     raeburn  7962:     } elsif(!defined($getpropath)) {
1.841     albertel 7963:         my @all_domains = sort(&all_domains());
1.955     raeburn  7964:         foreach my $domain (@all_domains) {
                   7965:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7966:         }
                   7967:         return @all_domains;
                   7968:     } else {
1.800     albertel 7969:         return ('missing domain');
1.275     stredwic 7970:     }
                   7971: }
                   7972: 
                   7973: # --------------------------------------------- GetFileTimestamp
                   7974: # This function utilizes dirlist and returns the date stamp for
                   7975: # when it was last modified.  It will also return an error of -1
                   7976: # if an error occurs
                   7977: 
                   7978: sub GetFileTimestamp {
1.955     raeburn  7979:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7980:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7981:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7982:     my ($fileStat) = 
                   7983:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7984:                                  undef,$getuserdir);
1.275     stredwic 7985:     my @stats = split('&', $fileStat);
                   7986:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7987:         # @stats contains first the filename, then the stat output
                   7988:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7989:     } else {
                   7990:         return -1;
1.253     stredwic 7991:     }
1.26      www      7992: }
                   7993: 
1.712     albertel 7994: sub stat_file {
                   7995:     my ($uri) = @_;
1.787     albertel 7996:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7997: 
1.955     raeburn  7998:     my ($udom,$uname,$file);
1.712     albertel 7999:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8000: 	($udom,$uname,$file) =
1.811     albertel 8001: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8002: 	$file = 'userfiles/'.$file;
                   8003:     }
                   8004:     if ($uri =~ m-^/res/-) {
                   8005: 	($udom,$uname) = 
1.807     albertel 8006: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8007: 	$file = $uri;
                   8008:     }
                   8009: 
                   8010:     if (!$udom || !$uname || !$file) {
                   8011: 	# unable to handle the uri
                   8012: 	return ();
                   8013:     }
1.956     raeburn  8014:     my $getpropath;
                   8015:     if ($file =~ /^userfiles\//) {
                   8016:         $getpropath = 1;
                   8017:     }
1.955     raeburn  8018:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8019:     my @stats = split('&', $result);
1.721     banghart 8020:     
1.712     albertel 8021:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8022: 	shift(@stats); #filename is first
                   8023: 	return @stats;
                   8024:     }
                   8025:     return ();
                   8026: }
                   8027: 
1.26      www      8028: # -------------------------------------------------------- Value of a Condition
                   8029: 
1.713     albertel 8030: # gets the value of a specific preevaluated condition
                   8031: #    stored in the string  $env{user.state.<cid>}
                   8032: # or looks up a condition reference in the bighash and if if hasn't
                   8033: # already been evaluated recurses into docondval to get the value of
                   8034: # the condition, then memoizing it to 
                   8035: #   $env{user.state.<cid>.<condition>}
1.40      www      8036: sub directcondval {
                   8037:     my $number=shift;
1.620     albertel 8038:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8039: 	&Apache::lonuserstate::evalstate();
                   8040:     }
1.713     albertel 8041:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8042: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8043:     } elsif ($number =~ /^_/) {
                   8044: 	my $sub_condition;
                   8045: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8046: 		&GDBM_READER(),0640)) {
                   8047: 	    $sub_condition=$bighash{'conditions'.$number};
                   8048: 	    untie(%bighash);
                   8049: 	}
                   8050: 	my $value = &docondval($sub_condition);
1.949     raeburn  8051: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8052: 	return $value;
                   8053:     }
1.620     albertel 8054:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8055:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8056:     } else {
                   8057:        return 2;
                   8058:     }
                   8059: }
                   8060: 
1.713     albertel 8061: # get the collection of conditions for this resource
1.26      www      8062: sub condval {
                   8063:     my $condidx=shift;
1.54      www      8064:     my $allpathcond='';
1.713     albertel 8065:     foreach my $cond (split(/\|/,$condidx)) {
                   8066: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8067: 	    $allpathcond.=
                   8068: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8069: 	}
1.191     harris41 8070:     }
1.54      www      8071:     $allpathcond=~s/\|$//;
1.713     albertel 8072:     return &docondval($allpathcond);
                   8073: }
                   8074: 
                   8075: #evaluates an expression of conditions
                   8076: sub docondval {
                   8077:     my ($allpathcond) = @_;
                   8078:     my $result=0;
                   8079:     if ($env{'request.course.id'}
                   8080: 	&& defined($allpathcond)) {
                   8081: 	my $operand='|';
                   8082: 	my @stack;
                   8083: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8084: 	    if ($chunk eq '(') {
                   8085: 		push @stack,($operand,$result);
                   8086: 	    } elsif ($chunk eq ')') {
                   8087: 		my $before=pop @stack;
                   8088: 		if (pop @stack eq '&') {
                   8089: 		    $result=$result>$before?$before:$result;
                   8090: 		} else {
                   8091: 		    $result=$result>$before?$result:$before;
                   8092: 		}
                   8093: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8094: 		$operand=$chunk;
                   8095: 	    } else {
                   8096: 		my $new=directcondval($chunk);
                   8097: 		if ($operand eq '&') {
                   8098: 		    $result=$result>$new?$new:$result;
                   8099: 		} else {
                   8100: 		    $result=$result>$new?$result:$new;
                   8101: 		}
                   8102: 	    }
                   8103: 	}
1.26      www      8104:     }
                   8105:     return $result;
1.421     albertel 8106: }
                   8107: 
                   8108: # ---------------------------------------------------- Devalidate courseresdata
                   8109: 
                   8110: sub devalidatecourseresdata {
                   8111:     my ($coursenum,$coursedomain)=@_;
                   8112:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8113:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8114: }
                   8115: 
1.763     www      8116: 
1.200     www      8117: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8118: #
                   8119: #  Parameters:
                   8120: #      $coursenum    - Number of the course.
                   8121: #      $coursedomain - Domain at which the course was created.
                   8122: #  Returns:
                   8123: #     A hash of the course parameters along (I think) with timestamps
                   8124: #     and version info.
1.877     foxr     8125: 
1.624     albertel 8126: sub get_courseresdata {
                   8127:     my ($coursenum,$coursedomain)=@_;
1.200     www      8128:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8129:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8130:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8131:     my %dumpreply;
1.417     albertel 8132:     unless (defined($cached)) {
1.624     albertel 8133: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8134: 	$result=\%dumpreply;
1.251     albertel 8135: 	my ($tmp) = keys(%dumpreply);
                   8136: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8137: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8138: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8139: 	    return $tmp;
1.416     albertel 8140: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8141: 	    $result=undef;
1.599     albertel 8142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8143: 	}
                   8144:     }
1.624     albertel 8145:     return $result;
                   8146: }
                   8147: 
1.633     albertel 8148: sub devalidateuserresdata {
                   8149:     my ($uname,$udom)=@_;
                   8150:     my $hashid="$udom:$uname";
                   8151:     &devalidate_cache_new('userres',$hashid);
                   8152: }
                   8153: 
1.624     albertel 8154: sub get_userresdata {
                   8155:     my ($uname,$udom)=@_;
                   8156:     #most student don\'t have any data set, check if there is some data
                   8157:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8158: 
                   8159:     my $hashid="$udom:$uname";
                   8160:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8161:     if (!defined($cached)) {
                   8162: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8163: 	$result=\%resourcedata;
                   8164: 	&do_cache_new('userres',$hashid,$result,600);
                   8165:     }
                   8166:     my ($tmp)=keys(%$result);
                   8167:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8168: 	return $result;
                   8169:     }
                   8170:     #error 2 occurs when the .db doesn't exist
                   8171:     if ($tmp!~/error: 2 /) {
1.672     albertel 8172: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8173: 		 " Trying to get resource data for ".
                   8174: 		 $uname." at ".$udom.": ".
                   8175: 		 $tmp."</font>");
                   8176:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8177: 	#&EXT_cache_set($udom,$uname);
                   8178: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8179: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8180:     }
                   8181:     return $tmp;
                   8182: }
1.879     foxr     8183: #----------------------------------------------- resdata - return resource data
                   8184: #  Purpose:
                   8185: #    Return resource data for either users or for a course.
                   8186: #  Parameters:
                   8187: #     $name      - Course/user name.
                   8188: #     $domain    - Name of the domain the user/course is registered on.
                   8189: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8190: #     @which     - Array of names of resources desired.
                   8191: #  Returns:
                   8192: #     The value of the first reasource in @which that is found in the
                   8193: #     resource hash.
                   8194: #  Exceptional Conditions:
                   8195: #     If the $type passed in is not valid (not the string 'course' or 
                   8196: #     'user', an undefined  reference is returned.
                   8197: #     If none of the resources are found, an undef is returned
1.624     albertel 8198: sub resdata {
                   8199:     my ($name,$domain,$type,@which)=@_;
                   8200:     my $result;
                   8201:     if ($type eq 'course') {
                   8202: 	$result=&get_courseresdata($name,$domain);
                   8203:     } elsif ($type eq 'user') {
                   8204: 	$result=&get_userresdata($name,$domain);
                   8205:     }
                   8206:     if (!ref($result)) { return $result; }    
1.251     albertel 8207:     foreach my $item (@which) {
1.927     albertel 8208: 	if (defined($result->{$item->[0]})) {
                   8209: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8210: 	}
1.250     albertel 8211:     }
1.291     albertel 8212:     return undef;
1.200     www      8213: }
                   8214: 
1.379     matthew  8215: #
                   8216: # EXT resource caching routines
                   8217: #
                   8218: 
                   8219: sub clear_EXT_cache_status {
1.383     albertel 8220:     &delenv('cache.EXT.');
1.379     matthew  8221: }
                   8222: 
                   8223: sub EXT_cache_status {
                   8224:     my ($target_domain,$target_user) = @_;
1.383     albertel 8225:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8226:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8227:         # We know already the user has no data
                   8228:         return 1;
                   8229:     } else {
                   8230:         return 0;
                   8231:     }
                   8232: }
                   8233: 
                   8234: sub EXT_cache_set {
                   8235:     my ($target_domain,$target_user) = @_;
1.383     albertel 8236:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8237:     #&appenv({$cachename => time});
1.379     matthew  8238: }
                   8239: 
1.28      www      8240: # --------------------------------------------------------- Value of a Variable
1.58      www      8241: sub EXT {
1.715     albertel 8242: 
1.395     albertel 8243:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8244:     unless ($varname) { return ''; }
1.218     albertel 8245:     #get real user name/domain, courseid and symb
                   8246:     my $courseid;
1.359     albertel 8247:     my $publicuser;
1.427     www      8248:     if ($symbparm) {
                   8249: 	$symbparm=&get_symb_from_alias($symbparm);
                   8250:     }
1.218     albertel 8251:     if (!($uname && $udom)) {
1.790     albertel 8252:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8253:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8254:     } else {
1.620     albertel 8255: 	$courseid=$env{'request.course.id'};
1.218     albertel 8256:     }
1.48      www      8257:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8258:     my $rest;
1.320     albertel 8259:     if (defined($therest[0])) {
1.48      www      8260:        $rest=join('.',@therest);
                   8261:     } else {
                   8262:        $rest='';
                   8263:     }
1.320     albertel 8264: 
1.57      www      8265:     my $qualifierrest=$qualifier;
                   8266:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8267:     my $spacequalifierrest=$space;
                   8268:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8269:     if ($realm eq 'user') {
1.48      www      8270: # --------------------------------------------------------------- user.resource
                   8271: 	if ($space eq 'resource') {
1.651     albertel 8272: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8273: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8274: 		 &&
1.744     albertel 8275: 		 ($symbparm eq &symbread()) ) {	
                   8276: 		# if we are in the middle of processing the resource the
                   8277: 		# get the value we are planning on committing
                   8278:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8279:                     return $Apache::lonhomework::results{$qualifierrest};
                   8280:                 } else {
                   8281:                     return $Apache::lonhomework::history{$qualifierrest};
                   8282:                 }
1.335     albertel 8283: 	    } else {
1.359     albertel 8284: 		my %restored;
1.620     albertel 8285: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8286: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8287: 		} else {
                   8288: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8289: 		}
1.335     albertel 8290: 		return $restored{$qualifierrest};
                   8291: 	    }
1.48      www      8292: # ----------------------------------------------------------------- user.access
                   8293:         } elsif ($space eq 'access') {
1.218     albertel 8294: 	    # FIXME - not supporting calls for a specific user
1.48      www      8295:             return &allowed($qualifier,$rest);
                   8296: # ------------------------------------------ user.preferences, user.environment
                   8297:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8298: 	    if (($uname eq $env{'user.name'}) &&
                   8299: 		($udom eq $env{'user.domain'})) {
                   8300: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8301: 	    } else {
1.359     albertel 8302: 		my %returnhash;
                   8303: 		if (!$publicuser) {
                   8304: 		    %returnhash=&userenvironment($udom,$uname,
                   8305: 						 $qualifierrest);
                   8306: 		}
1.218     albertel 8307: 		return $returnhash{$qualifierrest};
                   8308: 	    }
1.48      www      8309: # ----------------------------------------------------------------- user.course
                   8310:         } elsif ($space eq 'course') {
1.218     albertel 8311: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8312:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8313: # ------------------------------------------------------------------- user.role
                   8314:         } elsif ($space eq 'role') {
1.218     albertel 8315: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8316:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8317:             if ($qualifier eq 'value') {
                   8318: 		return $role;
                   8319:             } elsif ($qualifier eq 'extent') {
                   8320:                 return $where;
                   8321:             }
                   8322: # ----------------------------------------------------------------- user.domain
                   8323:         } elsif ($space eq 'domain') {
1.218     albertel 8324:             return $udom;
1.48      www      8325: # ------------------------------------------------------------------- user.name
                   8326:         } elsif ($space eq 'name') {
1.218     albertel 8327:             return $uname;
1.48      www      8328: # ---------------------------------------------------- Any other user namespace
1.29      www      8329:         } else {
1.359     albertel 8330: 	    my %reply;
                   8331: 	    if (!$publicuser) {
                   8332: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8333: 	    }
                   8334: 	    return $reply{$qualifierrest};
1.48      www      8335:         }
1.236     www      8336:     } elsif ($realm eq 'query') {
                   8337: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8338:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8339: 						[$spacequalifierrest]);
1.620     albertel 8340: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8341:    } elsif ($realm eq 'request') {
1.48      www      8342: # ------------------------------------------------------------- request.browser
                   8343:         if ($space eq 'browser') {
1.430     www      8344: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8345: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8346: 		    return 1;
                   8347: 		} else {
                   8348: 		    return 0;
                   8349: 		}
                   8350: 	    } else {
1.620     albertel 8351: 		return $env{'browser.'.$qualifier};
1.430     www      8352: 	    }
1.57      www      8353: # ------------------------------------------------------------ request.filename
                   8354:         } else {
1.620     albertel 8355:             return $env{'request.'.$spacequalifierrest};
1.29      www      8356:         }
1.28      www      8357:     } elsif ($realm eq 'course') {
1.48      www      8358: # ---------------------------------------------------------- course.description
1.620     albertel 8359:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8360:     } elsif ($realm eq 'resource') {
1.165     www      8361: 
1.620     albertel 8362: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8363: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8364: 	}
1.693     albertel 8365: 
                   8366: 	if ($space eq 'title') {
                   8367: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8368: 	    return &gettitle($symbparm);
                   8369: 	}
                   8370: 	
                   8371: 	if ($space eq 'map') {
                   8372: 	    my ($map) = &decode_symb($symbparm);
                   8373: 	    return &symbread($map);
                   8374: 	}
1.905     albertel 8375: 	if ($space eq 'filename') {
                   8376: 	    if ($symbparm) {
                   8377: 		return &clutter((&decode_symb($symbparm))[2]);
                   8378: 	    }
                   8379: 	    return &hreflocation('',$env{'request.filename'});
                   8380: 	}
1.693     albertel 8381: 
                   8382: 	my ($section, $group, @groups);
1.593     albertel 8383: 	my ($courselevelm,$courselevel);
1.539     albertel 8384: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8385: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8386: 
1.218     albertel 8387: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8388: 
1.60      www      8389: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8390: 	    my $symbp=$symbparm;
1.735     albertel 8391: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8392: 
                   8393: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8394: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8395: 
1.620     albertel 8396: 	    if (($env{'user.name'} eq $uname) &&
                   8397: 		($env{'user.domain'} eq $udom)) {
                   8398: 		$section=$env{'request.course.sec'};
1.733     raeburn  8399:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8400:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8401: 	    } else {
1.539     albertel 8402: 		if (! defined($usection)) {
1.551     albertel 8403: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8404: 		} else {
                   8405: 		    $section = $usection;
                   8406: 		}
1.733     raeburn  8407:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8408: 	    }
                   8409: 
                   8410: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8411: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8412: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8413: 
1.593     albertel 8414: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8415: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8416: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8417: 
1.60      www      8418: # ----------------------------------------------------------- first, check user
1.624     albertel 8419: 
                   8420: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8421: 				       ([$courselevelr,'resource'],
                   8422: 					[$courselevelm,'map'     ],
                   8423: 					[$courselevel, 'course'  ]));
1.931     albertel 8424: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8425: 
1.594     albertel 8426: # ------------------------------------------------ second, check some of course
1.684     raeburn  8427:             my $coursereply;
1.691     raeburn  8428:             if (@groups > 0) {
                   8429:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8430:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8431:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8432:             }
1.96      www      8433: 
1.684     raeburn  8434: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8435: 				  $env{'course.'.$courseid.'.domain'},
                   8436: 				  'course',
                   8437: 				  ([$seclevelr,   'resource'],
                   8438: 				   [$seclevelm,   'map'     ],
                   8439: 				   [$seclevel,    'course'  ],
                   8440: 				   [$courselevelr,'resource']));
                   8441: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8442: 
1.60      www      8443: # ------------------------------------------------------ third, check map parms
1.218     albertel 8444: 	    my %parmhash=();
                   8445: 	    my $thisparm='';
                   8446: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8447: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8448: 		    &GDBM_READER(),0640)) {
1.218     albertel 8449: 		$thisparm=$parmhash{$symbparm};
                   8450: 		untie(%parmhash);
                   8451: 	    }
1.927     albertel 8452: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8453: 	}
1.594     albertel 8454: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8455: 
1.218     albertel 8456: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8457: 	my $filename;
                   8458: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8459: 	if ($symbparm) {
1.409     www      8460: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8461: 	} else {
1.620     albertel 8462: 	    $filename=$env{'request.filename'};
1.282     albertel 8463: 	}
                   8464: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8465: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8466: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8467: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8468: 
1.927     albertel 8469: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8470: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8471: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8472: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8473: 				     $env{'course.'.$courseid.'.domain'},
                   8474: 				     'course',
1.927     albertel 8475: 				     ([$courselevelm,'map'   ],
                   8476: 				      [$courselevel, 'course']));
                   8477: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8478: 	}
1.145     www      8479: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8480: 	unless ($space eq '0') {
1.336     albertel 8481: 	    my @parts=split(/_/,$space);
                   8482: 	    my $id=pop(@parts);
                   8483: 	    my $part=join('_',@parts);
                   8484: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8485: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8486: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8487: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8488: 	}
1.395     albertel 8489: 	if ($recurse) { return undef; }
                   8490: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8491: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8492: # ---------------------------------------------------- Any other user namespace
                   8493:     } elsif ($realm eq 'environment') {
                   8494: # ----------------------------------------------------------------- environment
1.620     albertel 8495: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8496: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8497: 	} else {
1.770     albertel 8498: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8499: 		return '';
                   8500: 	    }
1.219     albertel 8501: 	    my %returnhash=&userenvironment($udom,$uname,
                   8502: 					    $spacequalifierrest);
                   8503: 	    return $returnhash{$spacequalifierrest};
                   8504: 	}
1.28      www      8505:     } elsif ($realm eq 'system') {
1.48      www      8506: # ----------------------------------------------------------------- system.time
                   8507: 	if ($space eq 'time') {
                   8508: 	    return time;
                   8509:         }
1.696     albertel 8510:     } elsif ($realm eq 'server') {
                   8511: # ----------------------------------------------------------------- system.time
                   8512: 	if ($space eq 'name') {
                   8513: 	    return $ENV{'SERVER_NAME'};
                   8514:         }
1.28      www      8515:     }
1.48      www      8516:     return '';
1.61      www      8517: }
                   8518: 
1.927     albertel 8519: sub get_reply {
                   8520:     my ($reply_value) = @_;
1.940     raeburn  8521:     if (ref($reply_value) eq 'ARRAY') {
                   8522:         if (wantarray) {
                   8523: 	    return @$reply_value;
                   8524:         }
                   8525:         return $reply_value->[0];
                   8526:     } else {
                   8527:         return $reply_value;
1.927     albertel 8528:     }
                   8529: }
                   8530: 
1.691     raeburn  8531: sub check_group_parms {
                   8532:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8533:     my @groupitems = ();
                   8534:     my $resultitem;
1.927     albertel 8535:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8536:     foreach my $group (@{$groups}) {
                   8537:         foreach my $level (@levels) {
1.927     albertel 8538:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8539:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8540:         }
                   8541:     }
                   8542:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8543:                             $env{'course.'.$courseid.'.domain'},
                   8544:                                      'course',@groupitems);
                   8545:     return $coursereply;
                   8546: }
                   8547: 
                   8548: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8549:     my ($courseid,@groups) = @_;
                   8550:     @groups = sort(@groups);
1.691     raeburn  8551:     return @groups;
                   8552: }
                   8553: 
1.395     albertel 8554: sub packages_tab_default {
                   8555:     my ($uri,$varname)=@_;
                   8556:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8557: 
                   8558:     my (@extension,@specifics,$do_default);
                   8559:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8560: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8561: 	if ($pack_type eq 'default') {
                   8562: 	    $do_default=1;
                   8563: 	} elsif ($pack_type eq 'extension') {
                   8564: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8565: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8566: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8567: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8568: 	}
                   8569:     }
                   8570:     # first look for a package that matches the requested part id
                   8571:     foreach my $package (@specifics) {
                   8572: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8573: 	next if ($pack_part ne $part);
                   8574: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8575: 	    return $packagetab{"$pack_type&$name&default"};
                   8576: 	}
                   8577:     }
                   8578:     # look for any possible matching non extension_ package
                   8579:     foreach my $package (@specifics) {
                   8580: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8581: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8582: 	    return $packagetab{"$pack_type&$name&default"};
                   8583: 	}
1.585     albertel 8584: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8585: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8586: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8587: 	}
                   8588:     }
1.738     albertel 8589:     # look for any posible extension_ match
                   8590:     foreach my $package (@extension) {
                   8591: 	my ($package,$pack_type)=@{$package};
                   8592: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8593: 	    return $packagetab{"$pack_type&$name&default"};
                   8594: 	}
                   8595: 	if (defined($packagetab{$package."&$name&default"})) {
                   8596: 	    return $packagetab{$package."&$name&default"};
                   8597: 	}
                   8598:     }
                   8599:     # look for a global default setting
                   8600:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8601: 	return $packagetab{"default&$name&default"};
                   8602:     }
1.395     albertel 8603:     return undef;
                   8604: }
                   8605: 
1.334     albertel 8606: sub add_prefix_and_part {
                   8607:     my ($prefix,$part)=@_;
                   8608:     my $keyroot;
                   8609:     if (defined($prefix) && $prefix !~ /^__/) {
                   8610: 	# prefix that has a part already
                   8611: 	$keyroot=$prefix;
                   8612:     } elsif (defined($prefix)) {
                   8613: 	# prefix that is missing a part
                   8614: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8615:     } else {
                   8616: 	# no prefix at all
                   8617: 	if (defined($part)) { $keyroot='_'.$part; }
                   8618:     }
                   8619:     return $keyroot;
                   8620: }
                   8621: 
1.71      www      8622: # ---------------------------------------------------------------- Get metadata
                   8623: 
1.599     albertel 8624: my %metaentry;
1.71      www      8625: sub metadata {
1.176     www      8626:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8627:     $uri=&declutter($uri);
1.288     albertel 8628:     # if it is a non metadata possible uri return quickly
1.529     albertel 8629:     if (($uri eq '') || 
                   8630: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8631: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.26  raeburn  8632:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8633: 	return undef;
                   8634:     }
                   8635:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8636: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8637: 	return undef;
1.288     albertel 8638:     }
1.73      www      8639:     my $filename=$uri;
                   8640:     $uri=~s/\.meta$//;
1.172     www      8641: #
                   8642: # Is the metadata already cached?
1.177     www      8643: # Look at timestamp of caching
1.172     www      8644: # Everything is cached by the main uri, libraries are never directly cached
                   8645: #
1.428     albertel 8646:     if (!defined($liburi)) {
1.599     albertel 8647: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8648: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8649:     }
                   8650:     {
1.172     www      8651: #
                   8652: # Is this a recursive call for a library?
                   8653: #
1.599     albertel 8654: #	if (! exists($metacache{$uri})) {
                   8655: #	    $metacache{$uri}={};
                   8656: #	}
1.924     albertel 8657: 	my $cachetime = 60*60;
1.171     www      8658:         if ($liburi) {
                   8659: 	    $liburi=&declutter($liburi);
                   8660:             $filename=$liburi;
1.401     bowersj2 8661:         } else {
1.599     albertel 8662: 	    &devalidate_cache_new('meta',$uri);
                   8663: 	    undef(%metaentry);
1.401     bowersj2 8664: 	}
1.140     www      8665:         my %metathesekeys=();
1.73      www      8666:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8667: 	my $metastring;
1.924     albertel 8668: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8669: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8670: 	    $metastring = 
1.929     albertel 8671: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8672: 					  ('grade_target' => 'meta'));
                   8673: 	    $cachetime = 1; # only want this cached in the child not long term
1.1056.4.26  raeburn  8674: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   8675:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 8676: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8677: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8678: 	    $metastring=&getfile($file);
1.489     albertel 8679: 	}
1.208     albertel 8680:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8681:         my $token;
1.140     www      8682:         undef %metathesekeys;
1.71      www      8683:         while ($token=$parser->get_token) {
1.339     albertel 8684: 	    if ($token->[0] eq 'S') {
                   8685: 		if (defined($token->[2]->{'package'})) {
1.172     www      8686: #
                   8687: # This is a package - get package info
                   8688: #
1.339     albertel 8689: 		    my $package=$token->[2]->{'package'};
                   8690: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8691: 		    if (defined($token->[2]->{'id'})) { 
                   8692: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8693: 		    }
1.599     albertel 8694: 		    if ($metaentry{':packages'}) {
                   8695: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8696: 		    } else {
1.599     albertel 8697: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8698: 		    }
1.736     albertel 8699: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8700: 			my $part=$keyroot;
                   8701: 			$part=~s/^\_//;
1.736     albertel 8702: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8703: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8704: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8705: 			    # ignore package.tab specified default values
                   8706:                             # here &package_tab_default() will fetch those
                   8707: 			    if ($subp eq 'default') { next; }
1.736     albertel 8708: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8709: 			    my $unikey;
                   8710: 			    if ($pack =~ /_0$/) {
                   8711: 				$unikey='parameter_0_'.$name;
                   8712: 				$part=0;
                   8713: 			    } else {
                   8714: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8715: 			    }
1.339     albertel 8716: 			    if ($subp eq 'display') {
                   8717: 				$value.=' [Part: '.$part.']';
                   8718: 			    }
1.599     albertel 8719: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8720: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8721: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8722: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8723: 			    }
1.599     albertel 8724: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8725: 				$metaentry{':'.$unikey}=
                   8726: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8727: 			    }
1.339     albertel 8728: 			}
                   8729: 		    }
                   8730: 		} else {
1.172     www      8731: #
                   8732: # This is not a package - some other kind of start tag
1.339     albertel 8733: #
                   8734: 		    my $entry=$token->[1];
                   8735: 		    my $unikey;
                   8736: 		    if ($entry eq 'import') {
                   8737: 			$unikey='';
                   8738: 		    } else {
                   8739: 			$unikey=$entry;
                   8740: 		    }
                   8741: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8742: 
                   8743: 		    if (defined($token->[2]->{'id'})) { 
                   8744: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8745: 		    }
1.175     www      8746: 
1.339     albertel 8747: 		    if ($entry eq 'import') {
1.175     www      8748: #
                   8749: # Importing a library here
1.339     albertel 8750: #
                   8751: 			if ($depthcount<20) {
                   8752: 			    my $location=$parser->get_text('/import');
                   8753: 			    my $dir=$filename;
                   8754: 			    $dir=~s|[^/]*$||;
                   8755: 			    $location=&filelocation($dir,$location);
1.736     albertel 8756: 			    my $metadata = 
                   8757: 				&metadata($uri,'keys', $location,$unikey,
                   8758: 					  $depthcount+1);
                   8759: 			    foreach my $meta (split(',',$metadata)) {
                   8760: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8761: 				$metathesekeys{$meta}=1;
1.339     albertel 8762: 			    }
                   8763: 			}
                   8764: 		    } else { 
                   8765: 			if (defined($token->[2]->{'name'})) { 
                   8766: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8767: 			}
                   8768: 			$metathesekeys{$unikey}=1;
1.736     albertel 8769: 			foreach my $param (@{$token->[3]}) {
                   8770: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8771: 				$token->[2]->{$param};
1.339     albertel 8772: 			}
                   8773: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8774: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8775: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8776: 		 # only ws inside the tag, and not in default, so use default
                   8777: 		 # as value
1.599     albertel 8778: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8779: 			} elsif ( $internaltext =~ /\S/ ) {
                   8780: 		  # something interesting inside the tag
                   8781: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8782: 			} else {
1.908     albertel 8783: 		  # no interesting values, don't set a default
1.339     albertel 8784: 			}
1.172     www      8785: # end of not-a-package not-a-library import
1.339     albertel 8786: 		    }
1.172     www      8787: # end of not-a-package start tag
1.339     albertel 8788: 		}
1.172     www      8789: # the next is the end of "start tag"
1.339     albertel 8790: 	    }
                   8791: 	}
1.483     albertel 8792: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8793: 	$extension = lc($extension);
                   8794: 	if ($extension eq 'htm') { $extension='html'; }
                   8795: 
1.737     albertel 8796: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8797: 	    #no specific packages #how's our extension
                   8798: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8799: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8800: 					 \%metathesekeys);
                   8801: 	}
1.883     albertel 8802: 
                   8803: 	if (!exists($metaentry{':packages'})
                   8804: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8805: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8806: 		#no specific packages well let's get default then
                   8807: 		if ($key!~/^default&/) { next; }
1.488     albertel 8808: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8809: 					     \%metathesekeys);
                   8810: 	    }
                   8811: 	}
1.338     www      8812: # are there custom rights to evaluate
1.599     albertel 8813: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8814: 
1.338     www      8815:     #
                   8816:     # Importing a rights file here
1.339     albertel 8817:     #
                   8818: 	    unless ($depthcount) {
1.599     albertel 8819: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8820: 		my $dir=$filename;
                   8821: 		$dir=~s|[^/]*$||;
                   8822: 		$location=&filelocation($dir,$location);
1.736     albertel 8823: 		my $rights_metadata =
                   8824: 		    &metadata($uri,'keys',$location,'_rights',
                   8825: 			      $depthcount+1);
                   8826: 		foreach my $rights (split(',',$rights_metadata)) {
                   8827: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8828: 		    $metathesekeys{$rights}=1;
1.339     albertel 8829: 		}
                   8830: 	    }
                   8831: 	}
1.737     albertel 8832: 	# uniqifiy package listing
                   8833: 	my %seen;
                   8834: 	my @uniq_packages =
                   8835: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8836: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8837: 
                   8838: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8839: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8840: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8841: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8842: # this is the end of "was not already recently cached
1.71      www      8843:     }
1.599     albertel 8844:     return $metaentry{':'.$what};
1.261     albertel 8845: }
                   8846: 
1.488     albertel 8847: sub metadata_create_package_def {
1.483     albertel 8848:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8849:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8850:     if ($subp eq 'default') { next; }
                   8851:     
1.599     albertel 8852:     if (defined($metaentry{':packages'})) {
                   8853: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8854:     } else {
1.599     albertel 8855: 	$metaentry{':packages'}=$package;
1.483     albertel 8856:     }
                   8857:     my $value=$packagetab{$key};
                   8858:     my $unikey;
                   8859:     $unikey='parameter_0_'.$name;
1.599     albertel 8860:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8861:     $$metathesekeys{$unikey}=1;
1.599     albertel 8862:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8863: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8864:     }
1.599     albertel 8865:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8866: 	$metaentry{':'.$unikey}=
                   8867: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8868:     }
                   8869: }
                   8870: 
1.261     albertel 8871: sub metadata_generate_part0 {
                   8872:     my ($metadata,$metacache,$uri) = @_;
                   8873:     my %allnames;
1.737     albertel 8874:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8875: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8876: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8877: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8878: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8879: 	    $allnames{$name}=$part;
                   8880: 	  }
                   8881: 	}
                   8882:     }
                   8883:     foreach my $name (keys(%allnames)) {
                   8884:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8885:       my $key=":parameter_0_$name";
1.261     albertel 8886:       $$metacache{"$key.part"}='0';
                   8887:       $$metacache{"$key.name"}=$name;
1.428     albertel 8888:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8889: 					   $allnames{$name}.'_'.$name.
                   8890: 					   '.type'};
1.428     albertel 8891:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8892: 			     '.display'};
1.644     www      8893:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8894:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8895:       $$metacache{"$key.display"}=$olddis;
                   8896:     }
1.71      www      8897: }
                   8898: 
1.764     albertel 8899: # ------------------------------------------------------ Devalidate title cache
                   8900: 
                   8901: sub devalidate_title_cache {
                   8902:     my ($url)=@_;
                   8903:     if (!$env{'request.course.id'}) { return; }
                   8904:     my $symb=&symbread($url);
                   8905:     if (!$symb) { return; }
                   8906:     my $key=$env{'request.course.id'}."\0".$symb;
                   8907:     &devalidate_cache_new('title',$key);
                   8908: }
                   8909: 
1.1014    droeschl 8910: # ------------------------------------------------- Get the title of a course
                   8911: 
                   8912: sub current_course_title {
                   8913:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8914: }
1.301     www      8915: # ------------------------------------------------- Get the title of a resource
                   8916: 
                   8917: sub gettitle {
                   8918:     my $urlsymb=shift;
                   8919:     my $symb=&symbread($urlsymb);
1.534     albertel 8920:     if ($symb) {
1.620     albertel 8921: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8922: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8923: 	if (defined($cached)) { 
                   8924: 	    return $result;
                   8925: 	}
1.534     albertel 8926: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8927: 	my $title='';
1.907     albertel 8928: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8929: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8930: 	} else {
                   8931: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8932: 		    &GDBM_READER(),0640)) {
                   8933: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8934: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8935: 		untie(%bighash);
                   8936: 	    }
1.534     albertel 8937: 	}
                   8938: 	$title=~s/\&colon\;/\:/gs;
                   8939: 	if ($title) {
1.599     albertel 8940: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8941: 	}
                   8942: 	$urlsymb=$url;
                   8943:     }
                   8944:     my $title=&metadata($urlsymb,'title');
                   8945:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8946:     return $title;
1.301     www      8947: }
1.613     albertel 8948: 
1.614     albertel 8949: sub get_slot {
                   8950:     my ($which,$cnum,$cdom)=@_;
                   8951:     if (!$cnum || !$cdom) {
1.790     albertel 8952: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8953: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8954: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8955:     }
1.703     albertel 8956:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8957:     my %slotinfo;
                   8958:     if (exists($remembered{$key})) {
                   8959: 	$slotinfo{$which} = $remembered{$key};
                   8960:     } else {
                   8961: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8962: 	&Apache::lonhomework::showhash(%slotinfo);
                   8963: 	my ($tmp)=keys(%slotinfo);
                   8964: 	if ($tmp=~/^error:/) { return (); }
                   8965: 	$remembered{$key} = $slotinfo{$which};
                   8966:     }
1.616     albertel 8967:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8968: 	return %{$slotinfo{$which}};
                   8969:     }
                   8970:     return $slotinfo{$which};
1.614     albertel 8971: }
1.31      www      8972: # ------------------------------------------------- Update symbolic store links
                   8973: 
                   8974: sub symblist {
                   8975:     my ($mapname,%newhash)=@_;
1.438     www      8976:     $mapname=&deversion(&declutter($mapname));
1.31      www      8977:     my %hash;
1.620     albertel 8978:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8979:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8980:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8981: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8982: 		next if ($url eq 'last_known'
                   8983: 			 && $env{'form.no_update_last_known'});
                   8984: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8985: 						    $newhash{$url}->[1],
                   8986: 						    $newhash{$url}->[0]);
1.191     harris41 8987:             }
1.31      www      8988:             if (untie(%hash)) {
                   8989: 		return 'ok';
                   8990:             }
                   8991:         }
                   8992:     }
                   8993:     return 'error';
1.212     www      8994: }
                   8995: 
                   8996: # --------------------------------------------------------------- Verify a symb
                   8997: 
                   8998: sub symbverify {
1.510     www      8999:     my ($symb,$thisurl)=@_;
                   9000:     my $thisfn=$thisurl;
1.439     www      9001:     $thisfn=&declutter($thisfn);
1.215     www      9002: # direct jump to resource in page or to a sequence - will construct own symbs
                   9003:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9004: # check URL part
1.409     www      9005:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9006: 
1.431     www      9007:     unless ($url eq $thisfn) { return 0; }
1.213     www      9008: 
1.216     www      9009:     $symb=&symbclean($symb);
1.510     www      9010:     $thisurl=&deversion($thisurl);
1.439     www      9011:     $thisfn=&deversion($thisfn);
1.213     www      9012: 
                   9013:     my %bighash;
                   9014:     my $okay=0;
1.431     www      9015: 
1.620     albertel 9016:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9017:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9018:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9019:             $thisurl =~ s/\?.+$//;
                   9020:         }
1.510     www      9021:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      9022:         unless ($ids) { 
1.1056.4.21  raeburn  9023:            my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
                   9024:            $ids=$bighash{$idkey};
1.216     www      9025:         }
                   9026:         if ($ids) {
                   9027: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9028: 	    foreach my $id (split(/\,/,$ids)) {
                   9029: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9030:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9031:                    $symb =~ s/\?.+$//;
                   9032:                }
1.216     www      9033:                if (
                   9034:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9035:    eq $symb) { 
1.620     albertel 9036: 		   if (($env{'request.role.adv'}) ||
1.1056.4.20  raeburn  9037: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9038: 		       ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9039: 		       $okay=1; 
                   9040: 		   }
                   9041: 	       }
1.216     www      9042: 	   }
                   9043:         }
1.213     www      9044: 	untie(%bighash);
                   9045:     }
                   9046:     return $okay;
1.31      www      9047: }
                   9048: 
1.210     www      9049: # --------------------------------------------------------------- Clean-up symb
                   9050: 
                   9051: sub symbclean {
                   9052:     my $symb=shift;
1.568     albertel 9053:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9054: # remove version from map
                   9055:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9056: 
1.210     www      9057: # remove version from URL
                   9058:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9059: 
1.507     www      9060: # remove wrapper
                   9061: 
1.510     www      9062:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9063:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9064:     return $symb;
1.409     www      9065: }
                   9066: 
                   9067: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9068: 
                   9069: sub encode_symb {
                   9070:     my ($map,$resid,$url)=@_;
                   9071:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9072: }
1.409     www      9073: 
                   9074: sub decode_symb {
1.568     albertel 9075:     my $symb=shift;
                   9076:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9077:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9078:     return (&fixversion($map),$resid,&fixversion($url));
                   9079: }
                   9080: 
                   9081: sub fixversion {
                   9082:     my $fn=shift;
1.609     banghart 9083:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9084:     my %bighash;
                   9085:     my $uri=&clutter($fn);
1.620     albertel 9086:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9087: # is this cached?
1.599     albertel 9088:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9089:     if (defined($cached)) { return $result; }
                   9090: # unfortunately not cached, or expired
1.620     albertel 9091:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9092: 	    &GDBM_READER(),0640)) {
                   9093:  	if ($bighash{'version_'.$uri}) {
                   9094:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9095:  	    unless (($version eq 'mostrecent') || 
                   9096: 		    ($version==&getversion($uri))) {
1.440     www      9097:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9098:  	    }
                   9099:  	}
                   9100:  	untie %bighash;
1.413     www      9101:     }
1.599     albertel 9102:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9103: }
                   9104: 
                   9105: sub deversion {
                   9106:     my $url=shift;
                   9107:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9108:     return $url;
1.210     www      9109: }
                   9110: 
1.31      www      9111: # ------------------------------------------------------ Return symb list entry
                   9112: 
                   9113: sub symbread {
1.249     www      9114:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9115:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9116:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9117: # no filename provided? try from environment
1.44      www      9118:     unless ($thisfn) {
1.620     albertel 9119:         if ($env{'request.symb'}) {
                   9120: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9121: 	}
1.620     albertel 9122: 	$thisfn=$env{'request.filename'};
1.44      www      9123:     }
1.569     albertel 9124:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9125: # is that filename actually a symb? Verify, clean, and return
                   9126:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9127: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9128: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9129: 	}
1.242     www      9130:     }
1.44      www      9131:     $thisfn=declutter($thisfn);
1.31      www      9132:     my %hash;
1.37      www      9133:     my %bighash;
                   9134:     my $syval='';
1.620     albertel 9135:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9136:         my $targetfn = $thisfn;
1.609     banghart 9137:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9138:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9139:         }
1.687     albertel 9140: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9141: 	    $targetfn=$1;
                   9142: 	}
1.620     albertel 9143:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9144:                       &GDBM_READER(),0640)) {
1.481     raeburn  9145: 	    $syval=$hash{$targetfn};
1.37      www      9146:             untie(%hash);
                   9147:         }
                   9148: # ---------------------------------------------------------- There was an entry
                   9149:         if ($syval) {
1.601     albertel 9150: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9151: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9152: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9153: 		    #return $env{$cache_str}='';
1.601     albertel 9154: 		#}    
                   9155: 		#$syval.=$1;
                   9156: 	    #}
1.37      www      9157:         } else {
                   9158: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9159:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9160:                             &GDBM_READER(),0640)) {
1.37      www      9161: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9162:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9163:               unless ($ids) { 
                   9164:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9165:               }
                   9166:               unless ($ids) {
                   9167: # alias?
                   9168: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9169:               }
1.37      www      9170:               if ($ids) {
                   9171: # ------------------------------------------------------------------- Has ID(s)
                   9172:                  my @possibilities=split(/\,/,$ids);
1.39      www      9173:                  if ($#possibilities==0) {
                   9174: # ----------------------------------------------- There is only one possibility
1.37      www      9175: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9176: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9177: 						    $resid,$thisfn);
1.249     www      9178:                  } elsif (!$donotrecurse) {
1.39      www      9179: # ------------------------------------------ There is more than one possibility
                   9180:                      my $realpossible=0;
1.800     albertel 9181:                      foreach my $id (@possibilities) {
                   9182: 			 my $file=$bighash{'src_'.$id};
1.39      www      9183:                          if (&allowed('bre',$file)) {
1.800     albertel 9184:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9185:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9186: 				$realpossible++;
1.626     albertel 9187:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9188: 						    $resid,$thisfn);
1.39      www      9189:                             }
                   9190: 			 }
1.191     harris41 9191:                      }
1.39      www      9192: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9193:                  } else {
                   9194:                      $syval='';
1.37      www      9195:                  }
                   9196: 	      }
                   9197:               untie(%bighash)
1.481     raeburn  9198:            }
1.31      www      9199:         }
1.62      www      9200:         if ($syval) {
1.620     albertel 9201: 	    return $env{$cache_str}=$syval;
1.62      www      9202:         }
1.31      www      9203:     }
1.949     raeburn  9204:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9205:     return $env{$cache_str}='';
1.31      www      9206: }
                   9207: 
                   9208: # ---------------------------------------------------------- Return random seed
                   9209: 
1.32      www      9210: sub numval {
                   9211:     my $txt=shift;
                   9212:     $txt=~tr/A-J/0-9/;
                   9213:     $txt=~tr/a-j/0-9/;
                   9214:     $txt=~tr/K-T/0-9/;
                   9215:     $txt=~tr/k-t/0-9/;
                   9216:     $txt=~tr/U-Z/0-5/;
                   9217:     $txt=~tr/u-z/0-5/;
                   9218:     $txt=~s/\D//g;
1.564     albertel 9219:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9220:     return int($txt);
1.368     albertel 9221: }
                   9222: 
1.484     albertel 9223: sub numval2 {
                   9224:     my $txt=shift;
                   9225:     $txt=~tr/A-J/0-9/;
                   9226:     $txt=~tr/a-j/0-9/;
                   9227:     $txt=~tr/K-T/0-9/;
                   9228:     $txt=~tr/k-t/0-9/;
                   9229:     $txt=~tr/U-Z/0-5/;
                   9230:     $txt=~tr/u-z/0-5/;
                   9231:     $txt=~s/\D//g;
                   9232:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9233:     my $total;
                   9234:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9235:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9236:     return int($total);
                   9237: }
                   9238: 
1.575     albertel 9239: sub numval3 {
                   9240:     use integer;
                   9241:     my $txt=shift;
                   9242:     $txt=~tr/A-J/0-9/;
                   9243:     $txt=~tr/a-j/0-9/;
                   9244:     $txt=~tr/K-T/0-9/;
                   9245:     $txt=~tr/k-t/0-9/;
                   9246:     $txt=~tr/U-Z/0-5/;
                   9247:     $txt=~tr/u-z/0-5/;
                   9248:     $txt=~s/\D//g;
                   9249:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9250:     my $total;
                   9251:     foreach my $val (@txts) { $total+=$val; }
                   9252:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9253:     return $total;
                   9254: }
                   9255: 
1.675     albertel 9256: sub digest {
                   9257:     my ($data)=@_;
                   9258:     my $digest=&Digest::MD5::md5($data);
                   9259:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9260:     my ($e,$f);
                   9261:     {
                   9262:         use integer;
                   9263:         $e=($a+$b);
                   9264:         $f=($c+$d);
                   9265:         if ($_64bit) {
                   9266:             $e=(($e<<32)>>32);
                   9267:             $f=(($f<<32)>>32);
                   9268:         }
                   9269:     }
                   9270:     if (wantarray) {
                   9271: 	return ($e,$f);
                   9272:     } else {
                   9273: 	my $g;
                   9274: 	{
                   9275: 	    use integer;
                   9276: 	    $g=($e+$f);
                   9277: 	    if ($_64bit) {
                   9278: 		$g=(($g<<32)>>32);
                   9279: 	    }
                   9280: 	}
                   9281: 	return $g;
                   9282:     }
                   9283: }
                   9284: 
1.368     albertel 9285: sub latest_rnd_algorithm_id {
1.675     albertel 9286:     return '64bit5';
1.366     albertel 9287: }
1.32      www      9288: 
1.503     albertel 9289: sub get_rand_alg {
                   9290:     my ($courseid)=@_;
1.790     albertel 9291:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9292:     if ($courseid) {
1.620     albertel 9293: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9294:     }
                   9295:     return &latest_rnd_algorithm_id();
                   9296: }
                   9297: 
1.562     albertel 9298: sub validCODE {
                   9299:     my ($CODE)=@_;
                   9300:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9301:     return 0;
                   9302: }
                   9303: 
1.491     albertel 9304: sub getCODE {
1.620     albertel 9305:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9306:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9307: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9308: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9309: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9310:     }
                   9311:     return undef;
                   9312: }
                   9313: 
1.31      www      9314: sub rndseed {
1.155     albertel 9315:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9316:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9317:     if (!defined($symb)) {
1.366     albertel 9318: 	unless ($symb=$wsymb) { return time; }
                   9319:     }
                   9320:     if (!$courseid) { $courseid=$wcourseid; }
                   9321:     if (!$domain) { $domain=$wdomain; }
                   9322:     if (!$username) { $username=$wusername }
1.503     albertel 9323:     my $which=&get_rand_alg();
1.803     albertel 9324: 
1.491     albertel 9325:     if (defined(&getCODE())) {
1.675     albertel 9326: 	if ($which eq '64bit5') {
                   9327: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9328: 	} elsif ($which eq '64bit4') {
1.575     albertel 9329: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9330: 	} else {
                   9331: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9332: 	}
1.675     albertel 9333:     } elsif ($which eq '64bit5') {
                   9334: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9335:     } elsif ($which eq '64bit4') {
                   9336: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9337:     } elsif ($which eq '64bit3') {
                   9338: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9339:     } elsif ($which eq '64bit2') {
                   9340: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9341:     } elsif ($which eq '64bit') {
                   9342: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9343:     }
                   9344:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9345: }
                   9346: 
                   9347: sub rndseed_32bit {
                   9348:     my ($symb,$courseid,$domain,$username)=@_;
                   9349:     {
                   9350: 	use integer;
                   9351: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9352: 	my $symbseed=numval($symb) << 22;
                   9353: 	my $namechck=unpack("%32C*",$username) << 17;
                   9354: 	my $nameseed=numval($username) << 12;
                   9355: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9356: 	my $courseseed=unpack("%32C*",$courseid);
                   9357: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9358: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9359: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9360: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9361: 	return $num;
                   9362:     }
                   9363: }
                   9364: 
                   9365: sub rndseed_64bit {
                   9366:     my ($symb,$courseid,$domain,$username)=@_;
                   9367:     {
                   9368: 	use integer;
                   9369: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9370: 	my $symbseed=numval($symb) << 10;
                   9371: 	my $namechck=unpack("%32S*",$username);
                   9372: 	
                   9373: 	my $nameseed=numval($username) << 21;
                   9374: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9375: 	my $courseseed=unpack("%32S*",$courseid);
                   9376: 	
                   9377: 	my $num1=$symbchck+$symbseed+$namechck;
                   9378: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9379: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9380: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9381: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9382: 	return "$num1,$num2";
1.155     albertel 9383:     }
1.366     albertel 9384: }
                   9385: 
1.443     albertel 9386: sub rndseed_64bit2 {
                   9387:     my ($symb,$courseid,$domain,$username)=@_;
                   9388:     {
                   9389: 	use integer;
                   9390: 	# strings need to be an even # of cahracters long, it it is odd the
                   9391:         # last characters gets thrown away
                   9392: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9393: 	my $symbseed=numval($symb) << 10;
                   9394: 	my $namechck=unpack("%32S*",$username.' ');
                   9395: 	
                   9396: 	my $nameseed=numval($username) << 21;
1.501     albertel 9397: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9398: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9399: 	
                   9400: 	my $num1=$symbchck+$symbseed+$namechck;
                   9401: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9402: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9403: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9404: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9405: 	return "$num1,$num2";
                   9406:     }
                   9407: }
                   9408: 
                   9409: sub rndseed_64bit3 {
                   9410:     my ($symb,$courseid,$domain,$username)=@_;
                   9411:     {
                   9412: 	use integer;
                   9413: 	# strings need to be an even # of cahracters long, it it is odd the
                   9414:         # last characters gets thrown away
                   9415: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9416: 	my $symbseed=numval2($symb) << 10;
                   9417: 	my $namechck=unpack("%32S*",$username.' ');
                   9418: 	
                   9419: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9420: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9421: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9422: 	
                   9423: 	my $num1=$symbchck+$symbseed+$namechck;
                   9424: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9425: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9426: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9427: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9428: 	
1.503     albertel 9429: 	return "$num1:$num2";
1.443     albertel 9430:     }
                   9431: }
                   9432: 
1.575     albertel 9433: sub rndseed_64bit4 {
                   9434:     my ($symb,$courseid,$domain,$username)=@_;
                   9435:     {
                   9436: 	use integer;
                   9437: 	# strings need to be an even # of cahracters long, it it is odd the
                   9438:         # last characters gets thrown away
                   9439: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9440: 	my $symbseed=numval3($symb) << 10;
                   9441: 	my $namechck=unpack("%32S*",$username.' ');
                   9442: 	
                   9443: 	my $nameseed=numval3($username) << 21;
                   9444: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9445: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9446: 	
                   9447: 	my $num1=$symbchck+$symbseed+$namechck;
                   9448: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9449: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9450: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9451: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   9452: 	
                   9453: 	return "$num1:$num2";
                   9454:     }
                   9455: }
                   9456: 
1.675     albertel 9457: sub rndseed_64bit5 {
                   9458:     my ($symb,$courseid,$domain,$username)=@_;
                   9459:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9460:     return "$num1:$num2";
                   9461: }
                   9462: 
1.366     albertel 9463: sub rndseed_CODE_64bit {
                   9464:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9465:     {
1.366     albertel 9466: 	use integer;
1.443     albertel 9467: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9468: 	my $symbseed=numval2($symb);
1.491     albertel 9469: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9470: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9471: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9472: 	my $num1=$symbseed+$CODEchck;
                   9473: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9474: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9475: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9476: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9477: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9478: 	return "$num1:$num2";
1.366     albertel 9479:     }
                   9480: }
                   9481: 
1.575     albertel 9482: sub rndseed_CODE_64bit4 {
                   9483:     my ($symb,$courseid,$domain,$username)=@_;
                   9484:     {
                   9485: 	use integer;
                   9486: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9487: 	my $symbseed=numval3($symb);
                   9488: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9489: 	my $CODEseed=numval3(&getCODE());
                   9490: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9491: 	my $num1=$symbseed+$CODEchck;
                   9492: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9493: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9494: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9495: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9496: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9497: 	return "$num1:$num2";
                   9498:     }
                   9499: }
                   9500: 
1.675     albertel 9501: sub rndseed_CODE_64bit5 {
                   9502:     my ($symb,$courseid,$domain,$username)=@_;
                   9503:     my $code = &getCODE();
                   9504:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9505:     return "$num1:$num2";
                   9506: }
                   9507: 
1.366     albertel 9508: sub setup_random_from_rndseed {
                   9509:     my ($rndseed)=@_;
1.503     albertel 9510:     if ($rndseed =~/([,:])/) {
                   9511: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9512: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9513:     } else {
                   9514: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9515:     }
1.36      albertel 9516: }
                   9517: 
1.474     albertel 9518: sub latest_receipt_algorithm_id {
1.835     albertel 9519:     return 'receipt3';
1.474     albertel 9520: }
                   9521: 
1.480     www      9522: sub recunique {
                   9523:     my $fucourseid=shift;
                   9524:     my $unique;
1.835     albertel 9525:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9526: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9527: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9528:     } else {
                   9529: 	$unique=$perlvar{'lonReceipt'};
                   9530:     }
                   9531:     return unpack("%32C*",$unique);
                   9532: }
                   9533: 
                   9534: sub recprefix {
                   9535:     my $fucourseid=shift;
                   9536:     my $prefix;
1.835     albertel 9537:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9538: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9539: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9540:     } else {
                   9541: 	$prefix=$perlvar{'lonHostID'};
                   9542:     }
                   9543:     return unpack("%32C*",$prefix);
                   9544: }
                   9545: 
1.76      www      9546: sub ireceipt {
1.474     albertel 9547:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9548: 
                   9549:     my $return =&recprefix($fucourseid).'-';
                   9550: 
                   9551:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9552: 	$env{'request.state'} eq 'construct') {
                   9553: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9554: 	return $return;
                   9555:     }
                   9556: 
1.76      www      9557:     my $cuname=unpack("%32C*",$funame);
                   9558:     my $cudom=unpack("%32C*",$fudom);
                   9559:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9560:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9561:     my $cunique=&recunique($fucourseid);
1.474     albertel 9562:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9563:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9564: 
1.790     albertel 9565: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9566: 			       
                   9567: 	$return.= ($cunique%$cuname+
                   9568: 		   $cunique%$cudom+
                   9569: 		   $cusymb%$cuname+
                   9570: 		   $cusymb%$cudom+
                   9571: 		   $cucourseid%$cuname+
                   9572: 		   $cucourseid%$cudom+
                   9573: 		   $cpart%$cuname+
                   9574: 		   $cpart%$cudom);
                   9575:     } else {
                   9576: 	$return.= ($cunique%$cuname+
                   9577: 		   $cunique%$cudom+
                   9578: 		   $cusymb%$cuname+
                   9579: 		   $cusymb%$cudom+
                   9580: 		   $cucourseid%$cuname+
                   9581: 		   $cucourseid%$cudom);
                   9582:     }
                   9583:     return $return;
1.76      www      9584: }
                   9585: 
                   9586: sub receipt {
1.474     albertel 9587:     my ($part)=@_;
1.790     albertel 9588:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9589:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9590: }
1.260     ng       9591: 
1.790     albertel 9592: sub whichuser {
                   9593:     my ($passedsymb)=@_;
                   9594:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9595:     if (defined($env{'form.grade_symb'})) {
                   9596: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9597: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9598: 	if (!$allowed &&
                   9599: 	    exists($env{'request.course.sec'}) &&
                   9600: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9601: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9602: 			      '/'.$env{'request.course.sec'});
                   9603: 	}
                   9604: 	if ($allowed) {
                   9605: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9606: 	    $courseid=$tmp_courseid;
                   9607: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9608: 	    ($name)=&get_env_multiple('form.grade_username');
                   9609: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9610: 	}
                   9611:     }
                   9612:     if (!$passedsymb) {
                   9613: 	$symb=&symbread();
                   9614:     } else {
                   9615: 	$symb=$passedsymb;
                   9616:     }
                   9617:     $courseid=$env{'request.course.id'};
                   9618:     $domain=$env{'user.domain'};
                   9619:     $name=$env{'user.name'};
                   9620:     if ($name eq 'public' && $domain eq 'public') {
                   9621: 	if (!defined($env{'form.username'})) {
                   9622: 	    $env{'form.username'}.=time.rand(10000000);
                   9623: 	}
                   9624: 	$name.=$env{'form.username'};
                   9625:     }
                   9626:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9627: 
                   9628: }
                   9629: 
1.36      albertel 9630: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9631: # returns either the contents of the file or 
                   9632: # -1 if the file doesn't exist
1.481     raeburn  9633: #
                   9634: # if the target is a file that was uploaded via DOCS, 
                   9635: # a check will be made to see if a current copy exists on the local server,
                   9636: # if it does this will be served, otherwise a copy will be retrieved from
                   9637: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9638: # the local server.   
1.472     albertel 9639: 
1.36      albertel 9640: sub getfile {
1.538     albertel 9641:     my ($file) = @_;
1.609     banghart 9642:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9643:     &repcopy($file);
                   9644:     return &readfile($file);
                   9645: }
                   9646: 
                   9647: sub repcopy_userfile {
                   9648:     my ($file)=@_;
1.609     banghart 9649:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9650:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9651:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9652: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9653:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9654:     if (-e "$file") {
1.828     www      9655: # we already have a local copy, check it out
1.538     albertel 9656: 	my @fileinfo = stat($file);
1.828     www      9657: 	my $rtncode;
                   9658: 	my $info;
1.538     albertel 9659: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9660: 	if ($lwpresp ne 'ok') {
1.828     www      9661: # there is no such file anymore, even though we had a local copy
1.482     albertel 9662: 	    if ($rtncode eq '404') {
1.538     albertel 9663: 		unlink($file);
1.482     albertel 9664: 	    }
                   9665: 	    return -1;
                   9666: 	}
                   9667: 	if ($info < $fileinfo[9]) {
1.828     www      9668: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9669: 	    return 'ok';
1.828     www      9670: 	} else {
                   9671: # the file is outdated, get rid of it
                   9672: 	    unlink($file);
1.482     albertel 9673: 	}
1.828     www      9674:     }
                   9675: # one way or the other, at this point, we don't have the file
                   9676: # construct the correct path for the file
                   9677:     my @parts = ($cdom,$cnum); 
                   9678:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9679: 	push @parts, split(/\//,$1);
                   9680:     }
                   9681:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9682:     foreach my $part (@parts) {
                   9683: 	$path .= '/'.$part;
                   9684: 	if (!-e $path) {
                   9685: 	    mkdir($path,0770);
1.482     albertel 9686: 	}
                   9687:     }
1.828     www      9688: # now the path exists for sure
                   9689: # get a user agent
                   9690:     my $ua=new LWP::UserAgent;
                   9691:     my $transferfile=$file.'.in.transfer';
                   9692: # FIXME: this should flock
                   9693:     if (-e $transferfile) { return 'ok'; }
                   9694:     my $request;
                   9695:     $uri=~s/^\///;
1.980     raeburn  9696:     my $homeserver = &homeserver($cnum,$cdom);
                   9697:     my $protocol = $protocol{$homeserver};
                   9698:     $protocol = 'http' if ($protocol ne 'https');
                   9699:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9700:     my $response=$ua->request($request,$transferfile);
                   9701: # did it work?
                   9702:     if ($response->is_error()) {
                   9703: 	unlink($transferfile);
                   9704: 	&logthis("Userfile repcopy failed for $uri");
                   9705: 	return -1;
                   9706:     }
                   9707: # worked, rename the transfer file
                   9708:     rename($transferfile,$file);
1.607     raeburn  9709:     return 'ok';
1.481     raeburn  9710: }
                   9711: 
1.517     albertel 9712: sub tokenwrapper {
                   9713:     my $uri=shift;
1.980     raeburn  9714:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9715:     $uri=~s|^/||;
1.620     albertel 9716:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9717:     my $token=$1;
1.552     albertel 9718:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9719:     if ($udom && $uname && $file) {
                   9720: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9721:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9722:         my $homeserver = &homeserver($uname,$udom);
                   9723:         my $protocol = $protocol{$homeserver};
                   9724:         $protocol = 'http' if ($protocol ne 'https');
                   9725:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9726:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9727:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9728:     } else {
                   9729:         return '/adm/notfound.html';
                   9730:     }
                   9731: }
                   9732: 
1.828     www      9733: # call with reqtype HEAD: get last modification time
                   9734: # call with reqtype GET: get the file contents
                   9735: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9736: #
1.481     raeburn  9737: sub getuploaded {
                   9738:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9739:     $uri=~s/^\///;
1.980     raeburn  9740:     my $homeserver = &homeserver($cnum,$cdom);
                   9741:     my $protocol = $protocol{$homeserver};
                   9742:     $protocol = 'http' if ($protocol ne 'https');
                   9743:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9744:     my $ua=new LWP::UserAgent;
                   9745:     my $request=new HTTP::Request($reqtype,$uri);
                   9746:     my $response=$ua->request($request);
                   9747:     $$rtncode = $response->code;
1.482     albertel 9748:     if (! $response->is_success()) {
                   9749: 	return 'failed';
                   9750:     }      
                   9751:     if ($reqtype eq 'HEAD') {
1.486     www      9752: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9753:     } elsif ($reqtype eq 'GET') {
                   9754: 	$$info = $response->content;
1.472     albertel 9755:     }
1.482     albertel 9756:     return 'ok';
1.36      albertel 9757: }
                   9758: 
1.481     raeburn  9759: sub readfile {
                   9760:     my $file = shift;
                   9761:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9762:     my $fh;
                   9763:     open($fh,"<$file");
                   9764:     my $a='';
1.800     albertel 9765:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9766:     return $a;
                   9767: }
                   9768: 
1.36      albertel 9769: sub filelocation {
1.590     banghart 9770:     my ($dir,$file) = @_;
                   9771:     my $location;
                   9772:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9773: 
                   9774:     if ($file =~ m-^/adm/-) {
                   9775: 	$file=~s-^/adm/wrapper/-/-;
                   9776: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9777:     }
1.882     albertel 9778: 
1.590     banghart 9779:     if ($file=~m:^/~:) { # is a contruction space reference
                   9780:         $location = $file;
                   9781:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9782:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9783: 	# is a correct contruction space reference
                   9784:         $location = $file;
1.956     raeburn  9785:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9786:         $location = $file;
1.609     banghart 9787:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9788:         my ($udom,$uname,$filename)=
1.811     albertel 9789:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9790:         my $home=&homeserver($uname,$udom);
                   9791:         my $is_me=0;
                   9792:         my @ids=&current_machine_ids();
                   9793:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9794:         if ($is_me) {
1.955     raeburn  9795:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9796:         } else {
                   9797:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9798:   	      $udom.'/'.$uname.'/'.$filename;
                   9799:         }
1.882     albertel 9800:     } elsif ($file =~ m-^/adm/-) {
                   9801: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9802:     } else {
                   9803:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9804:         $file=~s:^/res/:/:;
                   9805:         if ( !( $file =~ m:^/:) ) {
                   9806:             $location = $dir. '/'.$file;
                   9807:         } else {
                   9808:             $location = '/home/httpd/html/res'.$file;
                   9809:         }
1.59      albertel 9810:     }
1.590     banghart 9811:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9812:     while ($location=~m{/\.\./}) {
                   9813: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9814: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9815: 	} else {
                   9816: 	    $location=~ s{/\.\./}{/}g;
                   9817: 	}
                   9818:     } #remove dir/..
1.590     banghart 9819:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9820:     return $location;
1.46      www      9821: }
1.36      albertel 9822: 
1.46      www      9823: sub hreflocation {
                   9824:     my ($dir,$file)=@_;
1.980     raeburn  9825:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9826: 	$file=filelocation($dir,$file);
1.700     albertel 9827:     } elsif ($file=~m-^/adm/-) {
                   9828: 	$file=~s-^/adm/wrapper/-/-;
                   9829: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9830:     }
                   9831:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9832: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9833:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9834: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9835:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9836: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9837: 	    -/uploaded/$1/$2/-x;
1.46      www      9838:     }
1.913     albertel 9839:     if ($file=~ m{^/userfiles/}) {
                   9840: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9841:     }
1.462     albertel 9842:     return $file;
1.465     albertel 9843: }
                   9844: 
                   9845: sub current_machine_domains {
1.853     albertel 9846:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9847: }
                   9848: 
                   9849: sub machine_domains {
                   9850:     my ($hostname) = @_;
1.465     albertel 9851:     my @domains;
1.838     albertel 9852:     my %hostname = &all_hostnames();
1.465     albertel 9853:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9854: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9855: 	if ($hostname eq $name) {
1.844     albertel 9856: 	    push(@domains,&host_domain($id));
1.465     albertel 9857: 	}
                   9858:     }
                   9859:     return @domains;
                   9860: }
                   9861: 
                   9862: sub current_machine_ids {
1.853     albertel 9863:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9864: }
                   9865: 
                   9866: sub machine_ids {
                   9867:     my ($hostname) = @_;
                   9868:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9869:     my @ids;
1.888     albertel 9870:     my %name_to_host = &all_names();
1.889     albertel 9871:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9872: 	return @{ $name_to_host{$hostname} };
                   9873:     }
                   9874:     return;
1.31      www      9875: }
                   9876: 
1.824     raeburn  9877: sub additional_machine_domains {
                   9878:     my @domains;
                   9879:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9880:     while( my $line = <$fh>) {
                   9881:         $line =~ s/\s//g;
                   9882:         push(@domains,$line);
                   9883:     }
                   9884:     return @domains;
                   9885: }
                   9886: 
                   9887: sub default_login_domain {
                   9888:     my $domain = $perlvar{'lonDefDomain'};
                   9889:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9890:     foreach my $posdom (&current_machine_domains(),
                   9891:                         &additional_machine_domains()) {
                   9892:         if (lc($posdom) eq lc($testdomain)) {
                   9893:             $domain=$posdom;
                   9894:             last;
                   9895:         }
                   9896:     }
                   9897:     return $domain;
                   9898: }
                   9899: 
1.31      www      9900: # ------------------------------------------------------------- Declutters URLs
                   9901: 
                   9902: sub declutter {
                   9903:     my $thisfn=shift;
1.569     albertel 9904:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9905:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9906:     $thisfn=~s/^\///;
1.697     albertel 9907:     $thisfn=~s|^adm/wrapper/||;
                   9908:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9909:     $thisfn=~s/^res\///;
1.1032    raeburn  9910:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9911:         $thisfn=~s/\?.+$//;
                   9912:     }
1.268     www      9913:     return $thisfn;
                   9914: }
                   9915: 
                   9916: # ------------------------------------------------------------- Clutter up URLs
                   9917: 
                   9918: sub clutter {
                   9919:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9920:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9921: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9922:        $thisfn='/res'.$thisfn; 
                   9923:     }
1.1031    raeburn  9924:     if ($thisfn !~m|^/adm|) {
                   9925: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9926: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9927: 	} else {
                   9928: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9929: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9930: 	    if ($embstyle eq 'ssi'
                   9931: 		|| ($embstyle eq 'hdn')
                   9932: 		|| ($embstyle eq 'rat')
                   9933: 		|| ($embstyle eq 'prv')
                   9934: 		|| ($embstyle eq 'ign')) {
                   9935: 		#do nothing with these
                   9936: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9937: 		|| ($embstyle eq 'emb')
                   9938: 		|| ($embstyle eq 'wrp')) {
                   9939: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9940: 	    } elsif ($embstyle eq 'unk'
                   9941: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9942: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9943: 	    } else {
1.718     www      9944: #		&logthis("Got a blank emb style");
1.695     albertel 9945: 	    }
1.694     albertel 9946: 	}
                   9947:     }
1.31      www      9948:     return $thisfn;
1.12      www      9949: }
                   9950: 
1.787     albertel 9951: sub clutter_with_no_wrapper {
                   9952:     my $uri = &clutter(shift);
                   9953:     if ($uri =~ m-^/adm/-) {
                   9954: 	$uri =~ s-^/adm/wrapper/-/-;
                   9955: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9956:     }
                   9957:     return $uri;
                   9958: }
                   9959: 
1.557     albertel 9960: sub freeze_escape {
                   9961:     my ($value)=@_;
                   9962:     if (ref($value)) {
                   9963: 	$value=&nfreeze($value);
                   9964: 	return '__FROZEN__'.&escape($value);
                   9965:     }
                   9966:     return &escape($value);
                   9967: }
                   9968: 
1.11      www      9969: 
1.557     albertel 9970: sub thaw_unescape {
                   9971:     my ($value)=@_;
                   9972:     if ($value =~ /^__FROZEN__/) {
                   9973: 	substr($value,0,10,undef);
                   9974: 	$value=&unescape($value);
                   9975: 	return &thaw($value);
                   9976:     }
                   9977:     return &unescape($value);
                   9978: }
                   9979: 
1.436     albertel 9980: sub correct_line_ends {
                   9981:     my ($result)=@_;
                   9982:     $$result =~s/\r\n/\n/mg;
                   9983:     $$result =~s/\r/\n/mg;
1.415     albertel 9984: }
1.1       albertel 9985: # ================================================================ Main Program
                   9986: 
1.184     www      9987: sub goodbye {
1.204     albertel 9988:    &logthis("Starting Shut down");
1.443     albertel 9989: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9990:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9991: #converted
1.599     albertel 9992: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9993:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9994: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9995: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9996: #1.1 only
1.870     albertel 9997: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9998: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9999: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10000: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10001:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10002:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10003:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10004:    &flushcourselogs();
                   10005:    &logthis("Shutting down");
                   10006: }
                   10007: 
1.852     albertel 10008: sub get_dns {
1.869     albertel 10009:     my ($url,$func,$ignore_cache) = @_;
                   10010:     if (!$ignore_cache) {
                   10011: 	my ($content,$cached)=
                   10012: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10013: 	if ($cached) {
                   10014: 	    &$func($content);
                   10015: 	    return;
                   10016: 	}
                   10017:     }
                   10018: 
                   10019:     my %alldns;
1.852     albertel 10020:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10021:     foreach my $dns (<$config>) {
                   10022: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10023:         my $line = $1;
                   10024:         my ($host,$protocol) = split(/:/,$line);
                   10025:         if ($protocol ne 'https') {
                   10026:             $protocol = 'http';
                   10027:         }
                   10028: 	$alldns{$host} = $protocol;
1.869     albertel 10029:     }
                   10030:     while (%alldns) {
                   10031: 	my ($dns) = keys(%alldns);
1.852     albertel 10032: 	my $ua=new LWP::UserAgent;
1.1056.4.33! raeburn  10033:         $ua->timeout(30);
1.979     raeburn  10034: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10035: 	my $response=$ua->request($request);
1.979     raeburn  10036:         delete($alldns{$dns});
1.852     albertel 10037: 	next if ($response->is_error());
                   10038: 	my @content = split("\n",$response->content);
1.869     albertel 10039: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10040: 	&$func(\@content);
1.869     albertel 10041: 	return;
1.852     albertel 10042:     }
                   10043:     close($config);
1.871     albertel 10044:     my $which = (split('/',$url))[3];
                   10045:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10046:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10047:     my @content = <$config>;
                   10048:     &$func(\@content);
                   10049:     return;
1.852     albertel 10050: }
1.327     albertel 10051: # ------------------------------------------------------------ Read domain file
                   10052: {
1.852     albertel 10053:     my $loaded;
1.846     albertel 10054:     my %domain;
                   10055: 
1.852     albertel 10056:     sub parse_domain_tab {
                   10057: 	my ($lines) = @_;
                   10058: 	foreach my $line (@$lines) {
                   10059: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10060: 
1.846     albertel 10061: 	    chomp($line);
1.852     albertel 10062: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10063: 	    my %this_domain;
                   10064: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10065: 			       'lang_def', 'city', 'longi', 'lati',
                   10066: 			       'primary') {
                   10067: 		$this_domain{$field} = shift(@elements);
                   10068: 	    }
                   10069: 	    $domain{$name} = \%this_domain;
1.852     albertel 10070: 	}
                   10071:     }
1.864     albertel 10072: 
                   10073:     sub reset_domain_info {
                   10074: 	undef($loaded);
                   10075: 	undef(%domain);
                   10076:     }
                   10077: 
1.852     albertel 10078:     sub load_domain_tab {
1.869     albertel 10079: 	my ($ignore_cache) = @_;
                   10080: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10081: 	my $fh;
                   10082: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10083: 	    my @lines = <$fh>;
                   10084: 	    &parse_domain_tab(\@lines);
1.448     albertel 10085: 	}
1.852     albertel 10086: 	close($fh);
                   10087: 	$loaded = 1;
1.327     albertel 10088:     }
1.846     albertel 10089: 
                   10090:     sub domain {
1.852     albertel 10091: 	&load_domain_tab() if (!$loaded);
                   10092: 
1.846     albertel 10093: 	my ($name,$what) = @_;
                   10094: 	return if ( !exists($domain{$name}) );
                   10095: 
                   10096: 	if (!$what) {
                   10097: 	    return $domain{$name}{'description'};
                   10098: 	}
                   10099: 	return $domain{$name}{$what};
                   10100:     }
1.974     raeburn  10101: 
                   10102:     sub domain_info {
                   10103:         &load_domain_tab() if (!$loaded);
                   10104:         return %domain;
                   10105:     }
                   10106: 
1.327     albertel 10107: }
                   10108: 
                   10109: 
1.1       albertel 10110: # ------------------------------------------------------------- Read hosts file
                   10111: {
1.838     albertel 10112:     my %hostname;
1.844     albertel 10113:     my %hostdom;
1.845     albertel 10114:     my %libserv;
1.852     albertel 10115:     my $loaded;
1.888     albertel 10116:     my %name_to_host;
1.1056.4.6  raeburn  10117:     my %internetdom;
1.1056.4.25  raeburn  10118:     my %LC_dns_serv;
1.852     albertel 10119: 
                   10120:     sub parse_hosts_tab {
                   10121: 	my ($file) = @_;
                   10122: 	foreach my $configline (@$file) {
                   10123: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1056.4.25  raeburn  10124:             chomp($configline);
                   10125:             if ($configline =~ /^\^/) {
                   10126:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10127:                     $LC_dns_serv{$1} = 1;
                   10128:                 }
                   10129:                 next;
                   10130:             }
1.1056.4.6  raeburn  10131: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10132: 	    $name=~s/\s//g;
                   10133: 	    if ($id && $domain && $role && $name) {
                   10134: 		$hostname{$id}=$name;
1.888     albertel 10135: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10136: 		$hostdom{$id}=$domain;
                   10137: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10138:                 if (defined($protocol)) {
                   10139:                     if ($protocol eq 'https') {
                   10140:                         $protocol{$id} = $protocol;
                   10141:                     } else {
                   10142:                         $protocol{$id} = 'http'; 
                   10143:                     }
1.968     raeburn  10144:                 } else {
1.969     raeburn  10145:                     $protocol{$id} = 'http';
1.968     raeburn  10146:                 }
1.1056.4.6  raeburn  10147:                 if (defined($intdom)) {
                   10148:                     $internetdom{$id} = $intdom;
                   10149:                 }
1.852     albertel 10150: 	    }
                   10151: 	}
                   10152:     }
1.864     albertel 10153:     
                   10154:     sub reset_hosts_info {
1.897     albertel 10155: 	&purge_remembered();
1.864     albertel 10156: 	&reset_domain_info();
                   10157: 	&reset_hosts_ip_info();
1.892     albertel 10158: 	undef(%name_to_host);
1.864     albertel 10159: 	undef(%hostname);
                   10160: 	undef(%hostdom);
                   10161: 	undef(%libserv);
                   10162: 	undef($loaded);
                   10163:     }
1.1       albertel 10164: 
1.852     albertel 10165:     sub load_hosts_tab {
1.869     albertel 10166: 	my ($ignore_cache) = @_;
                   10167: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10168: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10169: 	my @config = <$config>;
                   10170: 	&parse_hosts_tab(\@config);
                   10171: 	close($config);
                   10172: 	$loaded=1;
1.1       albertel 10173:     }
1.852     albertel 10174: 
1.838     albertel 10175:     sub hostname {
1.852     albertel 10176: 	&load_hosts_tab() if (!$loaded);
                   10177: 
1.838     albertel 10178: 	my ($lonid) = @_;
                   10179: 	return $hostname{$lonid};
                   10180:     }
1.845     albertel 10181: 
1.838     albertel 10182:     sub all_hostnames {
1.852     albertel 10183: 	&load_hosts_tab() if (!$loaded);
                   10184: 
1.838     albertel 10185: 	return %hostname;
                   10186:     }
1.845     albertel 10187: 
1.888     albertel 10188:     sub all_names {
                   10189: 	&load_hosts_tab() if (!$loaded);
                   10190: 
                   10191: 	return %name_to_host;
                   10192:     }
                   10193: 
1.974     raeburn  10194:     sub all_host_domain {
                   10195:         &load_hosts_tab() if (!$loaded);
                   10196:         return %hostdom;
                   10197:     }
                   10198: 
1.845     albertel 10199:     sub is_library {
1.852     albertel 10200: 	&load_hosts_tab() if (!$loaded);
                   10201: 
1.845     albertel 10202: 	return exists($libserv{$_[0]});
                   10203:     }
                   10204: 
                   10205:     sub all_library {
1.852     albertel 10206: 	&load_hosts_tab() if (!$loaded);
                   10207: 
1.845     albertel 10208: 	return %libserv;
                   10209:     }
                   10210: 
1.1056.4.2  raeburn  10211:     sub unique_library {
                   10212:         #2x reverse removes all hostnames that appear more than once
                   10213:         my %unique = reverse &all_library();
                   10214:         return reverse %unique;
                   10215:     }
                   10216: 
1.841     albertel 10217:     sub get_servers {
1.852     albertel 10218: 	&load_hosts_tab() if (!$loaded);
                   10219: 
1.841     albertel 10220: 	my ($domain,$type) = @_;
                   10221: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10222: 	                                          : %hostname;
                   10223: 	my %result;
1.842     albertel 10224: 	if (ref($domain) eq 'ARRAY') {
                   10225: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10226: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10227: 		    $result{$host} = $hostname;
                   10228: 		}
                   10229: 	    }
                   10230: 	} else {
                   10231: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10232: 		if ($hostdom{$host} eq $domain) {
                   10233: 		    $result{$host} = $hostname;
                   10234: 		}
1.841     albertel 10235: 	    }
                   10236: 	}
                   10237: 	return %result;
                   10238:     }
1.845     albertel 10239: 
1.1056.4.2  raeburn  10240:     sub get_unique_servers {
                   10241:         my %unique = reverse &get_servers(@_);
                   10242:         return reverse %unique;
                   10243:     }
                   10244: 
1.844     albertel 10245:     sub host_domain {
1.852     albertel 10246: 	&load_hosts_tab() if (!$loaded);
                   10247: 
1.844     albertel 10248: 	my ($lonid) = @_;
                   10249: 	return $hostdom{$lonid};
                   10250:     }
                   10251: 
1.841     albertel 10252:     sub all_domains {
1.852     albertel 10253: 	&load_hosts_tab() if (!$loaded);
                   10254: 
1.841     albertel 10255: 	my %seen;
                   10256: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10257: 	return @uniq;
                   10258:     }
1.1056.4.3  raeburn  10259: 
                   10260:     sub internet_dom {
                   10261:         &load_hosts_tab() if (!$loaded);
                   10262: 
                   10263:         my ($lonid) = @_;
                   10264:         return $internetdom{$lonid};
                   10265:     }
1.1056.4.27  raeburn  10266: 
                   10267:     sub is_LC_dns {
                   10268:         &load_hosts_tab() if (!$loaded);
                   10269: 
                   10270:         my ($hostname) = @_;
                   10271:         return exists($LC_dns_serv{$hostname});
                   10272:     }
                   10273: 
1.1       albertel 10274: }
                   10275: 
1.847     albertel 10276: { 
                   10277:     my %iphost;
1.856     albertel 10278:     my %name_to_ip;
                   10279:     my %lonid_to_ip;
1.869     albertel 10280: 
1.847     albertel 10281:     sub get_hosts_from_ip {
                   10282: 	my ($ip) = @_;
                   10283: 	my %iphosts = &get_iphost();
                   10284: 	if (ref($iphosts{$ip})) {
                   10285: 	    return @{$iphosts{$ip}};
                   10286: 	}
                   10287: 	return;
1.839     albertel 10288:     }
1.864     albertel 10289:     
                   10290:     sub reset_hosts_ip_info {
                   10291: 	undef(%iphost);
                   10292: 	undef(%name_to_ip);
                   10293: 	undef(%lonid_to_ip);
                   10294:     }
1.856     albertel 10295: 
                   10296:     sub get_host_ip {
                   10297: 	my ($lonid) = @_;
                   10298: 	if (exists($lonid_to_ip{$lonid})) {
                   10299: 	    return $lonid_to_ip{$lonid};
                   10300: 	}
                   10301: 	my $name=&hostname($lonid);
                   10302:    	my $ip = gethostbyname($name);
                   10303: 	return if (!$ip || length($ip) ne 4);
                   10304: 	$ip=inet_ntoa($ip);
                   10305: 	$name_to_ip{$name}   = $ip;
                   10306: 	$lonid_to_ip{$lonid} = $ip;
                   10307: 	return $ip;
                   10308:     }
1.847     albertel 10309:     
                   10310:     sub get_iphost {
1.869     albertel 10311: 	my ($ignore_cache) = @_;
1.894     albertel 10312: 
1.869     albertel 10313: 	if (!$ignore_cache) {
                   10314: 	    if (%iphost) {
                   10315: 		return %iphost;
                   10316: 	    }
                   10317: 	    my ($ip_info,$cached)=
                   10318: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10319: 	    if ($cached) {
                   10320: 		%iphost      = %{$ip_info->[0]};
                   10321: 		%name_to_ip  = %{$ip_info->[1]};
                   10322: 		%lonid_to_ip = %{$ip_info->[2]};
                   10323: 		return %iphost;
                   10324: 	    }
                   10325: 	}
1.894     albertel 10326: 
                   10327: 	# get yesterday's info for fallback
                   10328: 	my %old_name_to_ip;
                   10329: 	my ($ip_info,$cached)=
                   10330: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10331: 	if ($cached) {
                   10332: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10333: 	}
                   10334: 
1.888     albertel 10335: 	my %name_to_host = &all_names();
                   10336: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10337: 	    my $ip;
                   10338: 	    if (!exists($name_to_ip{$name})) {
                   10339: 		$ip = gethostbyname($name);
                   10340: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10341: 		    if (defined($old_name_to_ip{$name})) {
                   10342: 			$ip = $old_name_to_ip{$name};
                   10343: 			&logthis("Can't find $name defaulting to old $ip");
                   10344: 		    } else {
                   10345: 			&logthis("Name $name no IP found");
                   10346: 			next;
                   10347: 		    }
                   10348: 		} else {
                   10349: 		    $ip=inet_ntoa($ip);
1.847     albertel 10350: 		}
                   10351: 		$name_to_ip{$name} = $ip;
                   10352: 	    } else {
                   10353: 		$ip = $name_to_ip{$name};
1.653     albertel 10354: 	    }
1.888     albertel 10355: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10356: 		$lonid_to_ip{$id} = $ip;
                   10357: 	    }
                   10358: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10359: 	}
1.869     albertel 10360: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10361: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10362: 				      48*60*60);
1.869     albertel 10363: 
1.847     albertel 10364: 	return %iphost;
1.598     albertel 10365:     }
                   10366: 
1.992     raeburn  10367:     #
                   10368:     #  Given a DNS returns the loncapa host name for that DNS 
                   10369:     # 
                   10370:     sub host_from_dns {
                   10371:         my ($dns) = @_;
                   10372:         my @hosts;
                   10373:         my $ip;
                   10374: 
1.993     raeburn  10375:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10376:             $ip = $name_to_ip{$dns};
                   10377:         }
                   10378:         if (!$ip) {
                   10379:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10380:             if (length($ip) == 4) { 
                   10381: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10382:             }
                   10383:         }
                   10384:         if ($ip) {
                   10385: 	    @hosts = get_hosts_from_ip($ip);
                   10386: 	    return $hosts[0];
                   10387:         }
                   10388:         return undef;
1.986     foxr     10389:     }
1.992     raeburn  10390: 
1.1056.4.3  raeburn  10391:     sub get_internet_names {
                   10392:         my ($lonid) = @_;
                   10393:         return if ($lonid eq '');
                   10394:         my ($idnref,$cached)=
                   10395:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10396:         if ($cached) {
                   10397:             return $idnref;
                   10398:         }
                   10399:         my $ip = &get_host_ip($lonid);
                   10400:         my @hosts = &get_hosts_from_ip($ip);
                   10401:         my %iphost = &get_iphost();
                   10402:         my (@idns,%seen);
                   10403:         foreach my $id (@hosts) {
                   10404:             my $dom = &host_domain($id);
                   10405:             my $prim_id = &domain($dom,'primary');
                   10406:             my $prim_ip = &get_host_ip($prim_id);
                   10407:             next if ($seen{$prim_ip});
                   10408:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10409:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10410:                     my $intdom = &internet_dom($id);
                   10411:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10412:                         push(@idns,$intdom);
                   10413:                     }
                   10414:                 }
                   10415:             }
                   10416:             $seen{$prim_ip} = 1;
                   10417:         }
                   10418:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10419:     }
                   10420: 
                   10421: }
                   10422: 
                   10423: sub all_loncaparevs {
                   10424:     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     10425: }
                   10426: 
1.862     albertel 10427: BEGIN {
                   10428: 
                   10429: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10430:     unless ($readit) {
                   10431: {
                   10432:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10433:     %perlvar = (%perlvar,%{$configvars});
                   10434: }
                   10435: 
                   10436: 
1.1       albertel 10437: # ------------------------------------------------------ Read spare server file
                   10438: {
1.448     albertel 10439:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10440: 
                   10441:     while (my $configline=<$config>) {
                   10442:        chomp($configline);
1.284     matthew  10443:        if ($configline) {
1.784     albertel 10444: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10445: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10446: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10447:        }
                   10448:     }
1.448     albertel 10449:     close($config);
1.1       albertel 10450: }
1.11      www      10451: # ------------------------------------------------------------ Read permissions
                   10452: {
1.448     albertel 10453:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10454: 
                   10455:     while (my $configline=<$config>) {
1.448     albertel 10456: 	chomp($configline);
                   10457: 	if ($configline) {
                   10458: 	    my ($role,$perm)=split(/ /,$configline);
                   10459: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10460: 	}
1.11      www      10461:     }
1.448     albertel 10462:     close($config);
1.11      www      10463: }
                   10464: 
                   10465: # -------------------------------------------- Read plain texts for permissions
                   10466: {
1.448     albertel 10467:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10468: 
                   10469:     while (my $configline=<$config>) {
1.448     albertel 10470: 	chomp($configline);
                   10471: 	if ($configline) {
1.742     raeburn  10472: 	    my ($short,@plain)=split(/:/,$configline);
                   10473:             %{$prp{$short}} = ();
                   10474: 	    if (@plain > 0) {
                   10475:                 $prp{$short}{'std'} = $plain[0];
                   10476:                 for (my $i=1; $i<@plain; $i++) {
                   10477:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10478:                 }
                   10479:             }
1.448     albertel 10480: 	}
1.135     www      10481:     }
1.448     albertel 10482:     close($config);
1.135     www      10483: }
                   10484: 
                   10485: # ---------------------------------------------------------- Read package table
                   10486: {
1.448     albertel 10487:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10488: 
                   10489:     while (my $configline=<$config>) {
1.483     albertel 10490: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10491: 	chomp($configline);
                   10492: 	my ($short,$plain)=split(/:/,$configline);
                   10493: 	my ($pack,$name)=split(/\&/,$short);
                   10494: 	if ($plain ne '') {
                   10495: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10496: 	    $packagetab{$short}=$plain; 
                   10497: 	}
1.11      www      10498:     }
1.448     albertel 10499:     close($config);
1.329     matthew  10500: }
                   10501: 
1.1056.4.3  raeburn  10502: # ---------------------------------------------------------- Read loncaparev table
                   10503: {
                   10504:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10505:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10506:             while (my $configline=<$config>) {
                   10507:                 chomp($configline);
                   10508:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10509:                 $loncaparevs{$hostid}=$loncaparev;
                   10510:             }
                   10511:             close($config);
                   10512:         }
                   10513:     }
                   10514: }
                   10515: 
                   10516: # ---------------------------------------------------------- Read serverhostID table
                   10517: {
                   10518:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10519:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10520:             while (my $configline=<$config>) {
                   10521:                 chomp($configline);
                   10522:                 my ($name,$id)=split(/:/,$configline);
                   10523:                 $serverhomeIDs{$name}=$id;
                   10524:             }
                   10525:             close($config);
                   10526:         }
                   10527:     }
                   10528: }
                   10529: 
1.1056.4.5  raeburn  10530: {
                   10531:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10532:     if (-e $file) {
                   10533:         my $parser = HTML::LCParser->new($file);
                   10534:         while (my $token = $parser->get_token()) {
                   10535:             if ($token->[0] eq 'S') {
                   10536:                 my $item = $token->[1];
                   10537:                 my $name = $token->[2]{'name'};
                   10538:                 my $value = $token->[2]{'value'};
                   10539:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10540:                     my $release = $parser->get_text();
                   10541:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10542:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10543:                 }
                   10544:             }
                   10545:         }
                   10546:     }
                   10547: }
                   10548: 
1.1056.4.33! raeburn  10549: # ---------------------------------------------------------- Read managers table
        !          10550: {
        !          10551:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
        !          10552:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
        !          10553:             while (my $configline=<$config>) {
        !          10554:                 chomp($configline);
        !          10555:                 next if ($configline =~ /^\#/);
        !          10556:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
        !          10557:                     $managerstab{$configline} = 1;
        !          10558:                 }
        !          10559:             }
        !          10560:             close($config);
        !          10561:         }
        !          10562:     }
        !          10563: }
        !          10564: 
1.329     matthew  10565: # ------------- set up temporary directory
                   10566: {
                   10567:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   10568: 
1.11      www      10569: }
                   10570: 
1.794     albertel 10571: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10572: 				'compress_threshold'=> 20_000,
                   10573:  			        });
1.185     www      10574: 
1.281     www      10575: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10576: $dumpcount=0;
1.958     www      10577: $locknum=0;
1.22      www      10578: 
1.163     harris41 10579: &logtouch();
1.672     albertel 10580: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10581: $readit=1;
1.564     albertel 10582:     {
                   10583: 	use integer;
                   10584: 	my $test=(2**32)+1;
1.568     albertel 10585: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10586: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10587:     }
1.195     www      10588: }
1.1       albertel 10589: }
1.179     www      10590: 
1.1       albertel 10591: 1;
1.191     harris41 10592: __END__
                   10593: 
1.243     albertel 10594: =pod
                   10595: 
1.191     harris41 10596: =head1 NAME
                   10597: 
1.243     albertel 10598: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10599: 
                   10600: =head1 SYNOPSIS
                   10601: 
1.243     albertel 10602: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10603: 
                   10604:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10605: 
1.243     albertel 10606: Common parameters:
                   10607: 
                   10608: =over 4
                   10609: 
                   10610: =item *
                   10611: 
                   10612: $uname : an internal username (if $cname expecting a course Id specifically)
                   10613: 
                   10614: =item *
                   10615: 
                   10616: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10617: 
                   10618: =item *
                   10619: 
                   10620: $symb : a resource instance identifier
                   10621: 
                   10622: =item *
                   10623: 
                   10624: $namespace : the name of a .db file that contains the data needed or
                   10625: being set.
                   10626: 
                   10627: =back
                   10628: 
1.394     bowersj2 10629: =head1 OVERVIEW
1.191     harris41 10630: 
1.394     bowersj2 10631: lonnet provides subroutines which interact with the
                   10632: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10633: about classes, users, and resources.
1.243     albertel 10634: 
                   10635: For many of these objects you can also use this to store data about
                   10636: them or modify them in various ways.
1.191     harris41 10637: 
1.394     bowersj2 10638: =head2 Symbs
1.191     harris41 10639: 
1.394     bowersj2 10640: To identify a specific instance of a resource, LON-CAPA uses symbols
                   10641: or "symbs"X<symb>. These identifiers are built from the URL of the
                   10642: map, the resource number of the resource in the map, and the URL of
                   10643: the resource itself. The latter is somewhat redundant, but might help
                   10644: if maps change.
                   10645: 
                   10646: An example is
                   10647: 
                   10648:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   10649: 
                   10650: The respective map entry is
                   10651: 
                   10652:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   10653:   title="Problem 2">
                   10654:  </resource>
                   10655: 
                   10656: Symbs are used by the random number generator, as well as to store and
                   10657: restore data specific to a certain instance of for example a problem.
                   10658: 
                   10659: =head2 Storing And Retrieving Data
                   10660: 
                   10661: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   10662: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   10663: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   10664: is is the non-critical message twin of cstore. These functions are for
                   10665: handlers to store a perl hash to a user's permanent data space in an
                   10666: easy manner, and to retrieve it again on another call. It is expected
                   10667: that a handler would use this once at the beginning to retrieve data,
                   10668: and then again once at the end to send only the new data back.
                   10669: 
                   10670: The data is stored in the user's data directory on the user's
                   10671: homeserver under the ID of the course.
                   10672: 
                   10673: The hash that is returned by restore will have all of the previous
                   10674: value for all of the elements of the hash.
                   10675: 
                   10676: Example:
                   10677: 
                   10678:  #creating a hash
                   10679:  my %hash;
                   10680:  $hash{'foo'}='bar';
                   10681: 
                   10682:  #storing it
                   10683:  &Apache::lonnet::cstore(\%hash);
                   10684: 
                   10685:  #changing a value
                   10686:  $hash{'foo'}='notbar';
                   10687: 
                   10688:  #adding a new value
                   10689:  $hash{'bar'}='foo';
                   10690:  &Apache::lonnet::cstore(\%hash);
                   10691: 
                   10692:  #retrieving the hash
                   10693:  my %history=&Apache::lonnet::restore();
                   10694: 
                   10695:  #print the hash
                   10696:  foreach my $key (sort(keys(%history))) {
                   10697:    print("\%history{$key} = $history{$key}");
                   10698:  }
                   10699: 
                   10700: Will print out:
1.191     harris41 10701: 
1.394     bowersj2 10702:  %history{1:foo} = bar
                   10703:  %history{1:keys} = foo:timestamp
                   10704:  %history{1:timestamp} = 990455579
                   10705:  %history{2:bar} = foo
                   10706:  %history{2:foo} = notbar
                   10707:  %history{2:keys} = foo:bar:timestamp
                   10708:  %history{2:timestamp} = 990455580
                   10709:  %history{bar} = foo
                   10710:  %history{foo} = notbar
                   10711:  %history{timestamp} = 990455580
                   10712:  %history{version} = 2
                   10713: 
                   10714: Note that the special hash entries C<keys>, C<version> and
                   10715: C<timestamp> were added to the hash. C<version> will be equal to the
                   10716: total number of versions of the data that have been stored. The
                   10717: C<timestamp> attribute will be the UNIX time the hash was
                   10718: stored. C<keys> is available in every historical section to list which
                   10719: keys were added or changed at a specific historical revision of a
                   10720: hash.
                   10721: 
                   10722: B<Warning>: do not store the hash that restore returns directly. This
                   10723: will cause a mess since it will restore the historical keys as if the
                   10724: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10725: 
1.394     bowersj2 10726: Calling convention:
1.191     harris41 10727: 
1.394     bowersj2 10728:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10729:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10730: 
1.394     bowersj2 10731: For more detailed information, see lonnet specific documentation.
1.191     harris41 10732: 
1.394     bowersj2 10733: =head1 RETURN MESSAGES
1.191     harris41 10734: 
1.394     bowersj2 10735: =over 4
1.191     harris41 10736: 
1.394     bowersj2 10737: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10738: 
1.394     bowersj2 10739: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10740: when the connection is brought back up
1.191     harris41 10741: 
1.394     bowersj2 10742: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10743: for later delivery
1.191     harris41 10744: 
1.967     bisitz   10745: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10746: 
1.394     bowersj2 10747: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10748: that was requested
1.191     harris41 10749: 
1.243     albertel 10750: =back
1.191     harris41 10751: 
1.243     albertel 10752: =head1 PUBLIC SUBROUTINES
1.191     harris41 10753: 
1.243     albertel 10754: =head2 Session Environment Functions
1.191     harris41 10755: 
1.243     albertel 10756: =over 4
1.191     harris41 10757: 
1.394     bowersj2 10758: =item * 
                   10759: X<appenv()>
1.949     raeburn  10760: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10761: the user envirnoment file, and will be restored for each access this
1.620     albertel 10762: user makes during this session, also modifies the %env for the current
1.949     raeburn  10763: process. Optional rolesarrayref - if defined contains a reference to an array
                   10764: of roles which are exempt from the restriction on modifying user.role entries 
                   10765: in the user's environment.db and in %env.    
1.191     harris41 10766: 
                   10767: =item *
1.394     bowersj2 10768: X<delenv()>
1.987     raeburn  10769: B<delenv($delthis,$regexp)>: removes all items from the session
                   10770: environment file that begin with $delthis. If the 
                   10771: optional second arg - $regexp - is true, $delthis is treated as a 
                   10772: regular expression, otherwise \Q$delthis\E is used. 
                   10773: The values are also deleted from the current processes %env.
1.191     harris41 10774: 
1.795     albertel 10775: =item * get_env_multiple($name) 
                   10776: 
                   10777: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10778: values may be defined and end up as an array ref.
                   10779: 
                   10780: returns an array of values
                   10781: 
1.243     albertel 10782: =back
                   10783: 
                   10784: =head2 User Information
1.191     harris41 10785: 
1.243     albertel 10786: =over 4
1.191     harris41 10787: 
                   10788: =item *
1.394     bowersj2 10789: X<queryauthenticate()>
                   10790: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10791: authentication scheme
                   10792: 
                   10793: =item *
1.394     bowersj2 10794: X<authenticate()>
1.1056.4.3  raeburn  10795: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 10796: authenticate user from domain's lib servers (first use the current
                   10797: one). C<$upass> should be the users password.
1.1056.4.3  raeburn  10798: $checkdefauth is optional (value is 1 if a check should be made to
                   10799:    authenticate user using default authentication method, and allow
                   10800:    account creation if username does not have account in the domain).
                   10801: $clientcancheckhost is optional (value is 1 if checking whether the
                   10802:    server can host will occur on the client side in lonauth.pm).
1.191     harris41 10803: 
                   10804: =item *
1.394     bowersj2 10805: X<homeserver()>
                   10806: B<homeserver($uname,$udom)>: find the server which has
                   10807: the user's directory and files (there must be only one), this caches
                   10808: the answer, and also caches if there is a borken connection.
1.191     harris41 10809: 
                   10810: =item *
1.394     bowersj2 10811: X<idget()>
                   10812: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10813: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10814: username, and only 1 username per ID in a specific domain) (returns
                   10815: hash: id=>name,id=>name)
1.191     harris41 10816: 
                   10817: =item *
1.394     bowersj2 10818: X<idrget()>
                   10819: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10820: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10821: 
                   10822: =item *
1.394     bowersj2 10823: X<idput()>
                   10824: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10825: 
                   10826: =item *
1.394     bowersj2 10827: X<rolesinit()>
                   10828: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10829: 
                   10830: =item *
1.551     albertel 10831: X<getsection()>
                   10832: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10833: course $cname, return section name/number or '' for "not in course"
                   10834: and '-1' for "no section"
                   10835: 
                   10836: =item *
1.394     bowersj2 10837: X<userenvironment()>
                   10838: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10839: passed in @what from the requested user's environment, returns a hash
                   10840: 
1.858     raeburn  10841: =item * 
                   10842: X<userlog_query()>
1.859     albertel 10843: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10844: activity.log file. %filters defines filters applied when parsing the
                   10845: log file. These can be start or end timestamps, or the type of action
                   10846: - log to look for Login or Logout events, check for Checkin or
                   10847: Checkout, role for role selection. The response is in the form
                   10848: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10849: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10850: 
1.243     albertel 10851: =back
                   10852: 
                   10853: =head2 User Roles
                   10854: 
                   10855: =over 4
                   10856: 
                   10857: =item *
                   10858: 
1.810     raeburn  10859: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10860:  F: full access
                   10861:  U,I,K: authentication modes (cxx only)
                   10862:  '': forbidden
                   10863:  1: user needs to choose course
                   10864:  2: browse allowed
1.766     albertel 10865:  A: passphrase authentication needed
1.243     albertel 10866: 
                   10867: =item *
                   10868: 
                   10869: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10870: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10871: and course level
                   10872: 
                   10873: =item *
                   10874: 
1.988     raeburn  10875: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10876: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10877: $type is Course (default) or Community.
1.988     raeburn  10878: If $forcedefault evaluates to true, text returned will be default 
                   10879: text for $type. Otherwise, if this is a course, the text returned 
                   10880: will be a custom name for the role (if defined in the course's 
                   10881: environment).  If no custom name is defined the default is returned.
                   10882:    
1.832     raeburn  10883: =item *
                   10884: 
1.935     raeburn  10885: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10886: All arguments are optional. Returns a hash of a roles, either for
                   10887: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10888: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10889: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10890: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10891: For each key, value is set to colon-separated start and end times for
                   10892: the role.  If no username and domain are specified, will default to
1.934     raeburn  10893: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10894: of role statuses (active, future or previous), roles 
                   10895: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10896: to restrict the list of roles reported. If no array ref is 
                   10897: provided for types, will default to return only active roles.
1.834     albertel 10898: 
1.243     albertel 10899: =back
                   10900: 
                   10901: =head2 User Modification
                   10902: 
                   10903: =over 4
                   10904: 
                   10905: =item *
                   10906: 
1.957     raeburn  10907: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10908: user for the level given by URL.  Optional start and end dates (leave empty
                   10909: string or zero for "no date")
1.191     harris41 10910: 
                   10911: =item *
                   10912: 
1.243     albertel 10913: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10914: change a users, password, possible return values are: ok,
                   10915: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10916: refused
1.191     harris41 10917: 
                   10918: =item *
                   10919: 
1.243     albertel 10920: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10921: 
                   10922: =item *
                   10923: 
1.1056.4.1  raeburn  10924: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   10925:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   10926: 
                   10927: will update user information (firstname,middlename,lastname,generation,
                   10928: permanentemail), and if forceid is true, student/employee ID also.
                   10929: A user's institutional affiliation(s) can also be updated.
                   10930: User information fields will not be overwritten with empty entries 
                   10931: unless the field is included in the $candelete array reference.
                   10932: This array is included when a single user is modified via "Manage Users",
                   10933: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 10934: 
                   10935: =item *
                   10936: 
1.286     matthew  10937: modifystudent
                   10938: 
1.957     raeburn  10939: modify a student's enrollment and identification information.
1.286     matthew  10940: The course id is resolved based on the current users environment.  
                   10941: This means the envoking user must be a course coordinator or otherwise
                   10942: associated with a course.
                   10943: 
1.297     matthew  10944: This call is essentially a wrapper for lonnet::modifyuser and
                   10945: lonnet::modify_student_enrollment
1.286     matthew  10946: 
                   10947: Inputs: 
                   10948: 
                   10949: =over 4
                   10950: 
1.957     raeburn  10951: =item B<$udom> Student's loncapa domain
1.286     matthew  10952: 
1.957     raeburn  10953: =item B<$uname> Student's loncapa login name
1.286     matthew  10954: 
1.964     bisitz   10955: =item B<$uid> Student/Employee ID
1.286     matthew  10956: 
1.957     raeburn  10957: =item B<$umode> Student's authentication mode
1.286     matthew  10958: 
1.957     raeburn  10959: =item B<$upass> Student's password
1.286     matthew  10960: 
1.957     raeburn  10961: =item B<$first> Student's first name
1.286     matthew  10962: 
1.957     raeburn  10963: =item B<$middle> Student's middle name
1.286     matthew  10964: 
1.957     raeburn  10965: =item B<$last> Student's last name
1.286     matthew  10966: 
1.957     raeburn  10967: =item B<$gene> Student's generation
1.286     matthew  10968: 
1.957     raeburn  10969: =item B<$usec> Student's section in course
1.286     matthew  10970: 
                   10971: =item B<$end> Unix time of the roles expiration
                   10972: 
                   10973: =item B<$start> Unix time of the roles start date
                   10974: 
                   10975: =item B<$forceid> If defined, allow $uid to be changed
                   10976: 
                   10977: =item B<$desiredhome> server to use as home server for student
                   10978: 
1.957     raeburn  10979: =item B<$email> Student's permanent e-mail address
                   10980: 
                   10981: =item B<$type> Type of enrollment (auto or manual)
                   10982: 
1.963     raeburn  10983: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10984: 
                   10985: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10986: 
1.963     raeburn  10987: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10988: 
1.963     raeburn  10989: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10990: 
1.963     raeburn  10991: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10992: 
1.286     matthew  10993: =back
1.297     matthew  10994: 
                   10995: =item *
                   10996: 
                   10997: modify_student_enrollment
                   10998: 
                   10999: Change a students enrollment status in a class.  The environment variable
                   11000: 'role.request.course' must be defined for this function to proceed.
                   11001: 
                   11002: Inputs:
                   11003: 
                   11004: =over 4
                   11005: 
                   11006: =item $udom, students domain
                   11007: 
                   11008: =item $uname, students name
                   11009: 
                   11010: =item $uid, students user id
                   11011: 
                   11012: =item $first, students first name
                   11013: 
                   11014: =item $middle
                   11015: 
                   11016: =item $last
                   11017: 
                   11018: =item $gene
                   11019: 
                   11020: =item $usec
                   11021: 
                   11022: =item $end
                   11023: 
                   11024: =item $start
                   11025: 
1.957     raeburn  11026: =item $type
                   11027: 
                   11028: =item $locktype
                   11029: 
                   11030: =item $cid
                   11031: 
                   11032: =item $selfenroll
                   11033: 
                   11034: =item $context
                   11035: 
1.297     matthew  11036: =back
                   11037: 
1.191     harris41 11038: 
                   11039: =item *
                   11040: 
1.243     albertel 11041: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11042: custom role; give a custom role to a user for the level given by URL.  Specify
                   11043: name and domain of role author, and role name
1.191     harris41 11044: 
                   11045: =item *
                   11046: 
1.243     albertel 11047: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11048: 
                   11049: =item *
                   11050: 
1.243     albertel 11051: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11052: 
                   11053: =back
                   11054: 
                   11055: =head2 Course Infomation
                   11056: 
                   11057: =over 4
1.191     harris41 11058: 
                   11059: =item *
                   11060: 
1.631     albertel 11061: coursedescription($courseid) : returns a hash of information about the
                   11062: specified course id, including all environment settings for the
                   11063: course, the description of the course will be in the hash under the
                   11064: key 'description'
1.191     harris41 11065: 
                   11066: =item *
                   11067: 
1.624     albertel 11068: resdata($name,$domain,$type,@which) : request for current parameter
                   11069: setting for a specific $type, where $type is either 'course' or 'user',
                   11070: @what should be a list of parameters to ask about. This routine caches
                   11071: answers for 5 minutes.
1.243     albertel 11072: 
1.877     foxr     11073: =item *
                   11074: 
                   11075: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11076: data base, returning a hash that is keyed by the resource name and has
                   11077: values that are the resource value.  I believe that the timestamps and
                   11078: versions are also returned.
                   11079: 
                   11080: 
1.243     albertel 11081: =back
                   11082: 
                   11083: =head2 Course Modification
                   11084: 
                   11085: =over 4
1.191     harris41 11086: 
                   11087: =item *
                   11088: 
1.243     albertel 11089: writecoursepref($courseid,%prefs) : write preferences (environment
                   11090: database) for a course
1.191     harris41 11091: 
                   11092: =item *
                   11093: 
1.1011    raeburn  11094: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11095: 
                   11096: =item *
                   11097: 
1.1038    raeburn  11098: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11099: 
                   11100: =back
                   11101: 
                   11102: =head2 Resource Subroutines
                   11103: 
                   11104: =over 4
1.191     harris41 11105: 
                   11106: =item *
                   11107: 
1.243     albertel 11108: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11109: 
                   11110: =item *
                   11111: 
1.243     albertel 11112: repcopy($filename) : subscribes to the requested file, and attempts to
                   11113: replicate from the owning library server, Might return
1.607     raeburn  11114: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11115: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11116: resource. Expects the local filesystem pathname
                   11117: (/home/httpd/html/res/....)
                   11118: 
                   11119: =back
                   11120: 
                   11121: =head2 Resource Information
                   11122: 
                   11123: =over 4
1.191     harris41 11124: 
                   11125: =item *
                   11126: 
1.243     albertel 11127: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11128: a vairety of different possible values, $varname should be a request
                   11129: string, and the other parameters can be used to specify who and what
                   11130: one is asking about.
                   11131: 
                   11132: Possible values for $varname are environment.lastname (or other item
                   11133: from the envirnment hash), user.name (or someother aspect about the
                   11134: user), resource.0.maxtries (or some other part and parameter of a
                   11135: resource)
1.204     albertel 11136: 
                   11137: =item *
                   11138: 
1.243     albertel 11139: directcondval($number) : get current value of a condition; reads from a state
                   11140: string
1.204     albertel 11141: 
                   11142: =item *
                   11143: 
1.243     albertel 11144: condval($condidx) : value of condition index based on state
1.204     albertel 11145: 
                   11146: =item *
                   11147: 
1.243     albertel 11148: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11149: resource's metadata, $what should be either a specific key, or either
                   11150: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11151: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11152: 
                   11153: this function automatically caches all requests
1.191     harris41 11154: 
                   11155: =item *
                   11156: 
1.243     albertel 11157: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11158: network of library servers; returns file handle of where SQL and regex results
                   11159: will be stored for query
1.191     harris41 11160: 
                   11161: =item *
                   11162: 
1.243     albertel 11163: symbread($filename) : return symbolic list entry (filename argument optional);
                   11164: returns the data handle
1.191     harris41 11165: 
                   11166: =item *
                   11167: 
1.243     albertel 11168: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11169: a possible symb for the URL in $thisfn, and if is an encryypted
                   11170: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11171: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11172: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11173: 
1.191     harris41 11174: 
                   11175: =item *
                   11176: 
1.243     albertel 11177: symbclean($symb) : removes versions numbers from a symb, returns the
                   11178: cleaned symb
1.191     harris41 11179: 
                   11180: =item *
                   11181: 
1.243     albertel 11182: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11183: course map, user must be in a course for it to work.
1.191     harris41 11184: 
                   11185: =item *
                   11186: 
1.243     albertel 11187: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11188: 
                   11189: =item *
                   11190: 
1.243     albertel 11191: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11192: a random seed, all arguments are optional, if they aren't sent it uses the
                   11193: environment to derive them. Note: if symb isn't sent and it can't get one
                   11194: from &symbread it will use the current time as its return value
1.191     harris41 11195: 
                   11196: =item *
                   11197: 
1.243     albertel 11198: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11199: unfakeable, receipt
1.191     harris41 11200: 
                   11201: =item *
                   11202: 
1.620     albertel 11203: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11204: 
                   11205: =item *
                   11206: 
1.243     albertel 11207: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11208: 
                   11209: =item *
                   11210: 
1.243     albertel 11211: 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 11212: 
                   11213: =item *
                   11214: 
1.243     albertel 11215: 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 11216: 
                   11217: =item *
                   11218: 
1.243     albertel 11219: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11220: 
                   11221: =item *
                   11222: 
1.243     albertel 11223: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11224: forcing spreadsheet to reevaluate the resource scores next time.
                   11225: 
                   11226: =back
                   11227: 
                   11228: =head2 Storing/Retreiving Data
                   11229: 
                   11230: =over 4
1.191     harris41 11231: 
                   11232: =item *
                   11233: 
1.243     albertel 11234: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11235: for this url; hashref needs to be given and should be a \%hashname; the
                   11236: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11237: be derived from the env
1.191     harris41 11238: 
                   11239: =item *
                   11240: 
1.243     albertel 11241: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11242: uses critical subroutine
1.191     harris41 11243: 
                   11244: =item *
                   11245: 
1.243     albertel 11246: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11247: all args are optional
1.191     harris41 11248: 
                   11249: =item *
                   11250: 
1.717     albertel 11251: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11252: dumps the complete (or key matching regexp) namespace into a hash
                   11253: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11254: normally &store()ed into
                   11255: 
                   11256: $range should be either an integer '100' (give me the first 100
                   11257:                                            matching records)
                   11258:               or be  two integers sperated by a - with no spaces
                   11259:                  '30-50' (give me the 30th through the 50th matching
                   11260:                           records)
                   11261: 
                   11262: 
                   11263: =item *
                   11264: 
                   11265: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11266: replaces a &store() version of data with a replacement set of data
                   11267: for a particular resource in a namespace passed in the $storehash hash 
                   11268: reference
                   11269: 
                   11270: =item *
                   11271: 
1.243     albertel 11272: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11273: works very similar to store/cstore, but all data is stored in a
                   11274: temporary location and can be reset using tmpreset, $storehash should
                   11275: be a hash reference, returns nothing on success
1.191     harris41 11276: 
                   11277: =item *
                   11278: 
1.243     albertel 11279: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11280: similar to restore, but all data is stored in a temporary location and
                   11281: can be reset using tmpreset. Returns a hash of values on success,
                   11282: error string otherwise.
1.191     harris41 11283: 
                   11284: =item *
                   11285: 
1.243     albertel 11286: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11287: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11288: 
                   11289: =item *
                   11290: 
1.243     albertel 11291: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11292: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11293: 
                   11294: =item *
                   11295: 
1.243     albertel 11296: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11297: namesp ($udom and $uname are optional)
1.191     harris41 11298: 
                   11299: =item *
                   11300: 
1.702     albertel 11301: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11302: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11303: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11304: 
1.702     albertel 11305: $range should be either an integer '100' (give me the first 100
                   11306:                                            matching records)
                   11307:               or be  two integers sperated by a - with no spaces
                   11308:                  '30-50' (give me the 30th through the 50th matching
                   11309:                           records)
1.449     matthew  11310: =item *
                   11311: 
                   11312: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11313: $store can be a scalar, an array reference, or if the amount to be 
                   11314: incremented is > 1, a hash reference.
                   11315: 
                   11316: ($udom and $uname are optional)
1.191     harris41 11317: 
                   11318: =item *
                   11319: 
1.243     albertel 11320: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11321: ($udom and $uname are optional)
1.191     harris41 11322: 
                   11323: =item *
                   11324: 
1.243     albertel 11325: cput($namespace,$storehash,$udom,$uname) : critical put
                   11326: ($udom and $uname are optional)
1.191     harris41 11327: 
                   11328: =item *
                   11329: 
1.748     albertel 11330: newput($namespace,$storehash,$udom,$uname) :
                   11331: 
                   11332: Attempts to store the items in the $storehash, but only if they don't
                   11333: currently exist, if this succeeds you can be certain that you have 
                   11334: successfully created a new key value pair in the $namespace db.
                   11335: 
                   11336: 
                   11337: Args:
                   11338:  $namespace: name of database to store values to
                   11339:  $storehash: hashref to store to the db
                   11340:  $udom: (optional) domain of user containing the db
                   11341:  $uname: (optional) name of user caontaining the db
                   11342: 
                   11343: Returns:
                   11344:  'ok' -> succeeded in storing all keys of $storehash
                   11345:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11346:                         least <key> already existed in the db (other
                   11347:                         requested keys may also already exist)
1.967     bisitz   11348:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11349:  'con_lost' -> unable to contact request server
                   11350:  'refused' -> action was not allowed by remote machine
                   11351: 
                   11352: 
                   11353: =item *
                   11354: 
1.243     albertel 11355: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11356: reference filled in from namesp (encrypts the return communication)
                   11357: ($udom and $uname are optional)
1.191     harris41 11358: 
                   11359: =item *
                   11360: 
1.243     albertel 11361: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11362: critical subroutine
                   11363: 
1.806     raeburn  11364: =item *
                   11365: 
1.860     raeburn  11366: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11367: array reference filled in from namespace found in domain level on either
                   11368: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11369: 
                   11370: =item *
                   11371: 
1.860     raeburn  11372: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11373: domain level either on specified domain server ($uhome) or primary domain 
                   11374: server ($udom and $uhome are optional)
1.806     raeburn  11375: 
1.943     raeburn  11376: =item * 
                   11377: 
                   11378: get_domain_defaults($target_domain) : returns hash with defaults for
                   11379: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11380: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11381: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11382: Values are retrieved from cache (if current), or from domain's configuration.db
                   11383: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11384: or lonTabs/domain.tab. 
                   11385: 
                   11386: %domdefaults = &get_auth_defaults($target_domain);
                   11387: 
1.243     albertel 11388: =back
                   11389: 
                   11390: =head2 Network Status Functions
                   11391: 
                   11392: =over 4
1.191     harris41 11393: 
                   11394: =item *
                   11395: 
                   11396: dirlist($uri) : return directory list based on URI
                   11397: 
                   11398: =item *
                   11399: 
1.243     albertel 11400: spareserver() : find server with least workload from spare.tab
                   11401: 
1.986     foxr     11402: 
                   11403: =item *
                   11404: 
                   11405: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11406: if there is no corresponding loncapa host.
                   11407: 
1.243     albertel 11408: =back
                   11409: 
1.986     foxr     11410: 
1.243     albertel 11411: =head2 Apache Request
                   11412: 
                   11413: =over 4
1.191     harris41 11414: 
                   11415: =item *
                   11416: 
1.243     albertel 11417: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11418: localhost, posts hash
                   11419: 
                   11420: =back
                   11421: 
                   11422: =head2 Data to String to Data
                   11423: 
                   11424: =over 4
1.191     harris41 11425: 
                   11426: =item *
                   11427: 
1.243     albertel 11428: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11429: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11430: 
                   11431: =item *
                   11432: 
1.243     albertel 11433: hashref2str($hashref) : convert a hashref into a string complete with
                   11434: escaping and '=' and '&' separators, supports elements that are
                   11435: arrayrefs and hashrefs
1.191     harris41 11436: 
                   11437: =item *
                   11438: 
1.243     albertel 11439: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11440: with escaping and '&' separators, supports elements that are arrayrefs
                   11441: and hashrefs
1.191     harris41 11442: 
                   11443: =item *
                   11444: 
1.243     albertel 11445: str2hash($string) : convert string to hash using unescaping and
                   11446: splitting on '=' and '&', supports elements that are arrayrefs and
                   11447: hashrefs
1.191     harris41 11448: 
                   11449: =item *
                   11450: 
1.243     albertel 11451: str2array($string) : convert string to hash using unescaping and
                   11452: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11453: 
                   11454: =back
                   11455: 
                   11456: =head2 Logging Routines
                   11457: 
                   11458: These routines allow one to make log messages in the lonnet.log and
                   11459: lonnet.perm logfiles.
1.191     harris41 11460: 
1.1056.4.31  raeburn  11461: =over 4
                   11462: 
1.191     harris41 11463: =item *
                   11464: 
1.243     albertel 11465: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11466: 
                   11467: =item *
                   11468: 
1.243     albertel 11469: logthis() : append message to the normal lonnet.log file, it gets
                   11470: preiodically rolled over and deleted.
1.191     harris41 11471: 
                   11472: =item *
                   11473: 
1.243     albertel 11474: logperm() : append a permanent message to lonnet.perm.log, this log
                   11475: file never gets deleted by any automated portion of the system, only
                   11476: messages of critical importance should go in here.
                   11477: 
                   11478: =back
                   11479: 
                   11480: =head2 General File Helper Routines
                   11481: 
                   11482: =over 4
1.191     harris41 11483: 
                   11484: =item *
                   11485: 
1.481     raeburn  11486: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11487: (a) files in /uploaded
                   11488:   (i) If a local copy of the file exists - 
                   11489:       compares modification date of local copy with last-modified date for 
                   11490:       definitive version stored on home server for course. If local copy is 
                   11491:       stale, requests a new version from the home server and stores it. 
                   11492:       If the original has been removed from the home server, then local copy 
                   11493:       is unlinked.
                   11494:   (ii) If local copy does not exist -
                   11495:       requests the file from the home server and stores it. 
                   11496:   
                   11497:   If $caller is 'uploadrep':  
                   11498:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11499:     for request for files originally uploaded via DOCS. 
                   11500:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11501:   
                   11502:   Otherwise:
                   11503:      This indicates a call from the content generation phase of the request.
                   11504:      -  returns the entire contents of the file or -1.
                   11505:      
                   11506: (b) files in /res
                   11507:    - returns the entire contents of a file or -1; 
                   11508:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11509: 
1.712     albertel 11510: 
                   11511: =item *
                   11512: 
                   11513: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11514:                   reference
                   11515: 
                   11516: returns either a stat() list of data about the file or an empty list
                   11517: if the file doesn't exist or couldn't find out about it (connection
                   11518: problems or user unknown)
                   11519: 
1.191     harris41 11520: =item *
                   11521: 
1.243     albertel 11522: filelocation($dir,$file) : returns file system location of a file
                   11523: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11524: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11525: and a file of ../bob will become /a/bob)
1.191     harris41 11526: 
                   11527: =item *
                   11528: 
                   11529: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11530: filelocation except for hrefs
                   11531: 
                   11532: =item *
                   11533: 
                   11534: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11535: 
1.243     albertel 11536: =back
                   11537: 
1.608     albertel 11538: =head2 Usererfile file routines (/uploaded*)
                   11539: 
                   11540: =over 4
                   11541: 
                   11542: =item *
                   11543: 
                   11544: userfileupload(): main rotine for putting a file in a user or course's
                   11545:                   filespace, arguments are,
                   11546: 
1.620     albertel 11547:  formname - required - this is the name of the element in $env where the
1.608     albertel 11548:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11549:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11550:            contents of the file is located in $env{'form.'.$formname}
1.1056.4.13  raeburn  11551:  context - if coursedoc, store the file in the course of the active role
                   11552:              of the current user;
                   11553:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11554:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11555:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11556:          if undefined, it will be placed in "unknown"
                   11557: 
                   11558:  (This routine calls clean_filename() to remove any dangerous
                   11559:  characters from the filename, and then calls finuserfileupload() to
                   11560:  complete the transaction)
                   11561: 
                   11562:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11563:  and /adm/notfound.html if unsuccessful
                   11564: 
                   11565: =item *
                   11566: 
                   11567: clean_filename(): routine for cleaing a filename up for storage in
                   11568:                  userfile space, argument is:
                   11569: 
                   11570:  filename - proposed filename
                   11571: 
                   11572: returns: the new clean filename
                   11573: 
                   11574: =item *
                   11575: 
1.1056.4.13  raeburn  11576: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11577: userspace, probably shouldn't be called directly
                   11578: 
                   11579:   docuname: username or courseid of destination for the file
                   11580:   docudom: domain of user/course of destination for the file
                   11581:   formname: same as for userfileupload()
1.1056.4.13  raeburn  11582:   fname: filename (including subdirectories) for the file
                   11583:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11584:   allfiles: reference to hash used to store objects found by parser
                   11585:   codebase: reference to hash used for codebases of java objects found by parser
                   11586:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11587:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11588:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11589:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11590:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11591:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1056.4.16  raeburn  11592:   mimetype: reference to scalar to accommodate mime type determined
                   11593:             from File::MMagic if $parser = parse.
1.608     albertel 11594: 
                   11595:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13  raeburn  11596:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11597:  was 'overwrite').
                   11598: 
1.608     albertel 11599: 
                   11600: =item *
                   11601: 
                   11602: renameuserfile(): renames an existing userfile to a new name
                   11603: 
                   11604:   Args:
                   11605:    docuname: username or courseid of destination for the file
                   11606:    docudom: domain of user/course of destination for the file
                   11607:    old: current file name (including any subdirs under userfiles)
                   11608:    new: desired file name (including any subdirs under userfiles)
                   11609: 
                   11610: =item *
                   11611: 
                   11612: mkdiruserfile(): creates a directory is a userfiles dir
                   11613: 
                   11614:   Args:
                   11615:    docuname: username or courseid of destination for the file
                   11616:    docudom: domain of user/course of destination for the file
                   11617:    dir: dir to create (including any subdirs under userfiles)
                   11618: 
                   11619: =item *
                   11620: 
                   11621: removeuserfile(): removes a file that exists in userfiles
                   11622: 
                   11623:   Args:
                   11624:    docuname: username or courseid of destination for the file
                   11625:    docudom: domain of user/course of destination for the file
                   11626:    fname: filname to delete (including any subdirs under userfiles)
                   11627: 
                   11628: =item *
                   11629: 
                   11630: removeuploadedurl(): convience function for removeuserfile()
                   11631: 
                   11632:   Args:
                   11633:    url:  a full /uploaded/... url to delete
                   11634: 
1.747     albertel 11635: =item * 
                   11636: 
                   11637: get_portfile_permissions():
                   11638:   Args:
                   11639:     domain: domain of user or course contain the portfolio files
                   11640:     user: name of user or num of course contain the portfolio files
                   11641:   Returns:
                   11642:     hashref of a dump of the proper file_permissions.db
                   11643:    
                   11644: 
                   11645: =item * 
                   11646: 
                   11647: get_access_controls():
                   11648: 
                   11649: Args:
                   11650:   current_permissions: the hash ref returned from get_portfile_permissions()
                   11651:   group: (optional) the group you want the files associated with
                   11652:   file: (optional) the file you want access info on
                   11653: 
                   11654: Returns:
1.749     raeburn  11655:     a hash (keys are file names) of hashes containing
                   11656:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   11657:         values are XML containing access control settings (see below) 
1.747     albertel 11658: 
                   11659: Internal notes:
                   11660: 
1.749     raeburn  11661:  access controls are stored in file_permissions.db as key=value pairs.
                   11662:     key -> path to file/file_name\0uniqueID:scope_end_start
                   11663:         where scope -> public,guest,course,group,domains or users.
                   11664:               end -> UNIX time for end of access (0 -> no end date)
                   11665:               start -> UNIX time for start of access
                   11666: 
                   11667:     value -> XML description of access control
                   11668:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   11669:             <start></start>
                   11670:             <end></end>
                   11671: 
                   11672:             <password></password>  for scope type = guest
                   11673: 
                   11674:             <domain></domain>     for scope type = course or group
                   11675:             <number></number>
                   11676:             <roles id="">
                   11677:              <role></role>
                   11678:              <access></access>
                   11679:              <section></section>
                   11680:              <group></group>
                   11681:             </roles>
                   11682: 
                   11683:             <dom></dom>         for scope type = domains
                   11684: 
                   11685:             <users>             for scope type = users
                   11686:              <user>
                   11687:               <uname></uname>
                   11688:               <udom></udom>
                   11689:              </user>
                   11690:             </users>
                   11691:            </scope> 
                   11692:               
                   11693:  Access data is also aggregated for each file in an additional key=value pair:
                   11694:  key -> path to file/file_name\0accesscontrol 
                   11695:  value -> reference to hash
                   11696:           hash contains key = value pairs
                   11697:           where key = uniqueID:scope_end_start
                   11698:                 value = UNIX time record was last updated
                   11699: 
                   11700:           Used to improve speed of look-ups of access controls for each file.  
                   11701:  
                   11702:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   11703: 
                   11704: modify_access_controls():
                   11705: 
                   11706: Modifies access controls for a portfolio file
                   11707: Args
                   11708: 1. file name
                   11709: 2. reference to hash of required changes,
                   11710: 3. domain
                   11711: 4. username
                   11712:   where domain,username are the domain of the portfolio owner 
                   11713:   (either a user or a course) 
                   11714: 
                   11715: Returns:
                   11716: 1. result of additions or updates ('ok' or 'error', with error message). 
                   11717: 2. result of deletions ('ok' or 'error', with error message).
                   11718: 3. reference to hash of any new or updated access controls.
                   11719: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   11720:    key = integer (inbound ID)
                   11721:    value = uniqueID  
1.747     albertel 11722: 
1.608     albertel 11723: =back
                   11724: 
1.243     albertel 11725: =head2 HTTP Helper Routines
                   11726: 
                   11727: =over 4
                   11728: 
1.191     harris41 11729: =item *
                   11730: 
                   11731: escape() : unpack non-word characters into CGI-compatible hex codes
                   11732: 
                   11733: =item *
                   11734: 
                   11735: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   11736: 
1.243     albertel 11737: =back
                   11738: 
                   11739: =head1 PRIVATE SUBROUTINES
                   11740: 
                   11741: =head2 Underlying communication routines (Shouldn't call)
                   11742: 
                   11743: =over 4
                   11744: 
                   11745: =item *
                   11746: 
                   11747: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11748: 
                   11749: =item *
                   11750: 
                   11751: reply() : uses subreply to send a message to remote machine, logs all failures
                   11752: 
                   11753: =item *
                   11754: 
                   11755: critical() : passes a critical message to another server; if cannot
                   11756: get through then place message in connection buffer directory and
                   11757: returns con_delayed, if incapable of saving message, returns
                   11758: con_failed
                   11759: 
                   11760: =item *
                   11761: 
                   11762: reconlonc() : tries to reconnect lonc client processes.
                   11763: 
                   11764: =back
                   11765: 
                   11766: =head2 Resource Access Logging
                   11767: 
                   11768: =over 4
                   11769: 
                   11770: =item *
                   11771: 
                   11772: flushcourselogs() : flush (save) buffer logs and access logs
                   11773: 
                   11774: =item *
                   11775: 
                   11776: courselog($what) : save message for course in hash
                   11777: 
                   11778: =item *
                   11779: 
                   11780: courseacclog($what) : save message for course using &courselog().  Perform
                   11781: special processing for specific resource types (problems, exams, quizzes, etc).
                   11782: 
1.191     harris41 11783: =item *
                   11784: 
                   11785: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11786: as a PerlChildExitHandler
1.243     albertel 11787: 
                   11788: =back
                   11789: 
                   11790: =head2 Other
                   11791: 
                   11792: =over 4
                   11793: 
                   11794: =item *
                   11795: 
                   11796: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11797: 
                   11798: =back
                   11799: 
                   11800: =cut
1.877     foxr     11801: 

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