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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.143! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.142 2021/12/14 20:23:40 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;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134  raeburn   130:         my $ip = &get_requestor_ip();  
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1       albertel  368: # -------------------------------------------------- Non-critical communication
                    369: sub subreply {
                    370:     my ($cmd,$server)=@_;
1.838     albertel  371:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      372:     #
                    373:     #  With loncnew process trimming, there's a timing hole between lonc server
                    374:     #  process exit and the master server picking up the listen on the AF_UNIX
                    375:     #  socket.  In that time interval, a lock file will exist:
                    376: 
                    377:     my $lockfile=$peerfile.".lock";
                    378:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   379: 	sleep(0.1);
1.549     foxr      380:     }
                    381:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      382:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      383:     #
1.550     foxr      384:     #   We'll give the connection a few tries before abandoning it.  If
                    385:     #   connection is not possible, we'll con_lost back to the client.
                    386:     #   
                    387:     my $client;
                    388:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    389: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    390: 				      Type    => SOCK_STREAM,
                    391: 				      Timeout => 10);
1.869     albertel  392: 	if ($client) {
1.550     foxr      393: 	    last;		# Connected!
1.850     albertel  394: 	} else {
1.853     albertel  395: 	    &create_connection(&hostname($server),$server);
1.550     foxr      396: 	}
1.1172.2.79  raeburn   397:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      398:     }
                    399:     my $answer;
                    400:     if ($client) {
1.704     albertel  401: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      402: 	$answer=<$client>;
                    403: 	if (!$answer) { $answer="con_lost"; }
                    404: 	chomp($answer);
                    405:     } else {
                    406: 	$answer = 'con_lost';	# Failed connection.
                    407:     }
1.1       albertel  408:     return $answer;
                    409: }
                    410: 
                    411: sub reply {
                    412:     my ($cmd,$server)=@_;
1.838     albertel  413:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  414:     my $answer=subreply($cmd,$server);
1.65      www       415:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   416:         my $logged = $cmd;
                    417:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    418:             my $subcmd = $1;
                    419:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    420:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    421:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    422:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    423:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    424:                     splice(@rest,2,1,'Hidden');
                    425:                 } elsif ($subcmd eq 'passwd') {
                    426:                     splice(@rest,2,2,('Hidden','Hidden'));
                    427:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    428:                          ($subcmd eq 'autoexportgrades')) {
                    429:                     splice(@rest,3,1,'Hidden');
                    430:                 }
                    431:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    432:             }
                    433:         }
                    434:         &logthis("<font color=\"blue\">WARNING:".
                    435:                  " $logged to $server returned $answer</font>");
1.12      www       436:     }
1.1       albertel  437:     return $answer;
                    438: }
                    439: 
                    440: # ----------------------------------------------------------- Send USR1 to lonc
                    441: 
                    442: sub reconlonc {
1.891     albertel  443:     my ($lonid) = @_;
                    444:     if ($lonid) {
1.1172.2.72  raeburn   445:         my $hostname = &hostname($lonid);
1.891     albertel  446: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    447: 	if ($hostname && -e $peerfile) {
                    448: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    449: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    450: 					     Type    => SOCK_STREAM,
                    451: 					     Timeout => 10);
                    452: 	    if ($client) {
                    453: 		print $client ("reset_retries\n");
                    454: 		my $answer=<$client>;
                    455: 		#reset just this one.
                    456: 	    }
                    457: 	}
                    458: 	return;
                    459:     }
                    460: 
1.836     www       461:     &logthis("Trying to reconnect lonc");
1.1       albertel  462:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   463:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  464: 	my $loncpid=<$fh>;
                    465:         chomp($loncpid);
                    466:         if (kill 0 => $loncpid) {
                    467: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    468:             kill USR1 => $loncpid;
                    469:             sleep 1;
1.836     www       470:          } else {
1.12      www       471: 	    &logthis(
1.672     albertel  472:                "<font color=\"blue\">WARNING:".
1.12      www       473:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  474:         }
                    475:     } else {
1.836     www       476: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  477:     }
                    478: }
                    479: 
                    480: # ------------------------------------------------------ Critical communication
1.12      www       481: 
1.1       albertel  482: sub critical {
                    483:     my ($cmd,$server)=@_;
1.838     albertel  484:     unless (&hostname($server)) {
1.672     albertel  485:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       486:                " Critical message to unknown server ($server)</font>");
                    487:         return 'no_such_host';
                    488:     }
1.1       albertel  489:     my $answer=reply($cmd,$server);
                    490:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   491: 	&reconlonc($server);
1.589     albertel  492: 	my $answer=reply($cmd,$server);
1.1       albertel  493:         if ($answer eq 'con_lost') {
                    494:             my $now=time;
                    495:             my $middlename=$cmd;
1.5       www       496:             $middlename=substr($middlename,0,16);
1.1       albertel  497:             $middlename=~s/\W//g;
                    498:             my $dfilename=
1.305     www       499:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    500:             $dumpcount++;
1.1       albertel  501:             {
1.448     albertel  502: 		my $dfh;
1.1172.2.96  raeburn   503: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  504: 		    print $dfh "$cmd\n"; 
                    505: 		    close($dfh);
                    506: 		}
1.1       albertel  507:             }
1.1172.2.79  raeburn   508:             sleep 1;
1.1       albertel  509:             my $wcmd='';
                    510:             {
1.448     albertel  511: 		my $dfh;
1.1172.2.96  raeburn   512: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  513: 		    $wcmd=<$dfh>; 
                    514: 		    close($dfh);
                    515: 		}
1.1       albertel  516:             }
                    517:             chomp($wcmd);
1.7       www       518:             if ($wcmd eq $cmd) {
1.672     albertel  519: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       520:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  521:                 &logperm("D:$server:$cmd");
                    522: 	        return 'con_delayed';
                    523:             } else {
1.672     albertel  524:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       525:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  526:                 &logperm("F:$server:$cmd");
                    527:                 return 'con_failed';
                    528:             }
                    529:         }
                    530:     }
                    531:     return $answer;
1.405     albertel  532: }
                    533: 
1.755     albertel  534: # ------------------------------------------- check if return value is an error
                    535: 
                    536: sub error {
                    537:     my ($result) = @_;
1.756     albertel  538:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  539: 	if ($2 == 2) { return undef; }
                    540: 	return $1;
                    541:     }
                    542:     return undef;
                    543: }
                    544: 
1.783     albertel  545: sub convert_and_load_session_env {
                    546:     my ($lonidsdir,$handle)=@_;
                    547:     my @profile;
                    548:     {
1.917     albertel  549: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    550: 	if (!$opened) {
1.915     albertel  551: 	    return 0;
                    552: 	}
1.783     albertel  553: 	flock($idf,LOCK_SH);
                    554: 	@profile=<$idf>;
                    555: 	close($idf);
                    556:     }
                    557:     my %temp_env;
                    558:     foreach my $line (@profile) {
1.786     albertel  559: 	if ($line !~ m/=/) {
                    560: 	    return 0;
                    561: 	}
1.783     albertel  562: 	chomp($line);
                    563: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    564: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    565:     }
                    566:     unlink("$lonidsdir/$handle.id");
                    567:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    568: 	    0640)) {
                    569: 	%disk_env = %temp_env;
                    570: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    571: 	untie(%disk_env);
                    572:     }
1.786     albertel  573:     return 1;
1.783     albertel  574: }
                    575: 
1.374     www       576: # ------------------------------------------- Transfer profile into environment
1.780     albertel  577: my $env_loaded;
                    578: sub transfer_profile_to_env {
1.788     albertel  579:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    580:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       581: 
1.720     albertel  582:     if (!defined($lonidsdir)) {
                    583: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    584:     }
                    585:     if (!defined($handle)) {
                    586:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    587:     }
                    588: 
1.786     albertel  589:     my $convert;
                    590:     {
1.917     albertel  591:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    592: 	if (!$opened) {
1.915     albertel  593: 	    return;
                    594: 	}
1.786     albertel  595: 	flock($idf,LOCK_SH);
                    596: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    597: 		&GDBM_READER(),0640)) {
                    598: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    599: 	    untie(%disk_env);
                    600: 	} else {
                    601: 	    $convert = 1;
                    602: 	}
                    603:     }
                    604:     if ($convert) {
                    605: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    606: 	    &logthis("Failed to load session, or convert session.");
                    607: 	}
1.374     www       608:     }
1.783     albertel  609: 
1.786     albertel  610:     my %remove;
1.783     albertel  611:     while ( my $envname = each(%env) ) {
1.433     matthew   612:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    613:             if ($time < time-300) {
1.783     albertel  614:                 $remove{$key}++;
1.433     matthew   615:             }
                    616:         }
                    617:     }
1.783     albertel  618: 
1.619     albertel  619:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  620:     $env_loaded=1;
1.783     albertel  621:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   622:         &delenv($expired_key);
1.374     www       623:     }
1.1       albertel  624: }
                    625: 
1.916     albertel  626: # ---------------------------------------------------- Check for valid session 
                    627: sub check_for_valid_session {
1.1172.2.96  raeburn   628:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  629:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   630:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   631:     if ($name eq 'lonDAV') {
                    632:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    633:     } else {
                    634:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   635:         if ($name eq '') {
                    636:             $name = 'lonID';
                    637:         }
                    638:     }
                    639:     if ($name eq 'lonID') {
                    640:         $secure = 'lonSID';
                    641:         $linkname = 'lonLinkID';
                    642:         $pubname = 'lonPubID';
                    643:         if (exists($cookies{$secure})) {
                    644:             $lonid=$cookies{$secure};
                    645:         } elsif (exists($cookies{$name})) {
                    646:             $lonid=$cookies{$name};
                    647:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    648:             $lonid=$cookies{$linkname};
                    649:         } elsif (exists($cookies{$pubname})) {
                    650:             $lonid=$cookies{$pubname};
                    651:         }
                    652:     } else {
                    653:         $lonid=$cookies{$name};
                    654:     }
                    655:     return undef if (!$lonid);
                    656: 
                    657:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    658:     if (-l "$lonidsdir/$handle.id") {
                    659:         my $link = readlink("$lonidsdir/$handle.id");
                    660:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    661:             $handle = $1;
                    662:         }
1.1155    raeburn   663:     }
1.1172.2.96  raeburn   664:     if (!-e "$lonidsdir/$handle.id") {
                    665:         if ((ref($domref)) && ($name eq 'lonID') &&
                    666:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    667:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    668:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    669:                 $$domref = $possudom;
                    670:             }
                    671:         }
                    672:         return undef;
                    673:     }
1.916     albertel  674: 
1.917     albertel  675:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    676:     return undef if (!$opened);
1.916     albertel  677: 
                    678:     flock($idf,LOCK_SH);
                    679:     my %disk_env;
                    680:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    681: 	    &GDBM_READER(),0640)) {
                    682: 	return undef;	
                    683:     }
                    684: 
                    685:     if (!defined($disk_env{'user.name'})
                    686: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   687:         untie(%disk_env);
1.916     albertel  688: 	return undef;
                    689:     }
1.1172.2.18  raeburn   690: 
1.1172.2.36  raeburn   691:     if (ref($userhashref) eq 'HASH') {
                    692:         $userhashref->{'name'} = $disk_env{'user.name'};
                    693:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   694:         if ($disk_env{'request.role'}) {
                    695:             $userhashref->{'role'} = $disk_env{'request.role'};
                    696:         }
1.1172.2.18  raeburn   697:     }
1.1172.2.107  raeburn   698:     untie(%disk_env);
1.1172.2.18  raeburn   699: 
1.916     albertel  700:     return $handle;
                    701: }
                    702: 
1.830     albertel  703: sub timed_flock {
                    704:     my ($file,$lock_type) = @_;
                    705:     my $failed=0;
                    706:     eval {
                    707: 	local $SIG{__DIE__}='DEFAULT';
                    708: 	local $SIG{ALRM}=sub {
                    709: 	    $failed=1;
                    710: 	    die("failed lock");
                    711: 	};
                    712: 	alarm(13);
                    713: 	flock($file,$lock_type);
                    714: 	alarm(0);
                    715:     };
                    716:     if ($failed) {
                    717: 	return undef;
                    718:     } else {
                    719: 	return 1;
                    720:     }
                    721: }
                    722: 
1.1172.2.107  raeburn   723: sub get_sessionfile_vars {
                    724:     my ($handle,$lonidsdir,$storearr) = @_;
                    725:     my %returnhash;
                    726:     unless (ref($storearr) eq 'ARRAY') {
                    727:         return %returnhash;
                    728:     }
                    729:     if (-l "$lonidsdir/$handle.id") {
                    730:         my $link = readlink("$lonidsdir/$handle.id");
                    731:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    732:             $handle = $1;
                    733:         }
                    734:     }
                    735:     if ((-e "$lonidsdir/$handle.id") &&
                    736:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    737:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    738:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    739:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    740:                 flock($idf,LOCK_SH);
                    741:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    742:                         &GDBM_READER(),0640)) {
                    743:                     foreach my $item (@{$storearr}) {
                    744:                         $returnhash{$item} = $disk_env{$item};
                    745:                     }
                    746:                     untie(%disk_env);
                    747:                 }
                    748:             }
                    749:         }
                    750:     }
                    751:     return %returnhash;
                    752: }
                    753: 
1.5       www       754: # ---------------------------------------------------------- Append Environment
                    755: 
                    756: sub appenv {
1.949     raeburn   757:     my ($newenv,$roles) = @_;
                    758:     if (ref($newenv) eq 'HASH') {
                    759:         foreach my $key (keys(%{$newenv})) {
                    760:             my $refused = 0;
                    761: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    762:                 $refused = 1;
                    763:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   764:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   765:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    766:                         $refused = 0;
                    767:                     }
                    768:                 }
                    769:             }
                    770:             if ($refused) {
                    771:                 &logthis("<font color=\"blue\">WARNING: ".
                    772:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    773:                          .'</font>');
                    774: 	        delete($newenv->{$key});
                    775:             } else {
                    776:                 $env{$key}=$newenv->{$key};
                    777:             }
                    778:         }
1.1172.2.96  raeburn   779:         my $lonids = $perlvar{'lonIDsDir'};
                    780:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    781:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    782:             if ($opened
                    783: 	        && &timed_flock($env_file,LOCK_EX)
                    784: 	        &&
                    785: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    786: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    787: 	        while (my ($key,$value) = each(%{$newenv})) {
                    788: 	            $disk_env{$key} = $value;
                    789: 	        }
                    790: 	        untie(%disk_env);
                    791:             }
1.35      www       792:         }
1.191     harris41  793:     }
1.56      www       794:     return 'ok';
                    795: }
                    796: # ----------------------------------------------------- Delete from Environment
                    797: 
                    798: sub delenv {
1.1104    raeburn   799:     my ($delthis,$regexp,$roles) = @_;
                    800:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    801:         my $refused = 1;
                    802:         if (ref($roles) eq 'ARRAY') {
                    803:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    804:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    805:                 $refused = 0;
                    806:             }
                    807:         }
                    808:         if ($refused) {
                    809:             &logthis("<font color=\"blue\">WARNING: ".
                    810:                      "Attempt to delete from environment ".$delthis);
                    811:             return 'error';
                    812:         }
1.56      www       813:     }
1.917     albertel  814:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    815:     if ($opened
1.915     albertel  816: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  817: 	&&
                    818: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    819: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  820: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   821: 	    if ($regexp) {
                    822:                 if ($key=~/^$delthis/) {
                    823:                     delete($env{$key});
                    824:                     delete($disk_env{$key});
                    825:                 } 
                    826:             } else {
                    827:                 if ($key=~/^\Q$delthis\E/) {
                    828: 		    delete($env{$key});
                    829: 		    delete($disk_env{$key});
                    830: 	        }
                    831:             }
1.448     albertel  832: 	}
1.783     albertel  833: 	untie(%disk_env);
1.5       www       834:     }
                    835:     return 'ok';
1.369     albertel  836: }
                    837: 
1.790     albertel  838: sub get_env_multiple {
                    839:     my ($name) = @_;
                    840:     my @values;
                    841:     if (defined($env{$name})) {
                    842:         # exists is it an array
                    843:         if (ref($env{$name})) {
                    844:             @values=@{ $env{$name} };
                    845:         } else {
                    846:             $values[0]=$env{$name};
                    847:         }
                    848:     }
                    849:     return(@values);
                    850: }
                    851: 
1.958     www       852: # ------------------------------------------------------------------- Locking
                    853: 
                    854: sub set_lock {
                    855:     my ($text)=@_;
                    856:     $locknum++;
                    857:     my $id=$$.'-'.$locknum;
                    858:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    859:              'session.lock.'.$id => $text});
                    860:     return $id;
                    861: }
                    862: 
                    863: sub get_locks {
                    864:     my $num=0;
                    865:     my %texts=();
                    866:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    867:        if ($lock=~/\w/) {
                    868:           $num++;
                    869:           $texts{$lock}=$env{'session.lock.'.$lock};
                    870:        }
                    871:    }
                    872:    return ($num,%texts);
                    873: }
                    874: 
                    875: sub remove_lock {
                    876:     my ($id)=@_;
                    877:     my $newlocks='';
                    878:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    879:        if (($lock=~/\w/) && ($lock ne $id)) {
                    880:           $newlocks.=','.$lock;
                    881:        }
                    882:     }
                    883:     &appenv({'session.locks' => $newlocks});
                    884:     &delenv('session.lock.'.$id);
                    885: }
                    886: 
                    887: sub remove_all_locks {
                    888:     my $activelocks=$env{'session.locks'};
                    889:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    890:        if ($lock=~/\w/) {
                    891:           &remove_lock($lock);
                    892:        }
                    893:     }
                    894: }
                    895: 
                    896: 
1.369     albertel  897: # ------------------------------------------ Find out current server userload
                    898: sub userload {
                    899:     my $numusers=0;
                    900:     {
                    901: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    902: 	my $filename;
                    903: 	my $curtime=time;
                    904: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  905: 	    next if ($filename eq '.' || $filename eq '..');
                    906: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   907:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  908: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  909: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  910: 	}
                    911: 	closedir(LONIDS);
                    912:     }
                    913:     my $userloadpercent=0;
                    914:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    915:     if ($maxuserload) {
1.371     albertel  916: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  917:     }
1.372     albertel  918:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  919:     return $userloadpercent;
1.283     www       920: }
                    921: 
1.1       albertel  922: # ------------------------------ Find server with least workload from spare.tab
1.11      www       923: 
1.1       albertel  924: sub spareserver {
1.1172.2.142  raeburn   925:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  926:     my $spare_server;
1.370     albertel  927:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  928:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    929:                                                      :  $userloadpercent;
1.1083    raeburn   930:     my ($uint_dom,$remotesessions);
                    931:     if (($udom ne '') && (&domain($udom) ne '')) {
                    932:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    933:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    934:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    935:         $remotesessions = $udomdefaults{'remotesessions'};
                    936:     }
1.1123    raeburn   937:     my $spareshash = &this_host_spares($udom);
                    938:     if (ref($spareshash) eq 'HASH') {
                    939:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    940:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   941:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    942:                                              $try_server));
1.1123    raeburn   943: 	        ($spare_server, $lowest_load) =
                    944: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    945:             }
1.1083    raeburn   946:         }
1.784     albertel  947: 
1.1123    raeburn   948:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    949: 
                    950:         if (!$found_server) {
                    951:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    952: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   953:                     next unless (&spare_can_host($udom,$uint_dom,
                    954:                                                  $remotesessions,$try_server));
1.1123    raeburn   955: 	            ($spare_server, $lowest_load) =
                    956: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    957:                 }
                    958: 	    }
                    959:         }
1.784     albertel  960:     }
                    961: 
                    962:     if (!$want_server_name) {
1.1001    raeburn   963:         if (defined($spare_server)) {
                    964:             my $hostname = &hostname($spare_server);
1.1083    raeburn   965:             if (defined($hostname)) {
1.1172.2.120  raeburn   966:                 my $protocol = 'http';
                    967:                 if ($protocol{$spare_server} eq 'https') {
                    968:                     $protocol = $protocol{$spare_server};
                    969:                 }
1.1172.2.142  raeburn   970:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                    971:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn   972: 	        $spare_server = $protocol.'://'.$hostname;
                    973:             }
                    974:         }
1.784     albertel  975:     }
                    976:     return $spare_server;
                    977: }
                    978: 
                    979: sub compare_server_load {
1.1172.2.41  raeburn   980:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    981: 
                    982:     if ($required) {
                    983:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    984:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    985:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    986:         if (($major eq '' && $minor eq '') ||
                    987:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    988:             return ($spare_server,$lowest_load);
                    989:         }
                    990:     }
1.784     albertel  991: 
                    992:     my $loadans     = &reply('load',    $try_server);
                    993:     my $userloadans = &reply('userload',$try_server);
                    994: 
                    995:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   996: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  997:     }
                    998: 
                    999:     my $load;
                   1000:     if ($loadans =~ /\d/) {
                   1001: 	if ($userloadans =~ /\d/) {
                   1002: 	    #both are numbers, pick the bigger one
                   1003: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1004: 		                              : $userloadans;
1.411     albertel 1005: 	} else {
1.784     albertel 1006: 	    $load = $loadans;
1.411     albertel 1007: 	}
1.784     albertel 1008:     } else {
                   1009: 	$load = $userloadans;
                   1010:     }
                   1011: 
                   1012:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1013: 	$spare_server = $try_server;
                   1014: 	$lowest_load  = $load;
1.370     albertel 1015:     }
1.784     albertel 1016:     return ($spare_server,$lowest_load);
1.202     matthew  1017: }
1.914     albertel 1018: 
                   1019: # --------------------------- ask offload servers if user already has a session
                   1020: sub find_existing_session {
                   1021:     my ($udom,$uname) = @_;
1.1123    raeburn  1022:     my $spareshash = &this_host_spares($udom);
                   1023:     if (ref($spareshash) eq 'HASH') {
                   1024:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1025:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1026:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1027:             }
                   1028:         }
                   1029:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1030:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1031:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1032:             }
                   1033:         }
1.914     albertel 1034:     }
                   1035:     return;
                   1036: }
                   1037: 
1.1172.2.107  raeburn  1038: # check if user's browser sent load balancer cookie and server still has session
                   1039: # and is not overloaded.
                   1040: sub check_for_balancer_cookie {
                   1041:     my ($r,$update_mtime) = @_;
                   1042:     my ($otherserver,$cookie);
                   1043:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1044:     if (exists($cookies{'balanceID'})) {
                   1045:         my $balid = $cookies{'balanceID'};
                   1046:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1047:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1048:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1049:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1050:                 my ($possudom,$possuname) = ($1,$2);
                   1051:                 my $has_session = 0;
                   1052:                 if ((&domain($possudom) ne '') &&
                   1053:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1054:                     my $try_server;
                   1055:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1056:                     if ($opened) {
                   1057:                         flock($idf,LOCK_SH);
                   1058:                         while (my $line = <$idf>) {
                   1059:                             chomp($line);
                   1060:                             if (&hostname($line) ne '') {
                   1061:                                 $try_server = $line;
                   1062:                                 last;
                   1063:                             }
                   1064:                         }
                   1065:                         close($idf);
                   1066:                         if (($try_server) &&
                   1067:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1068:                             my $lowest_load = 30000;
                   1069:                             ($otherserver,$lowest_load) =
                   1070:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1071:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1072:                                 $has_session = 1;
                   1073:                             } else {
                   1074:                                 undef($otherserver);
                   1075:                             }
                   1076:                         }
                   1077:                     }
                   1078:                 }
                   1079:                 if ($has_session) {
                   1080:                     if ($update_mtime) {
                   1081:                         my $atime = my $mtime = time;
                   1082:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1083:                     }
                   1084:                 } else {
                   1085:                     unlink("$balancedir/$cookie.id");
                   1086:                 }
                   1087:             }
                   1088:         }
                   1089:     }
                   1090:     return ($otherserver,$cookie);
                   1091: }
                   1092: 
1.1172.2.130  raeburn  1093: sub updatebalcookie {
                   1094:     my ($cookie,$balancer,$lastentry)=@_;
                   1095:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1096:         my ($udom,$uname) = ($1,$2);
                   1097:         my $uprimary_id = &domain($udom,'primary');
                   1098:         my $uintdom = &internet_dom($uprimary_id);
                   1099:         my $intdom = &internet_dom($balancer);
                   1100:         my $serverhomedom = &host_domain($balancer);
                   1101:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1102:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1103:         }
                   1104:     }
                   1105:     return;
                   1106: }
                   1107: 
1.1172.2.107  raeburn  1108: sub delbalcookie {
                   1109:     my ($cookie,$balancer) =@_;
                   1110:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1111:         my ($udom,$uname) = ($1,$2);
                   1112:         my $uprimary_id = &domain($udom,'primary');
                   1113:         my $uintdom = &internet_dom($uprimary_id);
                   1114:         my $intdom = &internet_dom($balancer);
                   1115:         my $serverhomedom = &host_domain($balancer);
                   1116:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1117:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1118:         }
                   1119:     }
                   1120: }
                   1121: 
1.914     albertel 1122: # -------------------------------- ask if server already has a session for user
                   1123: sub has_user_session {
                   1124:     my ($lonid,$udom,$uname) = @_;
                   1125:     my $result = &reply(join(':','userhassession',
                   1126: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1127:     return 1 if ($result eq 'ok');
                   1128: 
                   1129:     return 0;
                   1130: }
                   1131: 
1.1076    raeburn  1132: # --------- determine least loaded server in a user's domain which allows login
                   1133: 
                   1134: sub choose_server {
1.1172.2.47  raeburn  1135:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1136:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1137:     my %servers = &get_servers($udom);
1.1076    raeburn  1138:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1139:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1140:     if ($skiploadbal) {
                   1141:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1142:         unless (defined($cached)) {
                   1143:             my $cachetime = 60*60*24;
                   1144:             my %domconfig =
                   1145:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1146:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1147:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1148:                                            $cachetime);
                   1149:             }
                   1150:         }
                   1151:     }
1.1076    raeburn  1152:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1153:         my $loginvia;
1.1172.2.47  raeburn  1154:         if ($skiploadbal) {
                   1155:             if (ref($balancers) eq 'HASH') {
                   1156:                 next if (exists($balancers->{$lonhost}));
                   1157:             }
                   1158:         }
1.1115    raeburn  1159:         if ($checkloginvia) {
                   1160:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1161:             if ($loginvia) {
                   1162:                 my ($server,$path) = split(/:/,$loginvia);
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $server) {
                   1166:                     $portal_path = $path;
1.1151    raeburn  1167:                     $isredirect = 1;
1.1116    raeburn  1168:                 }
                   1169:             } else {
                   1170:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1171:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1172:                 if ($login_host eq $lonhost) {
                   1173:                     $portal_path = '';
1.1151    raeburn  1174:                     $isredirect = ''; 
1.1116    raeburn  1175:                 }
                   1176:             }
                   1177:         } else {
1.1076    raeburn  1178:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1179:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1180:         }
                   1181:     }
                   1182:     if ($login_host ne '') {
1.1116    raeburn  1183:         $hostname = &hostname($login_host);
1.1076    raeburn  1184:     }
1.1172.2.88  raeburn  1185:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1186: }
                   1187: 
1.1172.2.123  raeburn  1188: sub get_course_sessions {
                   1189:     my ($cnum,$cdom,$lastactivity) = @_;
                   1190:     my %servers = &internet_dom_servers($cdom);
                   1191:     my %returnhash;
                   1192:     foreach my $server (sort(keys(%servers))) {
                   1193:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1194:         my @pairs=split(/\&/,$rep);
                   1195:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1196:             foreach my $item (@pairs) {
                   1197:                 my ($key,$value)=split(/=/,$item,2);
                   1198:                 $key = &unescape($key);
                   1199:                 next if ($key =~ /^error: 2 /);
                   1200:                 if (exists($returnhash{$key})) {
                   1201:                     next if ($value < $returnhash{$key});
                   1202:                 }
                   1203:                 $returnhash{$key}=$value;
                   1204:             }
                   1205:         }
                   1206:     }
                   1207:     return %returnhash;
                   1208: }
                   1209: 
1.202     matthew  1210: # --------------------------------------------- Try to change a user's password
                   1211: 
                   1212: sub changepass {
1.799     raeburn  1213:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1214:     $currentpass = &escape($currentpass);
                   1215:     $newpass     = &escape($newpass);
1.1030    raeburn  1216:     my $lonhost = $perlvar{'lonHostID'};
                   1217:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1218: 		       $server);
                   1219:     if (! $answer) {
                   1220: 	&logthis("No reply on password change request to $server ".
                   1221: 		 "by $uname in domain $udom.");
                   1222:     } elsif ($answer =~ "^ok") {
                   1223:         &logthis("$uname in $udom successfully changed their password ".
                   1224: 		 "on $server.");
                   1225:     } elsif ($answer =~ "^pwchange_failure") {
                   1226: 	&logthis("$uname in $udom was unable to change their password ".
                   1227: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1228: 		 "or pwchange");
                   1229:     } elsif ($answer =~ "^non_authorized") {
                   1230:         &logthis("$uname in $udom did not get their password correct when ".
                   1231: 		 "attempting to change it on $server.");
                   1232:     } elsif ($answer =~ "^auth_mode_error") {
                   1233:         &logthis("$uname in $udom attempted to change their password despite ".
                   1234: 		 "not being locally or internally authenticated on $server.");
                   1235:     } elsif ($answer =~ "^unknown_user") {
                   1236:         &logthis("$uname in $udom attempted to change their password ".
                   1237: 		 "on $server but were unable to because $server is not ".
                   1238: 		 "their home server.");
                   1239:     } elsif ($answer =~ "^refused") {
                   1240: 	&logthis("$server refused to change $uname in $udom password because ".
                   1241: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1242:     } elsif ($answer =~ "invalid_client") {
                   1243:         &logthis("$server refused to change $uname in $udom password because ".
                   1244:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1245:     } elsif ($answer =~ "^prioruse") {
                   1246:        &logthis("$server refused to change $uname in $udom password because ".
                   1247:                 "the password had been used before");
1.202     matthew  1248:     }
                   1249:     return $answer;
1.1       albertel 1250: }
                   1251: 
1.169     harris41 1252: # ----------------------- Try to determine user's current authentication scheme
                   1253: 
                   1254: sub queryauthenticate {
                   1255:     my ($uname,$udom)=@_;
1.456     albertel 1256:     my $uhome=&homeserver($uname,$udom);
                   1257:     if (!$uhome) {
                   1258: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1259: 	return 'no_host';
                   1260:     }
                   1261:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1262:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1263: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1264:     }
1.456     albertel 1265:     return $answer;
1.169     harris41 1266: }
                   1267: 
1.1       albertel 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1269: 
1.1       albertel 1270: sub authenticate {
1.1073    raeburn  1271:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1272:     $upass=&escape($upass);
                   1273:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1274:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1275:     my $newhome;
1.836     www      1276:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1277: # Maybe the machine was offline and only re-appeared again recently?
                   1278:         &reconlonc();
                   1279: # One more
1.952     raeburn  1280: 	$uhome=&homeserver($uname,$udom,1);
                   1281:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1282:             if (defined(&domain($udom,'primary'))) {
                   1283:                 $newhome=&domain($udom,'primary');
                   1284:             }
                   1285:             if ($newhome ne '') {
                   1286:                 $uhome = $newhome;
                   1287:             }
                   1288:         }
1.836     www      1289: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1290: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1291: 	    return 'no_host';
                   1292:         }
1.1       albertel 1293:     }
1.1073    raeburn  1294:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1295:     if ($answer eq 'authorized') {
1.952     raeburn  1296:         if ($newhome) {
                   1297:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1298:             return 'no_account_on_host'; 
                   1299:         } else {
                   1300:             &logthis("User $uname at $udom authorized by $uhome");
                   1301:             return $uhome;
                   1302:         }
1.471     albertel 1303:     }
                   1304:     if ($answer eq 'non_authorized') {
                   1305: 	&logthis("User $uname at $udom rejected by $uhome");
                   1306: 	return 'no_host'; 
1.9       www      1307:     }
1.471     albertel 1308:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1309:     return 'no_host';
                   1310: }
                   1311: 
1.1073    raeburn  1312: sub can_host_session {
1.1074    raeburn  1313:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1314:     my $canhost = 1;
1.1074    raeburn  1315:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1316:     if (ref($remotesessions) eq 'HASH') {
                   1317:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 0;
                   1320:             } else {
                   1321:                 $canhost = 1;
                   1322:             }
                   1323:         }
                   1324:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1325:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1326:                 $canhost = 1;
                   1327:             } else {
                   1328:                 $canhost = 0;
                   1329:             }
                   1330:         }
                   1331:         if ($canhost) {
                   1332:             if ($remotesessions->{'version'} ne '') {
                   1333:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1334:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1335:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1336:                         my $major = $1;
                   1337:                         my $minor = $2;
                   1338:                         if (($major < $reqmajor ) ||
                   1339:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1340:                             $canhost = 0;
                   1341:                         }
                   1342:                     } else {
                   1343:                         $canhost = 0;
                   1344:                     }
                   1345:                 }
                   1346:             }
                   1347:         }
                   1348:     }
                   1349:     if ($canhost) {
                   1350:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1351:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1352:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1353:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1354:                 if (($uint_dom ne '') && 
                   1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1356:                     $canhost = 0;
                   1357:                 } else {
                   1358:                     $canhost = 1;
                   1359:                 }
                   1360:             }
                   1361:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1362:                 if (($uint_dom ne '') && 
                   1363:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1364:                     $canhost = 1;
                   1365:                 } else {
                   1366:                     $canhost = 0;
                   1367:                 }
                   1368:             }
                   1369:         }
                   1370:     }
                   1371:     return $canhost;
                   1372: }
                   1373: 
1.1083    raeburn  1374: sub spare_can_host {
                   1375:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1376:     my $canhost=1;
1.1172.2.62  raeburn  1377:     my $try_server_hostname = &hostname($try_server);
                   1378:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1379:     my $serverhomedom = &host_domain($serverhomeID);
                   1380:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1381:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1382:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1383:             $canhost = 0;
                   1384:         }
                   1385:     }
1.1172.2.136  raeburn  1386:     if ($canhost) {
                   1387:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1388:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1389:                 unless (&shared_institution($udom,$try_server)) {
                   1390:                     $canhost = 0;
                   1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
1.1172.2.62  raeburn  1395:     if (($canhost) && ($uint_dom)) {
                   1396:         my @intdoms;
                   1397:         my $internet_names = &get_internet_names($try_server);
                   1398:         if (ref($internet_names) eq 'ARRAY') {
                   1399:             @intdoms = @{$internet_names};
                   1400:         }
                   1401:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1402:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1403:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1404:                                          $remotesessions,
                   1405:                                          $defdomdefaults{'hostedsessions'});
                   1406:         }
1.1083    raeburn  1407:     }
                   1408:     return $canhost;
                   1409: }
                   1410: 
1.1123    raeburn  1411: sub this_host_spares {
                   1412:     my ($dom) = @_;
1.1126    raeburn  1413:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1414:     my @hosts = &current_machine_ids();
                   1415:     foreach my $lonhost (@hosts) {
                   1416:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1417:             $dom_in_use = $dom;
                   1418:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1419:             last;
                   1420:         }
                   1421:     }
1.1126    raeburn  1422:     if ($dom_in_use ne '') {
                   1423:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1424:     }
                   1425:     if (ref($result) ne 'HASH') {
                   1426:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1427:         $dom_in_use = &host_domain($lonhost_in_use);
                   1428:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1429:         if (ref($result) ne 'HASH') {
                   1430:             $result = \%spareid;
                   1431:         }
                   1432:     }
                   1433:     return $result;
                   1434: }
                   1435: 
                   1436: sub spares_for_offload  {
                   1437:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1438:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1439:     if (defined($cached)) {
                   1440:         return $result;
                   1441:     } else {
1.1126    raeburn  1442:         my $cachetime = 60*60*24;
                   1443:         my %domconfig =
                   1444:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1445:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1446:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1447:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1448:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1449:                 }
                   1450:             }
                   1451:         }
                   1452:     }
1.1126    raeburn  1453:     return;
1.1123    raeburn  1454: }
                   1455: 
1.1129    raeburn  1456: sub get_lonbalancer_config {
                   1457:     my ($servers) = @_;
                   1458:     my ($currbalancer,$currtargets);
                   1459:     if (ref($servers) eq 'HASH') {
                   1460:         foreach my $server (keys(%{$servers})) {
                   1461:             my %what = (
                   1462:                          spareid => 1,
                   1463:                          perlvar => 1,
                   1464:                        );
                   1465:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1466:             if ($result eq 'ok') {
                   1467:                 if (ref($returnhash) eq 'HASH') {
                   1468:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1469:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1470:                             $currbalancer = $server;
                   1471:                             $currtargets = {};
                   1472:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1473:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1474:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1475:                                 }
                   1476:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1477:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1478:                                 }
                   1479:                             }
                   1480:                             last;
                   1481:                         }
                   1482:                     }
                   1483:                 }
                   1484:             }
                   1485:         }
                   1486:     }
                   1487:     return ($currbalancer,$currtargets);
                   1488: }
                   1489: 
                   1490: sub check_loadbalancing {
1.1172.2.88  raeburn  1491:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1492:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1493:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1494:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1495:     my @hosts = &current_machine_ids();
1.1129    raeburn  1496:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1497:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1498:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1499:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1500:     my $domneedscache; 
1.1129    raeburn  1501:     my $cachetime = 60*60*24;
                   1502: 
                   1503:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1504:         $dom_in_use = $udom;
                   1505:         $homeintdom = 1;
                   1506:     } else {
                   1507:         $dom_in_use = $serverhomedom;
                   1508:     }
                   1509:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1510:     unless (defined($cached)) {
                   1511:         my %domconfig =
                   1512:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1513:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1514:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1515:         } else {
                   1516:             $domneedscache = $dom_in_use;
1.1129    raeburn  1517:         }
                   1518:     }
                   1519:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1520:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1521:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1522:         if ($is_balancer) {
                   1523:             if (ref($currrules) eq 'HASH') {
                   1524:                 if ($homeintdom) {
                   1525:                     if ($uname ne '') {
                   1526:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1527:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1528:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1529:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1530:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1531:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1532:                             }
                   1533:                         }
                   1534:                         if ($rule_in_effect eq '') {
                   1535:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1536:                             if ($userenv{'inststatus'} ne '') {
                   1537:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1538:                                 my ($othertitle,$usertypes,$types) =
                   1539:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1540:                                 if (ref($types) eq 'ARRAY') {
                   1541:                                     foreach my $type (@{$types}) {
                   1542:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1543:                                             if (exists($currrules->{$type})) {
                   1544:                                                 $rule_in_effect = $currrules->{$type};
                   1545:                                             }
                   1546:                                         }
                   1547:                                     }
                   1548:                                 }
                   1549:                             } else {
                   1550:                                 if (exists($currrules->{'default'})) {
                   1551:                                     $rule_in_effect = $currrules->{'default'};
                   1552:                                 }
                   1553:                             }
                   1554:                         }
                   1555:                     } else {
                   1556:                         if (exists($currrules->{'default'})) {
                   1557:                             $rule_in_effect = $currrules->{'default'};
                   1558:                         }
                   1559:                     }
                   1560:                 } else {
                   1561:                     if ($currrules->{'_LC_external'} ne '') {
                   1562:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1563:                     }
                   1564:                 }
                   1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1566:                                                        $uname,$udom);
                   1567:             }
                   1568:         }
                   1569:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1570:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1571:         unless (defined($cached)) {
                   1572:             my %domconfig =
                   1573:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1574:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1575:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1576:             } else {
                   1577:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1578:             }
                   1579:         }
                   1580:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1581:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1582:                 &check_balancer_result($result,@hosts);
                   1583:             if ($is_balancer) {
1.1129    raeburn  1584:                 if (ref($currrules) eq 'HASH') {
                   1585:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1586:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1587:                     }
                   1588:                 }
                   1589:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1590:                                                        $uname,$udom);
                   1591:             }
                   1592:         } else {
                   1593:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1594:                 $is_balancer = 1;
                   1595:                 $offloadto = &this_host_spares($dom_in_use);
                   1596:             }
1.1172.2.75  raeburn  1597:             unless (defined($cached)) {
                   1598:                 $domneedscache = $serverhomedom;
                   1599:             }
1.1129    raeburn  1600:         }
                   1601:     } else {
                   1602:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1603:             $is_balancer = 1;
                   1604:             $offloadto = &this_host_spares($dom_in_use);
                   1605:         }
1.1172.2.75  raeburn  1606:         unless (defined($cached)) {
                   1607:             $domneedscache = $serverhomedom;
                   1608:         }
                   1609:     }
                   1610:     if ($domneedscache) {
                   1611:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1612:     }
1.1172.2.130  raeburn  1613:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1614:         my $lowest_load = 30000;
                   1615:         if (ref($offloadto) eq 'HASH') {
                   1616:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1617:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1618:                     ($otherserver,$lowest_load) =
                   1619:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1620:                 }
1.1129    raeburn  1621:             }
1.1172.2.5  raeburn  1622:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1623: 
1.1172.2.5  raeburn  1624:             if (!$found_server) {
                   1625:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1626:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1627:                         ($otherserver,$lowest_load) =
                   1628:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1629:                     }
                   1630:                 }
                   1631:             }
                   1632:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1633:             if (@{$offloadto} == 1) {
                   1634:                 $otherserver = $offloadto->[0];
                   1635:             } elsif (@{$offloadto} > 1) {
                   1636:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1637:                     ($otherserver,$lowest_load) =
                   1638:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1639:                 }
                   1640:             }
                   1641:         }
1.1172.2.88  raeburn  1642:         unless ($caller eq 'login') {
                   1643:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1644:                 $is_balancer = 0;
                   1645:                 if ($uname ne '' && $udom ne '') {
                   1646:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1647:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1648:                                  'user.loadbalcheck.time' => time});
                   1649:                     }
1.1172.2.5  raeburn  1650:                 }
1.1129    raeburn  1651:             }
                   1652:         }
1.1172.2.130  raeburn  1653:     }
                   1654:     if (($is_balancer) && (!$homeintdom)) {
                   1655:         undef($setcookie);
1.1129    raeburn  1656:     }
1.1172.2.107  raeburn  1657:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1658: }
                   1659: 
1.1172.2.12  raeburn  1660: sub check_balancer_result {
                   1661:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1662:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1663:     if (ref($result) eq 'HASH') {
                   1664:         if ($result->{'lonhost'} ne '') {
                   1665:             my $currbalancer = $result->{'lonhost'};
                   1666:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1667:                 $is_balancer = 1;
                   1668:                 $currtargets = $result->{'targets'};
                   1669:                 $currrules = $result->{'rules'};
                   1670:             }
                   1671:         } else {
                   1672:             foreach my $key (keys(%{$result})) {
                   1673:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1674:                     (ref($result->{$key}) eq 'HASH')) {
                   1675:                     $is_balancer = 1;
                   1676:                     $currrules = $result->{$key}{'rules'};
                   1677:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1678:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1679:                     last;
                   1680:                 }
                   1681:             }
                   1682:         }
                   1683:     }
1.1172.2.107  raeburn  1684:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1685: }
                   1686: 
1.1129    raeburn  1687: sub get_loadbalancer_targets {
                   1688:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1689:     my $offloadto;
1.1172.2.4  raeburn  1690:     if ($rule_in_effect eq 'none') {
                   1691:         return [$perlvar{'lonHostID'}];
                   1692:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1693:         $offloadto = $currtargets;
                   1694:     } else {
                   1695:         if ($rule_in_effect eq 'homeserver') {
                   1696:             my $homeserver = &homeserver($uname,$udom);
                   1697:             if ($homeserver ne 'no_host') {
                   1698:                 $offloadto = [$homeserver];
                   1699:             }
                   1700:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1701:             my %domconfig =
                   1702:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1703:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1704:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1705:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1706:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1707:                     }
                   1708:                 }
                   1709:             } else {
1.1172.2.7  raeburn  1710:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1711:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1712:                 if (&hostname($remotebalancer) ne '') {
                   1713:                     $offloadto = [$remotebalancer];
                   1714:                 }
                   1715:             }
                   1716:         } elsif (&hostname($rule_in_effect) ne '') {
                   1717:             $offloadto = [$rule_in_effect];
                   1718:         }
                   1719:     }
                   1720:     return $offloadto;
                   1721: }
                   1722: 
1.1127    raeburn  1723: sub internet_dom_servers {
                   1724:     my ($dom) = @_;
                   1725:     my (%uniqservers,%servers);
                   1726:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1727:     my @machinedoms = &machine_domains($primaryserver);
                   1728:     foreach my $mdom (@machinedoms) {
                   1729:         my %currservers = %servers;
                   1730:         my %server = &get_servers($mdom);
                   1731:         %servers = (%currservers,%server);
                   1732:     }
                   1733:     my %by_hostname;
                   1734:     foreach my $id (keys(%servers)) {
                   1735:         push(@{$by_hostname{$servers{$id}}},$id);
                   1736:     }
                   1737:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1738:         if (@{$by_hostname{$hostname}} > 1) {
                   1739:             my $match = 0;
                   1740:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1741:                 if (&host_domain($id) eq $dom) {
                   1742:                     $uniqservers{$id} = $hostname;
                   1743:                     $match = 1;
                   1744:                 }
                   1745:             }
                   1746:             unless ($match) {
                   1747:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1748:             }
                   1749:         } else {
                   1750:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1751:         }
                   1752:     }
                   1753:     return %uniqservers;
                   1754: }
                   1755: 
1.1       albertel 1756: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1757: 
1.599     albertel 1758: my %homecache;
1.1       albertel 1759: sub homeserver {
1.230     stredwic 1760:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1761:     my $index="$uname:$udom";
1.426     albertel 1762: 
1.599     albertel 1763:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1764: 
                   1765:     my %servers = &get_servers($udom,'library');
                   1766:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1767:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1768: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1769: 
                   1770: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1771: 	if ($answer eq 'found') {
                   1772: 	    delete($badServerCache{$tryserver}); 
                   1773: 	    return $homecache{$index}=$tryserver;
                   1774: 	} elsif ($answer eq 'no_host') {
                   1775: 	    $badServerCache{$tryserver}=1;
                   1776: 	}
1.1       albertel 1777:     }    
                   1778:     return 'no_host';
1.70      www      1779: }
                   1780: 
                   1781: # ------------------------------------- Find the usernames behind a list of IDs
                   1782: 
                   1783: sub idget {
                   1784:     my ($udom,@ids)=@_;
                   1785:     my %returnhash=();
                   1786:     
1.841     albertel 1787:     my %servers = &get_servers($udom,'library');
                   1788:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1789: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1790: 	$idlist=~tr/A-Z/a-z/; 
                   1791: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1792: 	my @answer=();
                   1793: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1794: 	    @answer=split(/\&/,$reply);
                   1795: 	}                    ;
                   1796: 	my $i;
                   1797: 	for ($i=0;$i<=$#ids;$i++) {
                   1798: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1799: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1800: 	    } 
                   1801: 	}
                   1802:     } 
1.70      www      1803:     return %returnhash;
                   1804: }
                   1805: 
                   1806: # ------------------------------------- Find the IDs behind a list of usernames
                   1807: 
                   1808: sub idrget {
                   1809:     my ($udom,@unames)=@_;
                   1810:     my %returnhash=();
1.800     albertel 1811:     foreach my $uname (@unames) {
                   1812:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1813:     }
1.70      www      1814:     return %returnhash;
                   1815: }
                   1816: 
                   1817: # ------------------------------- Store away a list of names and associated IDs
                   1818: 
                   1819: sub idput {
                   1820:     my ($udom,%ids)=@_;
                   1821:     my %servers=();
1.800     albertel 1822:     foreach my $uname (keys(%ids)) {
                   1823: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1824:         my $uhom=&homeserver($uname,$udom);
1.70      www      1825:         if ($uhom ne 'no_host') {
1.800     albertel 1826:             my $id=&escape($ids{$uname});
1.70      www      1827:             $id=~tr/A-Z/a-z/;
1.800     albertel 1828:             my $esc_unam=&escape($uname);
1.70      www      1829: 	    if ($servers{$uhom}) {
1.800     albertel 1830: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1831:             } else {
1.800     albertel 1832:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1833:             }
                   1834:         }
1.191     harris41 1835:     }
1.800     albertel 1836:     foreach my $server (keys(%servers)) {
                   1837:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1838:     }
1.344     www      1839: }
                   1840: 
1.1172.2.30  raeburn  1841: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1842: 
                   1843: sub iddel {
                   1844:     my ($udom,$idshashref,$uhome)=@_;
                   1845:     my %result=();
                   1846:     unless (ref($idshashref) eq 'HASH') {
                   1847:         return %result;
                   1848:     }
                   1849:     my %servers=();
                   1850:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1851:         my $uhom;
                   1852:         if ($uhome) {
                   1853:             $uhom = $uhome;
                   1854:         } else {
                   1855:             $uhom=&homeserver($uname,$udom);
                   1856:         }
                   1857:         if ($uhom ne 'no_host') {
                   1858:             if ($servers{$uhom}) {
                   1859:                 $servers{$uhom}.='&'.&escape($id);
                   1860:             } else {
                   1861:                 $servers{$uhom}=&escape($id);
                   1862:             }
                   1863:         }
                   1864:     }
                   1865:     foreach my $server (keys(%servers)) {
                   1866:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1867:     }
                   1868:     return %result;
                   1869: }
                   1870: 
1.1023    raeburn  1871: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1872: sub dump_dom {
1.1165    droeschl 1873:     my ($namespace, $udom, $regexp) = @_;
                   1874: 
                   1875:     $udom ||= $env{'user.domain'};
                   1876: 
                   1877:     return () unless $udom;
                   1878: 
                   1879:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1880: }
                   1881: 
1.1023    raeburn  1882: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1883: 
                   1884: sub get_dom {
1.860     raeburn  1885:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1886:     return if ($udom eq 'public');
1.806     raeburn  1887:     my $items='';
                   1888:     foreach my $item (@$storearr) {
                   1889:         $items.=&escape($item).'&';
                   1890:     }
                   1891:     $items=~s/\&$//;
1.860     raeburn  1892:     if (!$udom) {
                   1893:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1894:         return if ($udom eq 'public');
1.860     raeburn  1895:         if (defined(&domain($udom,'primary'))) {
                   1896:             $uhome=&domain($udom,'primary');
                   1897:         } else {
1.874     albertel 1898:             undef($uhome);
1.860     raeburn  1899:         }
                   1900:     } else {
                   1901:         if (!$uhome) {
                   1902:             if (defined(&domain($udom,'primary'))) {
                   1903:                 $uhome=&domain($udom,'primary');
                   1904:             }
                   1905:         }
                   1906:     }
                   1907:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  1908:         my $rep;
                   1909:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1910:             # domain information is hosted on this machine
                   1911:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
                   1912:         } else {        
                   1913:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1914:         }
1.866     raeburn  1915:         my %returnhash;
1.875     albertel 1916:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1917:             return %returnhash;
                   1918:         }
1.806     raeburn  1919:         my @pairs=split(/\&/,$rep);
                   1920:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1921:             return @pairs;
                   1922:         }
                   1923:         my $i=0;
                   1924:         foreach my $item (@$storearr) {
                   1925:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1926:             $i++;
                   1927:         }
                   1928:         return %returnhash;
                   1929:     } else {
1.880     banghart 1930:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1931:     }
                   1932: }
                   1933: 
                   1934: # -------------------------------------------- put items in domain db files 
                   1935: 
                   1936: sub put_dom {
1.860     raeburn  1937:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1938:     if (!$udom) {
                   1939:         $udom=$env{'user.domain'};
                   1940:         if (defined(&domain($udom,'primary'))) {
                   1941:             $uhome=&domain($udom,'primary');
                   1942:         } else {
1.874     albertel 1943:             undef($uhome);
1.860     raeburn  1944:         }
                   1945:     } else {
                   1946:         if (!$uhome) {
                   1947:             if (defined(&domain($udom,'primary'))) {
                   1948:                 $uhome=&domain($udom,'primary');
                   1949:             }
                   1950:         }
                   1951:     } 
                   1952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1953:         my $items='';
                   1954:         foreach my $item (keys(%$storehash)) {
                   1955:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1956:         }
                   1957:         $items=~s/\&$//;
                   1958:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1959:     } else {
1.860     raeburn  1960:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1961:     }
                   1962: }
                   1963: 
1.1023    raeburn  1964: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1965: sub newput_dom {
1.1023    raeburn  1966:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1967:     my $result;
                   1968:     if (!$udom) {
                   1969:         $udom=$env{'user.domain'};
                   1970:     }
1.1023    raeburn  1971:     if ($udom) {
                   1972:         my $uname = &get_domainconfiguser($udom);
                   1973:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1974:     }
                   1975:     return $result;
                   1976: }
                   1977: 
1.1023    raeburn  1978: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1979: sub del_dom {
1.1023    raeburn  1980:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1981:     if (ref($storearr) eq 'ARRAY') {
                   1982:         if (!$udom) {
                   1983:             $udom=$env{'user.domain'};
                   1984:         }
1.1023    raeburn  1985:         if ($udom) {
                   1986:             my $uname = &get_domainconfiguser($udom); 
                   1987:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1988:         }
                   1989:     }
                   1990: }
                   1991: 
1.1023    raeburn  1992: # ----------------------------------construct domainconfig user for a domain 
                   1993: sub get_domainconfiguser {
                   1994:     my ($udom) = @_;
                   1995:     return $udom.'-domainconfig';
                   1996: }
                   1997: 
1.837     raeburn  1998: sub retrieve_inst_usertypes {
                   1999:     my ($udom) = @_;
                   2000:     my (%returnhash,@order);
1.989     raeburn  2001:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2002:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2003:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2004:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2005:     } else {
                   2006:         if (defined(&domain($udom,'primary'))) {
                   2007:             my $uhome=&domain($udom,'primary');
                   2008:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2009:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2010:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2011:                 return (\%returnhash,\@order);
                   2012:             }
                   2013:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2014:             my @pairs=split(/\&/,$hashitems);
                   2015:             foreach my $item (@pairs) {
                   2016:                 my ($key,$value)=split(/=/,$item,2);
                   2017:                 $key = &unescape($key);
                   2018:                 next if ($key =~ /^error: 2 /);
                   2019:                 $returnhash{$key}=&thaw_unescape($value);
                   2020:             }
                   2021:             my @esc_order = split(/\&/,$orderitems);
                   2022:             foreach my $item (@esc_order) {
                   2023:                 push(@order,&unescape($item));
                   2024:             }
                   2025:         } else {
1.1172.2.44  raeburn  2026:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2027:         }
1.1172.2.44  raeburn  2028:         return (\%returnhash,\@order);
1.837     raeburn  2029:     }
                   2030: }
                   2031: 
1.868     raeburn  2032: sub is_domainimage {
                   2033:     my ($url) = @_;
1.1172.2.142  raeburn  2034:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2035:         if (&domain($1) ne '') {
                   2036:             return '1';
                   2037:         }
                   2038:     }
                   2039:     return;
                   2040: }
                   2041: 
1.899     raeburn  2042: sub inst_directory_query {
                   2043:     my ($srch) = @_;
                   2044:     my $udom = $srch->{'srchdomain'};
                   2045:     my %results;
                   2046:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2047:     my $outcome;
1.899     raeburn  2048:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2049:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2050:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2051:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2052:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2053:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2054:                     (($major == 2) && ($minor < 11)) ||
                   2055:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2056:                     return;
                   2057:                 }
                   2058:             }
                   2059:         }
1.904     albertel 2060: 	my $queryid=&reply("querysend:instdirsearch:".
                   2061: 			   &escape($srch->{'srchby'}).':'.
                   2062: 			   &escape($srch->{'srchterm'}).':'.
                   2063: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2064: 	my $host=&hostname($homeserver);
                   2065: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2066: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2067: 	    return;
                   2068: 	}
                   2069: 	my $response = &get_query_reply($queryid);
                   2070: 	my $maxtries = 5;
                   2071: 	my $tries = 1;
                   2072: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2073: 	    $response = &get_query_reply($queryid);
                   2074: 	    $tries ++;
                   2075: 	}
                   2076: 
                   2077:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2078:             if ($response eq 'unavailable') {
                   2079:                 $outcome = $response;
                   2080:             } else {
                   2081:                 $outcome = 'ok';
                   2082:                 my @matches = split(/\n/,$response);
                   2083:                 foreach my $match (@matches) {
                   2084:                     my ($key,$value) = split(/=/,$match);
                   2085:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2086:                 }
1.899     raeburn  2087:             }
                   2088:         }
                   2089:     }
1.909     raeburn  2090:     return ($outcome,%results);
1.899     raeburn  2091: }
                   2092: 
                   2093: sub usersearch {
                   2094:     my ($srch) = @_;
                   2095:     my $dom = $srch->{'srchdomain'};
                   2096:     my %results;
                   2097:     my %libserv = &all_library();
                   2098:     my $query = 'usersearch';
                   2099:     foreach my $tryserver (keys(%libserv)) {
                   2100:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2101:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2102:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2103:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2104:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2105:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2106:                              (($major == 2) && ($minor < 11)) ||
                   2107:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2108:                 }
                   2109:             }
1.899     raeburn  2110:             my $host=&hostname($tryserver);
                   2111:             my $queryid=
1.911     raeburn  2112:                 &reply("querysend:".&escape($query).':'.
                   2113:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2114:                        &escape($srch->{'srchtype'}).':'.
                   2115:                        &escape($srch->{'srchterm'}),$tryserver);
                   2116:             if ($queryid !~/^\Q$host\E\_/) {
                   2117:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2118:                 next;
1.899     raeburn  2119:             }
                   2120:             my $reply = &get_query_reply($queryid);
                   2121:             my $maxtries = 1;
                   2122:             my $tries = 1;
                   2123:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2124:                 $reply = &get_query_reply($queryid);
                   2125:                 $tries ++;
                   2126:             }
                   2127:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2128:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2129:             } else {
1.911     raeburn  2130:                 my @matches;
                   2131:                 if ($reply =~ /\n/) {
                   2132:                     @matches = split(/\n/,$reply);
                   2133:                 } else {
                   2134:                     @matches = split(/\&/,$reply);
                   2135:                 }
1.899     raeburn  2136:                 foreach my $match (@matches) {
                   2137:                     my ($uname,$udom,%userhash);
1.911     raeburn  2138:                     foreach my $entry (split(/:/,$match)) {
                   2139:                         my ($key,$value) =
                   2140:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2141:                         $userhash{$key} = $value;
                   2142:                         if ($key eq 'username') {
                   2143:                             $uname = $value;
                   2144:                         } elsif ($key eq 'domain') {
                   2145:                             $udom = $value;
1.911     raeburn  2146:                         }
1.899     raeburn  2147:                     }
                   2148:                     $results{$uname.':'.$udom} = \%userhash;
                   2149:                 }
                   2150:             }
                   2151:         }
                   2152:     }
                   2153:     return %results;
                   2154: }
                   2155: 
1.912     raeburn  2156: sub get_instuser {
                   2157:     my ($udom,$uname,$id) = @_;
                   2158:     my $homeserver = &domain($udom,'primary');
                   2159:     my ($outcome,%results);
                   2160:     if ($homeserver ne '') {
                   2161:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2162:                            &escape($id).':'.&escape($udom),$homeserver);
                   2163:         my $host=&hostname($homeserver);
                   2164:         if ($queryid !~/^\Q$host\E\_/) {
                   2165:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2166:             return;
                   2167:         }
                   2168:         my $response = &get_query_reply($queryid);
                   2169:         my $maxtries = 5;
                   2170:         my $tries = 1;
                   2171:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2172:             $response = &get_query_reply($queryid);
                   2173:             $tries ++;
                   2174:         }
                   2175:         if (!&error($response) && $response ne 'refused') {
                   2176:             if ($response eq 'unavailable') {
                   2177:                 $outcome = $response;
                   2178:             } else {
                   2179:                 $outcome = 'ok';
                   2180:                 my @matches = split(/\n/,$response);
                   2181:                 foreach my $match (@matches) {
                   2182:                     my ($key,$value) = split(/=/,$match);
                   2183:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2184:                 }
                   2185:             }
                   2186:         }
                   2187:     }
                   2188:     my %userinfo;
                   2189:     if (ref($results{$uname}) eq 'HASH') {
                   2190:         %userinfo = %{$results{$uname}};
                   2191:     } 
                   2192:     return ($outcome,%userinfo);
                   2193: }
                   2194: 
1.1172.2.69  raeburn  2195: sub get_multiple_instusers {
                   2196:     my ($udom,$users,$caller) = @_;
                   2197:     my ($outcome,$results);
                   2198:     if (ref($users) eq 'HASH') {
                   2199:         my $count = keys(%{$users});
                   2200:         my $requested = &freeze_escape($users);
                   2201:         my $homeserver = &domain($udom,'primary');
                   2202:         if ($homeserver ne '') {
                   2203:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2204:             my $host=&hostname($homeserver);
                   2205:             if ($queryid !~/^\Q$host\E\_/) {
                   2206:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2207:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2208:                 return ($outcome,$results);
                   2209:             }
                   2210:             my $response = &get_query_reply($queryid);
                   2211:             my $maxtries = 5;
                   2212:             if ($count > 100) {
                   2213:                 $maxtries = 1+int($count/20);
                   2214:             }
                   2215:             my $tries = 1;
                   2216:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2217:                 $response = &get_query_reply($queryid);
                   2218:                 $tries ++;
                   2219:             }
                   2220:             if ($response eq '') {
                   2221:                 $results = {};
                   2222:                 foreach my $key (keys(%{$users})) {
                   2223:                     my ($uname,$id);
                   2224:                     if ($caller eq 'id') {
                   2225:                         $id = $key;
                   2226:                     } else {
                   2227:                         $uname = $key;
                   2228:                     }
                   2229:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2230:                     $outcome = $resp;
                   2231:                     if ($resp eq 'ok') {
                   2232:                         %{$results} = (%{$results}, %info);
                   2233:                     } else {
                   2234:                         last;
                   2235:                     }
                   2236:                 }
                   2237:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2238:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2239:                     $outcome = $response;
                   2240:                 } else {
                   2241:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2242:                     if ($outcome eq 'ok') {
                   2243:                         $results = &thaw_unescape($userdata);
                   2244:                     }
                   2245:                 }
                   2246:             }
                   2247:         }
                   2248:     }
                   2249:     return ($outcome,$results);
                   2250: }
                   2251: 
1.912     raeburn  2252: sub inst_rulecheck {
1.923     raeburn  2253:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2254:     my %returnhash;
                   2255:     if ($udom ne '') {
                   2256:         if (ref($rules) eq 'ARRAY') {
                   2257:             @{$rules} = map {&escape($_);} (@{$rules});
                   2258:             my $rulestr = join(':',@{$rules});
                   2259:             my $homeserver=&domain($udom,'primary');
                   2260:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2261:                 my $response;
                   2262:                 if ($item eq 'username') {                
                   2263:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2264:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2265:                                               $homeserver));
1.923     raeburn  2266:                 } elsif ($item eq 'id') {
                   2267:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2268:                                               ':'.&escape($id).':'.$rulestr,
                   2269:                                               $homeserver));
1.945     raeburn  2270:                 } elsif ($item eq 'selfcreate') {
                   2271:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2272:                                                &escape($udom).':'.&escape($uname).
                   2273:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2274:                 }
1.912     raeburn  2275:                 if ($response ne 'refused') {
                   2276:                     my @pairs=split(/\&/,$response);
                   2277:                     foreach my $item (@pairs) {
                   2278:                         my ($key,$value)=split(/=/,$item,2);
                   2279:                         $key = &unescape($key);
                   2280:                         next if ($key =~ /^error: 2 /);
                   2281:                         $returnhash{$key}=&thaw_unescape($value);
                   2282:                     }
                   2283:                 }
                   2284:             }
                   2285:         }
                   2286:     }
                   2287:     return %returnhash;
                   2288: }
                   2289: 
                   2290: sub inst_userrules {
1.923     raeburn  2291:     my ($udom,$check) = @_;
1.912     raeburn  2292:     my (%ruleshash,@ruleorder);
                   2293:     if ($udom ne '') {
                   2294:         my $homeserver=&domain($udom,'primary');
                   2295:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2296:             my $response;
                   2297:             if ($check eq 'id') {
                   2298:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2299:                                  $homeserver);
1.943     raeburn  2300:             } elsif ($check eq 'email') {
                   2301:                 $response=&reply('instemailrules:'.&escape($udom),
                   2302:                                  $homeserver);
1.923     raeburn  2303:             } else {
                   2304:                 $response=&reply('instuserrules:'.&escape($udom),
                   2305:                                  $homeserver);
                   2306:             }
1.912     raeburn  2307:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2308:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2309:                 ($response ne 'no_such_host')) {
                   2310:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2311:                 my @pairs=split(/\&/,$hashitems);
                   2312:                 foreach my $item (@pairs) {
                   2313:                     my ($key,$value)=split(/=/,$item,2);
                   2314:                     $key = &unescape($key);
                   2315:                     next if ($key =~ /^error: 2 /);
                   2316:                     $ruleshash{$key}=&thaw_unescape($value);
                   2317:                 }
                   2318:                 my @esc_order = split(/\&/,$orderitems);
                   2319:                 foreach my $item (@esc_order) {
                   2320:                     push(@ruleorder,&unescape($item));
                   2321:                 }
                   2322:             }
                   2323:         }
                   2324:     }
                   2325:     return (\%ruleshash,\@ruleorder);
                   2326: }
                   2327: 
1.976     raeburn  2328: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2329: 
                   2330: sub get_domain_defaults {
1.1172.2.35  raeburn  2331:     my ($domain,$ignore_cache) = @_;
                   2332:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2333:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2334:     unless ($ignore_cache) {
                   2335:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2336:         if (defined($cached)) {
                   2337:             if (ref($result) eq 'HASH') {
                   2338:                 return %{$result};
                   2339:             }
1.943     raeburn  2340:         }
                   2341:     }
                   2342:     my %domdefaults;
                   2343:     my %domconfig =
1.989     raeburn  2344:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2345:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2346:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2347:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2348:                                   'coursecategories','autoenroll',
                   2349:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2350:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2351:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2352:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2353:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2354:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2355:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2356:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2357:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2358:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2359:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2360:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2361:     } else {
                   2362:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2363:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2364:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2365:     }
1.976     raeburn  2366:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2367:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2368:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2369:         } else {
                   2370:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2371:         }
1.1172.2.6  raeburn  2372:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2373:         foreach my $item (@usertools) {
                   2374:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2375:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2376:             }
                   2377:         }
1.1172.2.29  raeburn  2378:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2379:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2380:         }
1.976     raeburn  2381:     }
1.985     raeburn  2382:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2383:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2384:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2385:         }
                   2386:     }
1.1172.2.9  raeburn  2387:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2388:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2389:     }
1.989     raeburn  2390:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2391:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2392:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2393:         }
                   2394:     }
1.1047    raeburn  2395:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2396:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2397:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2398:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2399:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2400:         }
1.1172.2.41  raeburn  2401:         foreach my $type (@coursetypes) {
                   2402:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2403:                 unless ($type eq 'community') {
                   2404:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2405:                 }
                   2406:             }
                   2407:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2408:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2409:             }
1.1172.2.60  raeburn  2410:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2411:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2412:                     $domdefaults{$type.'postsubtimeout'} =
                   2413:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2414:                 }
                   2415:             }
1.1172.2.30  raeburn  2416:         }
1.1172.2.67  raeburn  2417:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2418:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2419:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2420:                 if (@clonecodes) {
                   2421:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2422:                 }
                   2423:             }
                   2424:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2425:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2426:         }
1.1172.2.103  raeburn  2427:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2428:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2429:         }
1.1047    raeburn  2430:     }
1.1073    raeburn  2431:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2432:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2433:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2434:         }
                   2435:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2436:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2437:         }
1.1172.2.62  raeburn  2438:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2439:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2440:         }
1.1172.2.137  raeburn  2441:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2442:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2443:         }
1.1073    raeburn  2444:     }
1.1172.2.41  raeburn  2445:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2446:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2447:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2448:                             'approval','limit');
                   2449:             foreach my $type (@coursetypes) {
                   2450:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2451:                     my @mgrdc = ();
                   2452:                     foreach my $item (@settings) {
                   2453:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2454:                             push(@mgrdc,$item);
                   2455:                         }
                   2456:                     }
                   2457:                     if (@mgrdc) {
                   2458:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2459:                     }
                   2460:                 }
                   2461:             }
                   2462:         }
                   2463:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2464:             foreach my $type (@coursetypes) {
                   2465:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2466:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2467:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2468:                     }
                   2469:                 }
                   2470:             }
                   2471:         }
                   2472:     }
1.1172.2.46  raeburn  2473:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2474:         $domdefaults{'catauth'} = 'std';
                   2475:         $domdefaults{'catunauth'} = 'std';
                   2476:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2477:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2478:         }
                   2479:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2480:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2481:         }
                   2482:     }
1.1172.2.76  raeburn  2483:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2484:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2485:     }
1.1172.2.89  raeburn  2486:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2487:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2488:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2489:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2490:         }
                   2491:     }
1.1172.2.142  raeburn  2492:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2493:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2494:             if ($domconfig{'wafproxy'}{$item}) {
                   2495:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2496:             }
                   2497:         }
                   2498:     }
1.1172.2.23  raeburn  2499:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2500:     return %domdefaults;
                   2501: }
                   2502: 
1.1172.2.106  raeburn  2503: sub get_dom_cats {
                   2504:     my ($dom) = @_;
                   2505:     return unless (&domain($dom));
                   2506:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2507:     unless (defined($cached)) {
                   2508:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2509:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2510:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2511:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2512:             } else {
                   2513:                 $cats = {};
                   2514:             }
                   2515:         } else {
                   2516:             $cats = {};
                   2517:         }
                   2518:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2519:     }
                   2520:     return $cats;
                   2521: }
                   2522: 
                   2523: sub get_dom_instcats {
                   2524:     my ($dom) = @_;
                   2525:     return unless (&domain($dom));
                   2526:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2527:     unless (defined($cached)) {
                   2528:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2529:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2530:         if ($totcodes > 0) {
                   2531:             my $caller = 'global';
                   2532:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2533:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2534:                 $instcats = {
                   2535:                                 codes => \%codes,
                   2536:                                 codetitles => \@codetitles,
                   2537:                                 cat_titles => \%cat_titles,
                   2538:                                 cat_order => \%cat_order,
                   2539:                             };
                   2540:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2541:             }
                   2542:         }
                   2543:     }
                   2544:     return $instcats;
                   2545: }
                   2546: 
                   2547: sub retrieve_instcodes {
                   2548:     my ($coursecodes,$dom) = @_;
                   2549:     my $totcodes;
                   2550:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2551:     foreach my $course (keys(%courses)) {
                   2552:         if (ref($courses{$course}) eq 'HASH') {
                   2553:             if ($courses{$course}{'inst_code'} ne '') {
                   2554:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2555:                 $totcodes ++;
                   2556:             }
                   2557:         }
                   2558:     }
                   2559:     return $totcodes;
                   2560: }
                   2561: 
1.1172.2.113  raeburn  2562: # --------------------------------------------- Get domain config for passwords
                   2563: 
                   2564: sub get_passwdconf {
                   2565:     my ($dom) = @_;
                   2566:     my (%passwdconf,$gotconf,$lookup);
                   2567:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2568:     if (defined($cached)) {
                   2569:         if (ref($result) eq 'HASH') {
                   2570:             %passwdconf = %{$result};
                   2571:             $gotconf = 1;
                   2572:         }
                   2573:     }
                   2574:     unless ($gotconf) {
                   2575:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2576:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2577:             %passwdconf = %{$domconfig{'passwords'}};
                   2578:         }
                   2579:         my $cachetime = 24*60*60;
                   2580:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2581:     }
                   2582:     return %passwdconf;
                   2583: }
                   2584: 
1.344     www      2585: # --------------------------------------------------- Assign a key to a student
                   2586: 
                   2587: sub assign_access_key {
1.364     www      2588: #
                   2589: # a valid key looks like uname:udom#comments
                   2590: # comments are being appended
                   2591: #
1.498     www      2592:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2593:     $kdom=
1.620     albertel 2594:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2595:     $knum=
1.620     albertel 2596:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2597:     $cdom=
1.620     albertel 2598:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2599:     $cnum=
1.620     albertel 2600:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2601:     $udom=$env{'user.name'} unless (defined($udom));
                   2602:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2603:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2604:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2605:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2606:                                                   # assigned to this person
                   2607:                                                   # - this should not happen,
1.345     www      2608:                                                   # unless something went wrong
                   2609:                                                   # the first time around
                   2610: # ready to assign
1.364     www      2611:         $logentry=$1.'; '.$logentry;
1.496     www      2612:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2613:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2614: # key now belongs to user
1.346     www      2615: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2616:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2617:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2618:                 return 'ok';
                   2619:             } else {
                   2620:                 return 
                   2621:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2622: 	    }
                   2623:         } else {
                   2624:             return 'error: Could not assign key, try again later.';
                   2625:         }
1.364     www      2626:     } elsif (!$existing{$ckey}) {
1.345     www      2627: # the key does not exist
                   2628: 	return 'error: The key does not exist';
                   2629:     } else {
                   2630: # the key is somebody else's
                   2631: 	return 'error: The key is already in use';
                   2632:     }
1.344     www      2633: }
                   2634: 
1.364     www      2635: # ------------------------------------------ put an additional comment on a key
                   2636: 
                   2637: sub comment_access_key {
                   2638: #
                   2639: # a valid key looks like uname:udom#comments
                   2640: # comments are being appended
                   2641: #
                   2642:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2643:     $cdom=
1.620     albertel 2644:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2645:     $cnum=
1.620     albertel 2646:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2647:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2648:     if ($existing{$ckey}) {
                   2649:         $existing{$ckey}.='; '.$logentry;
                   2650: # ready to assign
1.367     www      2651:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2652:                                                  $cdom,$cnum) eq 'ok') {
                   2653: 	    return 'ok';
                   2654:         } else {
                   2655: 	    return 'error: Count not store comment.';
                   2656:         }
                   2657:     } else {
                   2658: # the key does not exist
                   2659: 	return 'error: The key does not exist';
                   2660:     }
                   2661: }
                   2662: 
1.344     www      2663: # ------------------------------------------------------ Generate a set of keys
                   2664: 
                   2665: sub generate_access_keys {
1.364     www      2666:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2667:     $cdom=
1.620     albertel 2668:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2669:     $cnum=
1.620     albertel 2670:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2671:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2672:     unless (($cdom) && ($cnum)) { return 0; }
                   2673:     if ($number>10000) { return 0; }
                   2674:     sleep(2); # make sure don't get same seed twice
                   2675:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2676:     my $total=0;
                   2677:     for (my $i=1;$i<=$number;$i++) {
                   2678:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2679:                   sprintf("%lx",int(100000*rand)).'-'.
                   2680:                   sprintf("%lx",int(100000*rand));
                   2681:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2682:        $newkey=~s/0/h/g; # and also 0 and O
                   2683:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2684:        if ($existing{$newkey}) {
                   2685:            $i--;
                   2686:        } else {
1.364     www      2687: 	  if (&put('accesskeys',
                   2688:               { $newkey => '# generated '.localtime().
1.620     albertel 2689:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2690:                            '; '.$logentry },
                   2691: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2692:               $total++;
                   2693: 	  }
                   2694:        }
                   2695:     }
1.620     albertel 2696:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2697:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2698:     return $total;
                   2699: }
                   2700: 
                   2701: # ------------------------------------------------------- Validate an accesskey
                   2702: 
                   2703: sub validate_access_key {
                   2704:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2705:     $cdom=
1.620     albertel 2706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2707:     $cnum=
1.620     albertel 2708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2709:     $udom=$env{'user.domain'} unless (defined($udom));
                   2710:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2711:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2712:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2713: }
                   2714: 
                   2715: # ------------------------------------- Find the section of student in a course
1.652     albertel 2716: sub devalidate_getsection_cache {
                   2717:     my ($udom,$unam,$courseid)=@_;
                   2718:     my $hashid="$udom:$unam:$courseid";
                   2719:     &devalidate_cache_new('getsection',$hashid);
                   2720: }
1.298     matthew  2721: 
1.815     albertel 2722: sub courseid_to_courseurl {
                   2723:     my ($courseid) = @_;
                   2724:     #already url style courseid
                   2725:     return $courseid if ($courseid =~ m{^/});
                   2726: 
                   2727:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2728: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2729: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2730: 	return "/$cdom/$cnum";
                   2731:     }
                   2732: 
                   2733:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2734:     if (exists($courseinfo{'num'})) {
                   2735: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2736:     }
                   2737: 
                   2738:     return undef;
                   2739: }
                   2740: 
1.298     matthew  2741: sub getsection {
                   2742:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2743:     my $cachetime=1800;
1.551     albertel 2744: 
                   2745:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2746:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2747:     if (defined($cached)) { return $result; }
                   2748: 
1.298     matthew  2749:     my %Pending; 
                   2750:     my %Expired;
                   2751:     #
                   2752:     # Each role can either have not started yet (pending), be active, 
                   2753:     #    or have expired.
                   2754:     #
                   2755:     # If there is an active role, we are done.
                   2756:     #
                   2757:     # If there is more than one role which has not started yet, 
                   2758:     #     choose the one which will start sooner
                   2759:     # If there is one role which has not started yet, return it.
                   2760:     #
                   2761:     # If there is more than one expired role, choose the one which ended last.
                   2762:     # If there is a role which has expired, return it.
                   2763:     #
1.815     albertel 2764:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2765:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2766:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2767:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2768:         my $section=$1;
                   2769:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2770:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2771:         my $now=time;
1.548     albertel 2772:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2773:             $Expired{$end}=$section;
                   2774:             next;
                   2775:         }
1.548     albertel 2776:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2777:             $Pending{$start}=$section;
                   2778:             next;
                   2779:         }
1.599     albertel 2780:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2781:     }
                   2782:     #
                   2783:     # Presumedly there will be few matching roles from the above
                   2784:     # loop and the sorting time will be negligible.
                   2785:     if (scalar(keys(%Pending))) {
                   2786:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2787:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2788:     } 
                   2789:     if (scalar(keys(%Expired))) {
                   2790:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2791:         my $time = pop(@sorted);
1.599     albertel 2792:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2793:     }
1.599     albertel 2794:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2795: }
1.70      www      2796: 
1.599     albertel 2797: sub save_cache {
                   2798:     &purge_remembered();
1.722     albertel 2799:     #&Apache::loncommon::validate_page();
1.620     albertel 2800:     undef(%env);
1.780     albertel 2801:     undef($env_loaded);
1.599     albertel 2802: }
1.452     albertel 2803: 
1.599     albertel 2804: my $to_remember=-1;
                   2805: my %remembered;
                   2806: my %accessed;
                   2807: my $kicks=0;
                   2808: my $hits=0;
1.849     albertel 2809: sub make_key {
                   2810:     my ($name,$id) = @_;
1.872     albertel 2811:     if (length($id) > 65 
                   2812: 	&& length(&escape($id)) > 200) {
                   2813: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2814:     }
1.849     albertel 2815:     return &escape($name.':'.$id);
                   2816: }
                   2817: 
1.599     albertel 2818: sub devalidate_cache_new {
                   2819:     my ($name,$id,$debug) = @_;
                   2820:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2821:     my $remembered_id=$name.':'.$id;
1.849     albertel 2822:     $id=&make_key($name,$id);
1.599     albertel 2823:     $memcache->delete($id);
1.1172.2.81  raeburn  2824:     delete($remembered{$remembered_id});
                   2825:     delete($accessed{$remembered_id});
1.599     albertel 2826: }
                   2827: 
                   2828: sub is_cached_new {
                   2829:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2830:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2831:                                      # keys in %remembered hash, which persists for
                   2832:                                      # duration of request (no restriction on key length).
                   2833:     if (exists($remembered{$remembered_id})) {
                   2834: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2835: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2836: 	$hits++;
1.1172.2.81  raeburn  2837: 	return ($remembered{$remembered_id},1);
1.599     albertel 2838:     }
1.1172.2.81  raeburn  2839:     $id=&make_key($name,$id);
1.599     albertel 2840:     my $value = $memcache->get($id);
                   2841:     if (!(defined($value))) {
                   2842: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2843: 	return (undef,undef);
1.416     albertel 2844:     }
1.599     albertel 2845:     if ($value eq '__undef__') {
                   2846: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2847: 	$value=undef;
                   2848:     }
1.1172.2.81  raeburn  2849:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2850:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2851:     return ($value,1);
                   2852: }
                   2853: 
                   2854: sub do_cache_new {
                   2855:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2856:     my $remembered_id=$name.':'.$id;
1.849     albertel 2857:     $id=&make_key($name,$id);
1.599     albertel 2858:     my $setvalue=$value;
                   2859:     if (!defined($setvalue)) {
                   2860: 	$setvalue='__undef__';
                   2861:     }
1.623     albertel 2862:     if (!defined($time) ) {
                   2863: 	$time=600;
                   2864:     }
1.599     albertel 2865:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2866:     my $result = $memcache->set($id,$setvalue,$time);
                   2867:     if (! $result) {
1.872     albertel 2868: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2869: 	$memcache->disconnect_all();
1.872     albertel 2870:     }
1.600     albertel 2871:     # need to make a copy of $value
1.1172.2.81  raeburn  2872:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2873:     return $value;
                   2874: }
                   2875: 
                   2876: sub make_room {
1.1172.2.81  raeburn  2877:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2878: 
1.1172.2.81  raeburn  2879:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2880:                                     : $value;
1.599     albertel 2881:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2882:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2883:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2884:     my $to_kick;
                   2885:     my $max_time=0;
                   2886:     foreach my $other (keys(%accessed)) {
                   2887: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2888: 	    $to_kick=$other;
                   2889: 	    $max_time=&tv_interval($accessed{$other});
                   2890: 	}
                   2891:     }
                   2892:     delete($remembered{$to_kick});
                   2893:     delete($accessed{$to_kick});
                   2894:     $kicks++;
                   2895:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2896:     return;
                   2897: }
                   2898: 
1.599     albertel 2899: sub purge_remembered {
1.604     albertel 2900:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2901:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2902:     undef(%remembered);
                   2903:     undef(%accessed);
1.428     albertel 2904: }
1.70      www      2905: # ------------------------------------- Read an entry from a user's environment
                   2906: 
                   2907: sub userenvironment {
                   2908:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2909:     my $items;
                   2910:     foreach my $item (@what) {
                   2911:         $items.=&escape($item).'&';
                   2912:     }
                   2913:     $items=~s/\&$//;
1.70      www      2914:     my %returnhash=();
1.1009    raeburn  2915:     my $uhome = &homeserver($unam,$udom);
                   2916:     unless ($uhome eq 'no_host') {
                   2917:         my @answer=split(/\&/, 
                   2918:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2919:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2920:             return %returnhash;
                   2921:         }
1.1009    raeburn  2922:         my $i;
                   2923:         for ($i=0;$i<=$#what;$i++) {
                   2924: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2925:         }
1.70      www      2926:     }
                   2927:     return %returnhash;
1.1       albertel 2928: }
                   2929: 
1.617     albertel 2930: # ---------------------------------------------------------- Get a studentphoto
                   2931: sub studentphoto {
                   2932:     my ($udom,$unam,$ext) = @_;
                   2933:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2934:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2935:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2936:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2937:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2938:             } else {
                   2939:                 my ($result,$perm_reqd)=
1.707     albertel 2940: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2941:                 if ($result eq 'ok') {
                   2942:                     if (!($perm_reqd eq 'yes')) {
                   2943:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2944:                     }
                   2945:                 }
                   2946:             }
                   2947:         }
                   2948:     } else {
                   2949:         my ($result,$perm_reqd) = 
1.707     albertel 2950: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2951:         if ($result eq 'ok') {
                   2952:             if (!($perm_reqd eq 'yes')) {
                   2953:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2954:             }
                   2955:         }
                   2956:     }
                   2957:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2958: }
                   2959: 
                   2960: sub retrievestudentphoto {
                   2961:     my ($udom,$unam,$ext,$type) = @_;
                   2962:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2963:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2964:     if ($ret eq 'ok') {
                   2965:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2966:         if ($type eq 'thumbnail') {
                   2967:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2968:         }
                   2969:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2970:         return $tokenurl;
                   2971:     } else {
                   2972:         if ($type eq 'thumbnail') {
                   2973:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2974:         } else { 
                   2975:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2976:         }
1.617     albertel 2977:     }
                   2978: }
                   2979: 
1.263     www      2980: # -------------------------------------------------------------------- New chat
                   2981: 
                   2982: sub chatsend {
1.724     raeburn  2983:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2984:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2985:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2986:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2987:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2988: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2989: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2990: }
                   2991: 
                   2992: # ------------------------------------------ Find current version of a resource
                   2993: 
                   2994: sub getversion {
                   2995:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2996:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2997:     return &currentversion(&filelocation('',$fname));
                   2998: }
                   2999: 
                   3000: sub currentversion {
                   3001:     my $fname=shift;
                   3002:     my $author=$fname;
                   3003:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3004:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3005:     my $home=&homeserver($uname,$udom);
1.292     www      3006:     if ($home eq 'no_host') { 
                   3007:         return -1; 
                   3008:     }
1.1112    www      3009:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3010:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3011: 	return -1;
                   3012:     }
1.1112    www      3013:     return $answer;
1.263     www      3014: }
                   3015: 
1.1111    www      3016: #
                   3017: # Return special version number of resource if set by override, empty otherwise
                   3018: #
                   3019: sub usedversion {
                   3020:     my $fname=shift;
                   3021:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3022:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3023:     if ($urlversion) { return $urlversion; }
                   3024:     return '';
                   3025: }
                   3026: 
1.1       albertel 3027: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3028: 
1.1       albertel 3029: sub subscribe {
                   3030:     my $fname=shift;
1.761     raeburn  3031:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3032:     $fname=~s/[\n\r]//g;
1.1       albertel 3033:     my $author=$fname;
                   3034:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3035:     my ($udom,$uname)=split(/\//,$author);
                   3036:     my $home=homeserver($uname,$udom);
1.335     albertel 3037:     if ($home eq 'no_host') {
                   3038:         return 'not_found';
1.1       albertel 3039:     }
                   3040:     my $answer=reply("sub:$fname",$home);
1.64      www      3041:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3042: 	$answer.=' by '.$home;
                   3043:     }
1.1       albertel 3044:     return $answer;
                   3045: }
                   3046:     
1.8       www      3047: # -------------------------------------------------------------- Replicate file
                   3048: 
                   3049: sub repcopy {
                   3050:     my $filename=shift;
1.23      www      3051:     $filename=~s/\/+/\//g;
1.1142    raeburn  3052:     my $londocroot = $perlvar{'lonDocRoot'};
                   3053:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3054:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3055:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3056: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3057: 	return &repcopy_userfile($filename);
                   3058:     }
1.532     albertel 3059:     $filename=~s/[\n\r]//g;
1.8       www      3060:     my $transname="$filename.in.transfer";
1.828     www      3061: # FIXME: this should flock
1.607     raeburn  3062:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3063:     my $remoteurl=subscribe($filename);
1.64      www      3064:     if ($remoteurl =~ /^con_lost by/) {
                   3065: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3066:            return 'unavailable';
1.8       www      3067:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3068: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3069: 	   return 'not_found';
1.64      www      3070:     } elsif ($remoteurl =~ /^rejected by/) {
                   3071: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3072:            return 'forbidden';
1.20      www      3073:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3074:            return 'ok';
1.8       www      3075:     } else {
1.290     www      3076:         my $author=$filename;
                   3077:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3078:         my ($udom,$uname)=split(/\//,$author);
                   3079:         my $home=homeserver($uname,$udom);
                   3080:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3081:            my @parts=split(/\//,$filename);
                   3082:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3083:            if ($path ne "$londocroot/res") {
1.8       www      3084:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3085: 	       return 'bad_request';
1.8       www      3086:            }
                   3087:            my $count;
                   3088:            for ($count=5;$count<$#parts;$count++) {
                   3089:                $path.="/$parts[$count]";
                   3090:                if ((-e $path)!=1) {
                   3091: 		   mkdir($path,0777);
                   3092:                }
                   3093:            }
                   3094:            my $ua=new LWP::UserAgent;
                   3095:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3096:            my $response=$ua->request($request,$transname);
                   3097:            if ($response->is_error()) {
                   3098: 	       unlink($transname);
                   3099:                my $message=$response->status_line;
1.672     albertel 3100:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3101:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3102:                return 'unavailable';
1.8       www      3103:            } else {
1.16      www      3104: 	       if ($remoteurl!~/\.meta$/) {
                   3105:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3106:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3107:                   if ($mresponse->is_error()) {
                   3108: 		      unlink($filename.'.meta');
                   3109:                       &logthis(
1.672     albertel 3110:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3111:                   }
                   3112: 	       }
1.8       www      3113:                rename($transname,$filename);
1.607     raeburn  3114:                return 'ok';
1.8       www      3115:            }
1.290     www      3116:        }
1.8       www      3117:     }
1.330     www      3118: }
                   3119: 
1.1172.2.124  raeburn  3120: # ------------------------------------------------- Unsubscribe from a resource
                   3121: 
                   3122: sub unsubscribe {
                   3123:     my ($fname) = @_;
                   3124:     my $answer;
                   3125:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3126:     $fname=~s/[\n\r]//g;
                   3127:     my $author=$fname;
                   3128:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3129:     my ($udom,$uname)=split(/\//,$author);
                   3130:     my $home=homeserver($uname,$udom);
                   3131:     if ($home eq 'no_host') {
                   3132:         $answer = 'no_host';
                   3133:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3134:         $answer = 'home';
                   3135:     } else {
1.1172.2.125  raeburn  3136:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3137:     }
                   3138:     return $answer;
                   3139: }
                   3140: 
1.330     www      3141: # ------------------------------------------------ Get server side include body
                   3142: sub ssi_body {
1.381     albertel 3143:     my ($filelink,%form)=@_;
1.606     matthew  3144:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3145:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3146:     }
1.953     www      3147:     my $output='';
                   3148:     my $response;
1.980     raeburn  3149:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3150:        ($output,$response)=&externalssi($filelink);
1.953     www      3151:     } else {
1.1004    droeschl 3152:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3153:        $filelink .= 'inhibitmenu=yes';
1.953     www      3154:        ($output,$response)=&ssi($filelink,%form);
                   3155:     }
1.778     albertel 3156:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3157:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3158:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3159:     if (wantarray) {
                   3160:         return ($output, $response);
                   3161:     } else {
                   3162:         return $output;
                   3163:     }
1.8       www      3164: }
                   3165: 
1.15      www      3166: # --------------------------------------------------------- Server Side Include
                   3167: 
1.782     albertel 3168: sub absolute_url {
                   3169:     my ($host_name) = @_;
                   3170:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3171:     if ($host_name eq '') {
                   3172: 	$host_name = $ENV{'SERVER_NAME'};
                   3173:     }
                   3174:     return $protocol.$host_name;
                   3175: }
                   3176: 
1.942     foxr     3177: #
                   3178: #   Server side include.
                   3179: # Parameters:
                   3180: #  fn     Possibly encrypted resource name/id.
                   3181: #  form   Hash that describes how the rendering should be done
                   3182: #         and other things.
1.944     foxr     3183: # Returns:
1.950     raeburn  3184: #   Scalar context: The content of the response.
                   3185: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3186: #     
1.15      www      3187: sub ssi {
                   3188: 
1.944     foxr     3189:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3190:     my ($request,$response);
1.711     albertel 3191: 
                   3192:     $form{'no_update_last_known'}=1;
1.895     albertel 3193:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3194:     if (%form) {
1.782     albertel 3195:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3196:       $request->content(join('&',map {
                   3197:             my $name = escape($_);
                   3198:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3199:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3200:             : &escape($form{$_}) );
                   3201:         } keys(%form)));
1.23      www      3202:     } else {
1.782     albertel 3203:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3204:     }
                   3205: 
1.15      www      3206:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3207: 
1.1172.2.101  raeburn  3208:     if (($env{'request.course.id'}) &&
                   3209:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3210:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3211:         ($form{'grade_symb'} ne '') &&
                   3212:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3213:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3214:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3215:             my $ua=new LWP::UserAgent;
                   3216:             $ua->local_address('127.0.0.1');
                   3217:             $response = $ua->request($request);
                   3218:         } else {
                   3219:             {
                   3220:                 require LWP::Protocol::http;
                   3221:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3222:                 my $ua=new LWP::UserAgent;
                   3223:                 $response = $ua->request($request);
                   3224:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3225:             }
                   3226:         }
                   3227:     } else {
                   3228:         my $ua=new LWP::UserAgent;
                   3229:         $response = $ua->request($request);
                   3230:     }
1.944     foxr     3231:     if (wantarray) {
1.1172.2.3  raeburn  3232: 	return ($response->content, $response);
1.944     foxr     3233:     } else {
1.1172.2.3  raeburn  3234: 	return $response->content;
1.942     foxr     3235:     }
1.324     www      3236: }
                   3237: 
                   3238: sub externalssi {
                   3239:     my ($url)=@_;
                   3240:     my $ua=new LWP::UserAgent;
                   3241:     my $request=new HTTP::Request('GET',$url);
                   3242:     my $response=$ua->request($request);
1.954     raeburn  3243:     if (wantarray) {
                   3244:         return ($response->content, $response);
                   3245:     } else {
                   3246:         return $response->content;
                   3247:     }
1.15      www      3248: }
1.254     www      3249: 
1.1172.2.98  raeburn  3250: # If the local copy of a replicated resource is outdated, trigger a
                   3251: # connection from the homeserver to flush the delayed queue. If no update
                   3252: # happens, remove local copies of outdated resource (and corresponding
                   3253: # metadata file).
                   3254: 
                   3255: sub remove_stale_resfile {
                   3256:     my ($url) = @_;
                   3257:     my $removed;
                   3258:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3259:         my $audom = $1;
                   3260:         my $auname = $2;
                   3261:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3262:             my $homeserver = &homeserver($auname,$audom);
                   3263:             unless (($homeserver eq 'no_host') ||
                   3264:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3265:                 my $fname = &filelocation('',$url);
                   3266:                 if (-e $fname) {
                   3267:                     my $hostname = &hostname($homeserver);
                   3268:                     if ($hostname) {
1.1172.2.120  raeburn  3269:                         my $protocol = $protocol{$homeserver};
                   3270:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3271:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3272:                         my $ua=new LWP::UserAgent;
                   3273:                         $ua->timeout(5);
1.1172.2.98  raeburn  3274:                         my $request=new HTTP::Request('HEAD',$uri);
                   3275:                         my $response=$ua->request($request);
                   3276:                         if ($response->is_success()) {
                   3277:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3278:                             my $locmodtime = (stat($fname))[9];
                   3279:                             if ($locmodtime < $remmodtime) {
                   3280:                                 my $stale;
                   3281:                                 my $answer = &reply('pong',$homeserver);
                   3282:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3283:                                     sleep(0.2);
                   3284:                                     $locmodtime = (stat($fname))[9];
                   3285:                                     if ($locmodtime < $remmodtime) {
                   3286:                                         my $posstransfer = $fname.'.in.transfer';
                   3287:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3288:                                             $removed = 1;
                   3289:                                         } else {
                   3290:                                             $stale = 1;
                   3291:                                         }
                   3292:                                     } else {
                   3293:                                         $removed = 1;
                   3294:                                     }
                   3295:                                 } else {
                   3296:                                     $stale = 1;
                   3297:                                 }
                   3298:                                 if ($stale) {
1.1172.2.124  raeburn  3299:                                     if (unlink($fname)) {
                   3300:                                         if ($uri!~/\.meta$/) {
                   3301:                                             if (-e $fname.'.meta') {
                   3302:                                                 unlink($fname.'.meta');
                   3303:                                             }
                   3304:                                         }
                   3305:                                         my $unsubresult = &unsubscribe($fname);
                   3306:                                         unless ($unsubresult eq 'ok') {
                   3307:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3308:                                         }
                   3309:                                         $removed = 1;
1.1172.2.98  raeburn  3310:                                     }
                   3311:                                 }
                   3312:                             }
                   3313:                         }
                   3314:                     }
                   3315:                 }
                   3316:             }
                   3317:         }
                   3318:     }
                   3319:     return $removed;
                   3320: }
                   3321: 
1.492     albertel 3322: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3323: 
                   3324: sub allowuploaded {
                   3325:     my ($srcurl,$url)=@_;
                   3326:     $url=&clutter(&declutter($url));
                   3327:     my $dir=$url;
                   3328:     $dir=~s/\/[^\/]+$//;
                   3329:     my %httpref=();
                   3330:     my $httpurl=&hreflocation('',$url);
                   3331:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3332:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3333: }
1.477     raeburn  3334: 
1.1172.2.13  raeburn  3335: #
                   3336: # Determine if the current user should be able to edit a particular resource,
                   3337: # when viewing in course context.
                   3338: # (a) When viewing resource used to determine if "Edit" item is included in
                   3339: #     Functions.
                   3340: # (b) When displaying folder contents in course editor, used to determine if
                   3341: #     "Edit" link will be displayed alongside resource.
                   3342: #
                   3343: #  input: six args -- filename (decluttered), course number, course domain,
                   3344: #                   url, symb (if registered) and group (if this is a group
                   3345: #                   item -- e.g., bulletin board, group page etc.).
                   3346: #  output: array of five scalars --
                   3347: #          $cfile -- url for file editing if editable on current server
                   3348: #          $home -- homeserver of resource (i.e., for author if published,
                   3349: #                                           or course if uploaded.).
                   3350: #          $switchserver --  1 if server switch will be needed.
                   3351: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3352: #          $forceview -- 1 if icon/link should be to go to view mode
                   3353: #
                   3354: 
                   3355: sub can_edit_resource {
                   3356:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3357:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3358: #
                   3359: # For aboutme pages user can only edit his/her own.
                   3360: #
                   3361:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3362:         my ($sdom,$sname) = ($1,$2);
                   3363:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3364:             $home = $env{'user.home'};
                   3365:             $cfile = $resurl;
                   3366:             if ($env{'form.forceedit'}) {
                   3367:                 $forceview = 1;
                   3368:             } else {
                   3369:                 $forceedit = 1;
                   3370:             }
                   3371:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3372:         } else {
                   3373:             return;
                   3374:         }
                   3375:     }
                   3376: 
                   3377:     if ($env{'request.course.id'}) {
                   3378:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3379:         if ($group ne '') {
                   3380: # if this is a group homepage or group bulletin board, check group privs
                   3381:             my $allowed = 0;
                   3382:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3383:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3384:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3385:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3386:                     $allowed = 1;
                   3387:                 }
                   3388:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3389:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3390:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3391:                     $allowed = 1;
                   3392:                 }
                   3393:             }
                   3394:             if ($allowed) {
                   3395:                 $home=&homeserver($cnum,$cdom);
                   3396:                 if ($env{'form.forceedit'}) {
                   3397:                     $forceview = 1;
                   3398:                 } else {
                   3399:                     $forceedit = 1;
                   3400:                 }
                   3401:                 $cfile = $resurl;
                   3402:             } else {
                   3403:                 return;
                   3404:             }
                   3405:         } else {
1.1172.2.15  raeburn  3406:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3407:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3408:                     return;
                   3409:                 }
                   3410:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3411: #
                   3412: # No edit allowed where CC has switched to student role.
                   3413: #
                   3414:                 return;
                   3415:             }
                   3416:         }
                   3417:     }
                   3418: 
                   3419:     if ($file ne '') {
                   3420:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3421:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3422:                 $uploaded = 1;
                   3423:                 $incourse = 1;
                   3424:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3425:                     $cfile = &hreflocation('',$file);
                   3426:                     if ($env{'form.forceedit'}) {
                   3427:                         $forceview = 1;
                   3428:                     } else {
                   3429:                         $forceedit = 1;
                   3430:                     }
                   3431:                 }
                   3432:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3433:                 $incourse = 1;
                   3434:                 if ($env{'form.forceedit'}) {
                   3435:                     $forceview = 1;
                   3436:                 } else {
                   3437:                     $forceedit = 1;
                   3438:                 }
                   3439:                 $cfile = $resurl;
                   3440:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3441:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3442:                     $incourse = 1;
                   3443:                     if ($env{'form.forceedit'}) {
                   3444:                         $forceview = 1;
                   3445:                     } else {
                   3446:                         $forceedit = 1;
                   3447:                     }
                   3448:                     $cfile = $resurl;
                   3449:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3450:                     $incourse = 1;
                   3451:                     $cfile = $resurl.'/smpedit';
                   3452:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3453:                     $incourse = 1;
                   3454:                     if ($env{'form.forceedit'}) {
                   3455:                         $forceview = 1;
                   3456:                     } else {
                   3457:                         $forceedit = 1;
                   3458:                     }
                   3459:                     $cfile = $resurl;
1.1172.2.122  raeburn  3460:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3461:                     my ($map,$id,$res) = &decode_symb($symb);
                   3462:                     if ($map =~ /\.page$/) {
                   3463:                         $incourse = 1;
                   3464:                         if ($env{'form.forceedit'}) {
                   3465:                             $forceview = 1;
                   3466:                             $cfile = $map;
                   3467:                         } else {
                   3468:                             $forceedit = 1;
                   3469:                             $cfile =  '/adm/wrapper'.$resurl;
                   3470:                         }
                   3471:                     }
1.1172.2.15  raeburn  3472:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3473:                     $incourse = 1;
                   3474:                     if ($env{'form.forceedit'}) {
                   3475:                         $forceview = 1;
                   3476:                     } else {
                   3477:                         $forceedit = 1;
                   3478:                     }
                   3479:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3480:                 }
                   3481:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3482:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3483:                 if (&is_on_map($template)) {
                   3484:                     $incourse = 1;
                   3485:                     $forceview = 1;
                   3486:                     $cfile = $template;
                   3487:                 }
                   3488:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3489:                 $incourse = 1;
                   3490:                 if ($env{'form.forceedit'}) {
                   3491:                     $forceview = 1;
                   3492:                 } else {
                   3493:                     $forceedit = 1;
                   3494:                 }
                   3495:                 $cfile = $resurl;
1.1172.2.13  raeburn  3496:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3497:                 $incourse = 1;
                   3498:                 $forceview = 1;
                   3499:                 if ($symb) {
                   3500:                     my ($map,$id,$res)=&decode_symb($symb);
                   3501:                     $env{'request.symb'} = $symb;
                   3502:                     $cfile = &clutter($res);
                   3503:                 } else {
                   3504:                     $cfile = $env{'form.suppurl'};
                   3505:                     $cfile =~ s{^http://}{};
                   3506:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3507:                 }
1.1172.2.31  raeburn  3508:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3509:                 if ($env{'form.forceedit'}) {
                   3510:                     $forceview = 1;
                   3511:                 } else {
                   3512:                     $forceedit = 1;
                   3513:                 }
                   3514:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3515:             }
                   3516:         }
                   3517:         if ($uploaded || $incourse) {
                   3518:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3519:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3520:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3521:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3522:             # Check that the user has permission to edit this resource
                   3523:             my $setpriv = 1;
                   3524:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3525:             if (defined($cfudom)) {
                   3526:                 $home=&homeserver($cfuname,$cfudom);
                   3527:                 $cfile=$file;
                   3528:             }
                   3529:         }
                   3530:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3531:             (($home ne '') && ($home ne 'no_host'))) {
                   3532:             my @ids=&current_machine_ids();
                   3533:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3534:                 $switchserver=1;
                   3535:             }
                   3536:         }
                   3537:     }
                   3538:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3539: }
                   3540: 
                   3541: sub is_course_upload {
                   3542:     my ($file,$cnum,$cdom) = @_;
                   3543:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3544:     $uploadpath =~ s{^\/}{};
                   3545:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3546:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3547:         return 1;
                   3548:     }
                   3549:     return;
                   3550: }
                   3551: 
                   3552: sub in_course {
                   3553:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3554:     if ($hideprivileged) {
                   3555:         my $skipuser;
1.1172.2.23  raeburn  3556:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3557:         my @possdoms = ($cdom);
                   3558:         if ($coursehash{'checkforpriv'}) {
                   3559:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3560:         }
                   3561:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3562:             $skipuser = 1;
                   3563:             if ($coursehash{'nothideprivileged'}) {
                   3564:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3565:                     my $user;
                   3566:                     if ($item =~ /:/) {
                   3567:                         $user = $item;
                   3568:                     } else {
                   3569:                         $user = join(':',split(/[\@]/,$item));
                   3570:                     }
                   3571:                     if ($user eq $uname.':'.$udom) {
                   3572:                         undef($skipuser);
                   3573:                         last;
                   3574:                     }
                   3575:                 }
                   3576:             }
                   3577:             if ($skipuser) {
                   3578:                 return 0;
                   3579:             }
                   3580:         }
                   3581:     }
                   3582:     $type ||= 'any';
                   3583:     if (!defined($cdom) || !defined($cnum)) {
                   3584:         my $cid  = $env{'request.course.id'};
                   3585:         $cdom = $env{'course.'.$cid.'.domain'};
                   3586:         $cnum = $env{'course.'.$cid.'.num'};
                   3587:     }
                   3588:     my $typesref;
                   3589:     if (($type eq 'any') || ($type eq 'all')) {
                   3590:         $typesref = ['active','previous','future'];
                   3591:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3592:         $typesref = [$type];
                   3593:     }
                   3594:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3595:                               $typesref,undef,[$cdom]);
                   3596:     my ($tmp) = keys(%roles);
                   3597:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3598:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3599:     if (@course_roles > 0) {
                   3600:         return 1;
                   3601:     }
                   3602:     return 0;
                   3603: }
                   3604: 
1.478     albertel 3605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3606: # input: action, courseID, current domain, intended
1.637     raeburn  3607: #        path to file, source of file, instruction to parse file for objects,
                   3608: #        ref to hash for embedded objects,
                   3609: #        ref to hash for codebase of java objects.
1.1095    raeburn  3610: #        reference to scalar to accommodate mime type determined
                   3611: #          from File::MMagic if $parser = parse.
1.637     raeburn  3612: #
1.485     raeburn  3613: # output: url to file (if action was uploaddoc), 
                   3614: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3615: #
1.478     albertel 3616: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3617: # course.
1.477     raeburn  3618: #
1.478     albertel 3619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3620: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3621: #          course's home server.
1.477     raeburn  3622: #
1.478     albertel 3623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3624: #          be copied from $source (current location) to 
                   3625: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3626: #         and will then be copied to
                   3627: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3628: #         course's home server.
1.485     raeburn  3629: #
1.481     raeburn  3630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3631: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3632: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3633: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3634: #         in course's home server.
1.637     raeburn  3635: #
1.477     raeburn  3636: 
                   3637: sub process_coursefile {
1.1095    raeburn  3638:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3639:         $mimetype)=@_;
1.477     raeburn  3640:     my $fetchresult;
1.638     albertel 3641:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3642:     if ($action eq 'propagate') {
1.638     albertel 3643:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3644: 			     $home);
1.481     raeburn  3645:     } else {
1.477     raeburn  3646:         my $fpath = '';
                   3647:         my $fname = $file;
1.478     albertel 3648:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3649:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3650:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3651:         if ($action eq 'copy') {
                   3652:             if ($source eq '') {
                   3653:                 $fetchresult = 'no source file';
                   3654:                 return $fetchresult;
                   3655:             } else {
                   3656:                 my $destination = $filepath.'/'.$fname;
                   3657:                 rename($source,$destination);
                   3658:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3659:                                  $home);
1.481     raeburn  3660:             }
                   3661:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3662:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3663:             print $fh $env{'form.'.$source};
1.481     raeburn  3664:             close($fh);
1.637     raeburn  3665:             if ($parser eq 'parse') {
1.1024    raeburn  3666:                 my $mm = new File::MMagic;
1.1095    raeburn  3667:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3668:                 if ($type eq 'text/html') {
1.1024    raeburn  3669:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3670:                     unless ($parse_result eq 'ok') {
                   3671:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3672:                     }
1.637     raeburn  3673:                 }
1.1095    raeburn  3674:                 if (ref($mimetype)) {
                   3675:                     $$mimetype = $type;
                   3676:                 } 
1.637     raeburn  3677:             }
1.477     raeburn  3678:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3679:                                  $home);
1.481     raeburn  3680:             if ($fetchresult eq 'ok') {
                   3681:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3682:             } else {
                   3683:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3684:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3685:                 return '/adm/notfound.html';
                   3686:             }
1.477     raeburn  3687:         }
                   3688:     }
1.485     raeburn  3689:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3690:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3691:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3692:     }
                   3693:     return $fetchresult;
                   3694: }
                   3695: 
1.637     raeburn  3696: sub build_filepath {
                   3697:     my ($fpath) = @_;
                   3698:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3699:     unless ($fpath eq '') {
                   3700:         my @parts=split('/',$fpath);
                   3701:         foreach my $part (@parts) {
                   3702:             $filepath.= '/'.$part;
                   3703:             if ((-e $filepath)!=1) {
                   3704:                 mkdir($filepath,0777);
                   3705:             }
                   3706:         }
                   3707:     }
                   3708:     return $filepath;
                   3709: }
                   3710: 
                   3711: sub store_edited_file {
1.638     albertel 3712:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3713:     my $file = $primary_url;
                   3714:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3715:     my $fpath = '';
                   3716:     my $fname = $file;
                   3717:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3718:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3719:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3720:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3721:     print $fh $content;
                   3722:     close($fh);
1.638     albertel 3723:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3724:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3725: 			  $home);
1.637     raeburn  3726:     if ($$fetchresult eq 'ok') {
                   3727:         return '/uploaded/'.$fpath.'/'.$fname;
                   3728:     } else {
1.638     albertel 3729:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3730: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3731:         return '/adm/notfound.html';
                   3732:     }
                   3733: }
                   3734: 
1.531     albertel 3735: sub clean_filename {
1.831     albertel 3736:     my ($fname,$args)=@_;
1.315     www      3737: # Replace Windows backslashes by forward slashes
1.257     www      3738:     $fname=~s/\\/\//g;
1.831     albertel 3739:     if (!$args->{'keep_path'}) {
                   3740:         # Get rid of everything but the actual filename
                   3741: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3742:     }
1.315     www      3743: # Replace spaces by underscores
                   3744:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3745: # Transliterate non-ascii text to ascii
                   3746:     my $lang = &Apache::lonlocal::current_language();
                   3747:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3748: # Replace all other weird characters by nothing
1.831     albertel 3749:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3750: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3751: # numbers
                   3752:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3753: # Replace three or more adjacent underscores with one for consistency
                   3754: # with loncfile::filename_check() so complete url can be extracted by
                   3755: # lonnet::decode_symb()
                   3756:     $fname=~s/_{3,}/_/g;
1.531     albertel 3757:     return $fname;
                   3758: }
1.1172.2.110  raeburn  3759: 
1.1051    raeburn  3760: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3761: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3762: # image with the same aspect ratio as the original, but with dimensions which do 
                   3763: # not exceed $resizewidth and $resizeheight.
                   3764:  
1.984     neumanie 3765: sub resizeImage {
1.1051    raeburn  3766:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3767:     my $ima = Image::Magick->new;
                   3768:     my $resized;
                   3769:     if (-e $img_path) {
                   3770:         $ima->Read($img_path);
                   3771:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3772:             my $width = $ima->Get('width');
                   3773:             my $height = $ima->Get('height');
                   3774:             if ($width > $resizewidth) {
                   3775: 	        my $factor = $width/$resizewidth;
                   3776:                 my $newheight = $height/$factor;
                   3777:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3778:                 $resized = 1;
                   3779:             }
                   3780:         }
                   3781:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3782:             my $width = $ima->Get('width');
                   3783:             my $height = $ima->Get('height');
                   3784:             if ($height > $resizeheight) {
                   3785:                 my $factor = $height/$resizeheight;
                   3786:                 my $newwidth = $width/$factor;
                   3787:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3788:                 $resized = 1;
                   3789:             }
                   3790:         }
                   3791:         if ($resized) {
                   3792:             $ima->Write($img_path);
                   3793:         }
                   3794:     }
                   3795:     return;
1.977     amueller 3796: }
                   3797: 
1.608     albertel 3798: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3799: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3800: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3801: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3802: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3803: #                   if 'coursedoc': upload to the current course
                   3804: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3805: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3806: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3807: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3808: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3809: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3810: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3811: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3812: #        $allfiles - reference to hash for embedded objects
                   3813: #        $codebase - reference to hash for codebase of java objects
                   3814: #        $desuname - username for permanent storage of uploaded file
                   3815: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3816: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3817: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3818: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3819: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3820: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3821: #                    from File::MMagic.
1.858     raeburn  3822: # 
1.686     albertel 3823: # output: url of file in userspace, or error: <message> 
                   3824: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3825: 
1.531     albertel 3826: sub userfileupload {
1.1090    raeburn  3827:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3828:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3829:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3830:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3831:     $fname=&clean_filename($fname);
1.1090    raeburn  3832:     # See if there is anything left
1.257     www      3833:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3834:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3835:     if ($fname =~ /^\./) {
                   3836:         my ($s,$usec) = &gettimeofday();
                   3837:         while (length($usec) < 6) {
                   3838:             $usec = '0'.$usec;
                   3839:         }
                   3840:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3841:     }
1.1090    raeburn  3842:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3843:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3844:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3845:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3846:         my $now = time;
1.1090    raeburn  3847:         my $filepath;
1.1095    raeburn  3848:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3849:              $filepath = 'tmp/helprequests/'.$now;
                   3850:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3851:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3852:                          '_'.$env{'user.domain'}.'/pending';
                   3853:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3854:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3855:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3856:                 $docudom = $destudom;
                   3857:             } else {
                   3858:                 $docudom = $env{'user.domain'};
                   3859:             }
1.1172.2.96  raeburn  3860:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3861:                 $docuname = $destuname;
                   3862:             } else {
                   3863:                 $docuname = $env{'user.name'};
                   3864:             }
                   3865:             if (exists($env{'form.group'})) {
                   3866:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3867:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3868:             }
                   3869:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3870:             if ($context eq 'canceloverwrite') {
                   3871:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3872:                 if (-e  $tempfile) {
                   3873:                     my @info = stat($tempfile);
                   3874:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3875:                         unlink($tempfile);
                   3876:                     }
                   3877:                 }
                   3878:                 return;
1.523     raeburn  3879:             }
                   3880:         }
1.1090    raeburn  3881:         # Create the directory if not present
1.741     raeburn  3882:         my @parts=split(/\//,$filepath);
                   3883:         my $fullpath = $perlvar{'lonDaemons'};
                   3884:         for (my $i=0;$i<@parts;$i++) {
                   3885:             $fullpath .= '/'.$parts[$i];
                   3886:             if ((-e $fullpath)!=1) {
                   3887:                 mkdir($fullpath,0777);
                   3888:             }
                   3889:         }
1.1172.2.96  raeburn  3890:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3891:         print $fh $env{'form.'.$formname};
                   3892:         close($fh);
1.1090    raeburn  3893:         if ($context eq 'existingfile') {
                   3894:             my @info = stat($fullpath.'/'.$fname);
                   3895:             return ($fullpath.'/'.$fname,$info[9]);
                   3896:         } else {
                   3897:             return $fullpath.'/'.$fname;
                   3898:         }
1.523     raeburn  3899:     }
1.995     raeburn  3900:     if ($subdir eq 'scantron') {
                   3901:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3902:     } else {
1.995     raeburn  3903:         $fname="$subdir/$fname";
                   3904:     }
1.1090    raeburn  3905:     if ($context eq 'coursedoc') {
1.638     albertel 3906: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3907: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3908:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3909:             return &finishuserfileupload($docuname,$docudom,
                   3910: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3911: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3912:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3913:         } else {
1.1172.2.21  raeburn  3914:             if ($env{'form.folder'}) {
                   3915:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3916:             }
1.638     albertel 3917:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3918: 				       $fname,$formname,$parser,
1.1095    raeburn  3919: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3920:         }
1.719     banghart 3921:     } elsif (defined($destuname)) {
                   3922:         my $docuname=$destuname;
                   3923:         my $docudom=$destudom;
1.860     raeburn  3924: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3925: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3926:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3927:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3928:     } else {
1.638     albertel 3929:         my $docuname=$env{'user.name'};
                   3930:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3931:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3932:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3933:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3934:         }
1.860     raeburn  3935: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3936: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3937:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3938:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3939:     }
1.271     www      3940: }
                   3941: 
                   3942: sub finishuserfileupload {
1.860     raeburn  3943:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3944:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3945:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3946:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3947:   
1.860     raeburn  3948:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3949:     $file=$fname;
                   3950:     if ($fname=~m|/|) {
                   3951:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3952: 	$path.=$fnamepath.'/';
                   3953:     }
1.259     www      3954:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3955:     my $count;
                   3956:     for ($count=4;$count<=$#parts;$count++) {
                   3957:         $filepath.="/$parts[$count]";
                   3958:         if ((-e $filepath)!=1) {
                   3959: 	    mkdir($filepath,0777);
                   3960:         }
                   3961:     }
1.984     neumanie 3962: 
1.258     www      3963: # Save the file
                   3964:     {
1.1172.2.96  raeburn  3965: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3966: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3967: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3968: 	    return '/adm/notfound.html';
                   3969: 	}
1.1090    raeburn  3970:         if ($context eq 'overwrite') {
1.1117    foxr     3971:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3972:             my $target = $filepath.'/'.$file;
                   3973:             if (-e $source) {
                   3974:                 my @info = stat($source);
                   3975:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3976:                     unless (&File::Copy::move($source,$target)) {
                   3977:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3978:                         return "Moving from $source failed";
                   3979:                     }
                   3980:                 } else {
                   3981:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3982:                 }
                   3983:             } else {
                   3984:                 return "Temporary file: $source missing";
                   3985:             }
                   3986:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3987: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3988: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3989: 	    return '/adm/notfound.html';
                   3990: 	}
1.570     albertel 3991: 	close(FH);
1.1051    raeburn  3992:         if ($resizewidth && $resizeheight) {
                   3993:             my $mm = new File::MMagic;
                   3994:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3995:             if ($mime_type =~ m{^image/}) {
                   3996: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3997:             }  
1.977     amueller 3998: 	}
1.258     www      3999:     }
1.1152    raeburn  4000:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4001:         if (ref($mimetype)) {
                   4002:             if ($$mimetype eq '') {
                   4003:                 my $mm = new File::MMagic;
                   4004:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4005:                 $$mimetype = $type;
                   4006:             }
                   4007:         }
                   4008:     }
1.1172.2.109  raeburn  4009:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4010:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4011:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4012:                                                        $allfiles,$codebase);
                   4013:             unless ($parse_result eq 'ok') {
                   4014:                 &logthis('Failed to parse '.$filepath.$file.
                   4015: 	   	         ' for embedded media: '.$parse_result); 
                   4016:             }
1.637     raeburn  4017:         }
1.1172.2.109  raeburn  4018:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4019:         my $format = $env{'form.scantron_format'};
                   4020:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4021:     }
1.860     raeburn  4022:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4023:         my $input = $filepath.'/'.$file;
                   4024:         my $output = $filepath.'/'.'tn-'.$file;
                   4025:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4026:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4027:         system({$args[0]} @args);
1.860     raeburn  4028:         if (-e $filepath.'/'.'tn-'.$file) {
                   4029:             $fetchthumb  = 1; 
                   4030:         }
                   4031:     }
1.858     raeburn  4032:  
1.259     www      4033: # Notify homeserver to grep it
                   4034: #
1.984     neumanie 4035:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4036:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4037:     if ($fetchresult eq 'ok') {
1.860     raeburn  4038:         if ($fetchthumb) {
                   4039:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4040:             if ($thumbresult ne 'ok') {
                   4041:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4042:                          $docuhome.': '.$thumbresult);
                   4043:             }
                   4044:         }
1.259     www      4045: #
1.258     www      4046: # Return the URL to it
1.494     albertel 4047:         return '/uploaded/'.$path.$file;
1.263     www      4048:     } else {
1.494     albertel 4049:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4050: 		 ': '.$fetchresult);
1.263     www      4051:         return '/adm/notfound.html';
1.858     raeburn  4052:     }
1.493     albertel 4053: }
                   4054: 
1.637     raeburn  4055: sub extract_embedded_items {
1.961     raeburn  4056:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4057:     my @state = ();
1.1164    raeburn  4058:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4059:     my %javafiles = (
                   4060:                       codebase => '',
                   4061:                       code => '',
                   4062:                       archive => ''
                   4063:                     );
                   4064:     my %mediafiles = (
                   4065:                       src => '',
                   4066:                       movie => '',
                   4067:                      );
1.648     raeburn  4068:     my $p;
                   4069:     if ($content) {
                   4070:         $p = HTML::LCParser->new($content);
                   4071:     } else {
1.961     raeburn  4072:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4073:     }
1.641     albertel 4074:     while (my $t=$p->get_token()) {
1.640     albertel 4075: 	if ($t->[0] eq 'S') {
                   4076: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4077: 	    push(@state, $tagname);
1.648     raeburn  4078:             if (lc($tagname) eq 'allow') {
                   4079:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4080:             }
1.640     albertel 4081: 	    if (lc($tagname) eq 'img') {
                   4082: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4083: 	    }
1.886     albertel 4084: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4085:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4086: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4087:                 }
1.886     albertel 4088: 	    }
1.645     raeburn  4089:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4090:                 my $src;
1.645     raeburn  4091:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4092:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4093:                 } else {
1.1164    raeburn  4094:                     if ($attr->{'src'} ne '') {
                   4095:                         $src = $attr->{'src'};
                   4096:                         &add_filetype($allfiles,$src,'src');
                   4097:                     }
                   4098:                 }
                   4099:                 my $text = $p->get_trimmed_text();
                   4100:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4101:                     my @swfargs = split(/,/,$1);
                   4102:                     foreach my $item (@swfargs) {
                   4103:                         $item =~ s/["']//g;
                   4104:                         $item =~ s/^\s+//;
                   4105:                         $item =~ s/\s+$//;
                   4106:                     }
                   4107:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4108:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4109:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4110:                         } else {
                   4111:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4112:                         }
                   4113:                     }
1.645     raeburn  4114:                 }
                   4115:             }
                   4116:             if (lc($tagname) eq 'link') {
                   4117:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4118:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4119:                 }
                   4120:             }
1.640     albertel 4121: 	    if (lc($tagname) eq 'object' ||
                   4122: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4123: 		foreach my $item (keys(%javafiles)) {
                   4124: 		    $javafiles{$item} = '';
                   4125: 		}
1.1164    raeburn  4126:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4127:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4128:                 }
1.640     albertel 4129: 	    }
                   4130: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4131: 		my $name = lc($attr->{'name'});
                   4132: 		foreach my $item (keys(%javafiles)) {
                   4133: 		    if ($name eq $item) {
                   4134: 			$javafiles{$item} = $attr->{'value'};
                   4135: 			last;
                   4136: 		    }
                   4137: 		}
1.1164    raeburn  4138:                 my $pathfrom;
1.640     albertel 4139: 		foreach my $item (keys(%mediafiles)) {
                   4140: 		    if ($name eq $item) {
1.1164    raeburn  4141:                         $pathfrom = $attr->{'value'};
                   4142:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4143: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4144: 			last;
                   4145: 		    }
                   4146: 		}
1.1164    raeburn  4147:                 if ($name eq 'flashvars') {
                   4148:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4149:                 }
                   4150:                 if ($pathfrom ne '') {
                   4151:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4152:                                          $pathfrom);
                   4153:                 }
1.640     albertel 4154: 	    }
                   4155: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4156: 		foreach my $item (keys(%javafiles)) {
                   4157: 		    if ($attr->{$item}) {
                   4158: 			$javafiles{$item} = $attr->{$item};
                   4159: 			last;
                   4160: 		    }
                   4161: 		}
                   4162: 		foreach my $item (keys(%mediafiles)) {
                   4163: 		    if ($attr->{$item}) {
                   4164: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4165: 			last;
                   4166: 		    }
                   4167: 		}
1.1164    raeburn  4168:                 if (lc($tagname) eq 'embed') {
                   4169:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4170:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4171:                                              $attr->{'src'});
                   4172:                     }
                   4173:                 }
1.640     albertel 4174: 	    }
1.1172.2.35  raeburn  4175:             if (lc($tagname) eq 'iframe') {
                   4176:                 my $src = $attr->{'src'} ;
                   4177:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4178:                     &add_filetype($allfiles,$src,'src');
                   4179:                 } elsif ($src =~ m{^/}) {
                   4180:                     if ($env{'request.course.id'}) {
                   4181:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4182:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4183:                         my $url = &hreflocation('',$fullpath);
                   4184:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4185:                             my $relpath = $1;
                   4186:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4187:                                 &add_filetype($allfiles,$1,'src');
                   4188:                             }
                   4189:                         }
                   4190:                     }
                   4191:                 }
                   4192:             }
1.1164    raeburn  4193:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4194:                 pop(@state);
1.1164    raeburn  4195:             }
1.640     albertel 4196: 	} elsif ($t->[0] eq 'E') {
                   4197: 	    my ($tagname) = ($t->[1]);
                   4198: 	    if ($javafiles{'codebase'} ne '') {
                   4199: 		$javafiles{'codebase'} .= '/';
                   4200: 	    }  
                   4201: 	    if (lc($tagname) eq 'applet' ||
                   4202: 		lc($tagname) eq 'object' ||
                   4203: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4204: 		) {
                   4205: 		foreach my $item (keys(%javafiles)) {
                   4206: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4207: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4208: 			&add_filetype($allfiles,$file,$item);
                   4209: 		    }
                   4210: 		}
                   4211: 	    } 
                   4212: 	    pop @state;
                   4213: 	}
                   4214:     }
1.1164    raeburn  4215:     foreach my $id (sort(keys(%flashvars))) {
                   4216:         if ($shockwave{$id} ne '') {
                   4217:             my @pairs = split(/\&/,$flashvars{$id});
                   4218:             foreach my $pair (@pairs) {
                   4219:                 my ($key,$value) = split(/\=/,$pair);
                   4220:                 if ($key eq 'thumb') {
                   4221:                     &add_filetype($allfiles,$value,$key);
                   4222:                 } elsif ($key eq 'content') {
                   4223:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4224:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4225:                     if ($ext ne '') {
                   4226:                         &add_filetype($allfiles,$path.$value,$ext);
                   4227:                     }
                   4228:                 }
                   4229:             }
                   4230:         }
                   4231:     }
1.637     raeburn  4232:     return 'ok';
                   4233: }
                   4234: 
1.639     albertel 4235: sub add_filetype {
                   4236:     my ($allfiles,$file,$type)=@_;
                   4237:     if (exists($allfiles->{$file})) {
                   4238: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4239: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4240: 	}
                   4241:     } else {
                   4242: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4243:     }
                   4244: }
                   4245: 
1.1164    raeburn  4246: sub embedded_dependency {
                   4247:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4248:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4249:         if (($identifier ne '') &&
                   4250:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4251:             ($pathfrom ne '')) {
                   4252:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4253:             foreach my $dep (@{$related->{$identifier}}) {
                   4254:                 &add_filetype($allfiles,$path.$dep,'object');
                   4255:             }
                   4256:         }
                   4257:     }
                   4258:     return;
                   4259: }
                   4260: 
1.1172.2.109  raeburn  4261: sub bubblesheet_converter {
                   4262:     my ($cdom,$fullpath,$config,$format) = @_;
                   4263:     if ((&domain($cdom) ne '') &&
                   4264:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4265:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4266:         my (%csvcols,%csvoptions);
                   4267:         if (ref($config->{'fields'}) eq 'HASH') {
                   4268:             %csvcols = %{$config->{'fields'}};
                   4269:         }
                   4270:         if (ref($config->{'options'}) eq 'HASH') {
                   4271:             %csvoptions = %{$config->{'options'}};
                   4272:         }
                   4273:         my %csvbynum = reverse(%csvcols);
                   4274:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4275:         if (keys(%scantronconf)) {
                   4276:             my %bynum = (
                   4277:                           $scantronconf{CODEstart} => 'CODEstart',
                   4278:                           $scantronconf{IDstart}   => 'IDstart',
                   4279:                           $scantronconf{PaperID}   => 'PaperID',
                   4280:                           $scantronconf{FirstName} => 'FirstName',
                   4281:                           $scantronconf{LastName}  => 'LastName',
                   4282:                           $scantronconf{Qstart}    => 'Qstart',
                   4283:                         );
                   4284:             my @ordered;
                   4285:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4286:                 push(@ordered,$bynum{$item});
                   4287:             }
                   4288:             my %mapstart = (
                   4289:                               CODEstart => 'CODE',
                   4290:                               IDstart   => 'ID',
                   4291:                               PaperID   => 'PaperID',
                   4292:                               FirstName => 'FirstName',
                   4293:                               LastName  => 'LastName',
                   4294:                               Qstart    => 'FirstQuestion',
                   4295:                            );
                   4296:             my %maplength = (
                   4297:                               CODEstart => 'CODElength',
                   4298:                               IDstart   => 'IDlength',
                   4299:                               PaperID   => 'PaperIDlength',
                   4300:                               FirstName => 'FirstNamelength',
                   4301:                               LastName  => 'LastNamelength',
                   4302:             );
                   4303:             if (open(my $fh,'<',$fullpath)) {
                   4304:                 my $output;
                   4305:                 my %lettdig = &letter_to_digits();
                   4306:                 my %diglett = reverse(%lettdig);
                   4307:                 my $numletts = scalar(keys(%lettdig));
                   4308:                 my $num = 0;
                   4309:                 while (my $line=<$fh>) {
                   4310:                     $num ++;
                   4311:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4312:                     $line =~ s{[\r\n]+$}{};
                   4313:                     my %found;
1.1172.2.143! raeburn  4314:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4315:                     my ($qstart,$record);
                   4316:                     for (my $i=0; $i<@values; $i++) {
                   4317:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4318:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4319:                             if ($values[$i] eq '') {
                   4320:                                 $values[$i] = $scantronconf{'Qoff'};
                   4321:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4322:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4323:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4324:                                 }
                   4325:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4326:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4327:                                     $values[$i] = $diglett{$values[$i]};
                   4328:                                 }
                   4329:                             } else {
                   4330:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4331:                                     my $digit;
                   4332:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4333:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4334:                                         if ($values[$i] eq 'J') {
                   4335:                                             $digit += $numletts;
                   4336:                                         }
                   4337:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4338:                                         $digit = $values[$i]-1;
                   4339:                                         if ($values[$i] eq '0') {
                   4340:                                             $digit += $numletts;
                   4341:                                         }
                   4342:                                     }
                   4343:                                     my $qval='';
                   4344:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4345:                                         if ($j == $digit) {
                   4346:                                             $qval .= $scantronconf{'Qon'};
                   4347:                                         } else {
                   4348:                                             $qval .= $scantronconf{'Qoff'};
                   4349:                                         }
                   4350:                                     }
                   4351:                                     $values[$i] = $qval;
                   4352:                                 }
                   4353:                             }
                   4354:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4355:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4356:                             }
                   4357:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4358:                             if ($numblank > 0) {
                   4359:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4360:                             }
                   4361:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4362:                                 $qstart = $i;
                   4363:                                 $found{$csvbynum{$i}} = $values[$i];
                   4364:                             } else {
                   4365:                                 $found{'FirstQuestion'} .= $values[$i];
                   4366:                             }
                   4367:                         } elsif (exists($csvbynum{$i})) {
                   4368:                             if ($csvoptions{'rem'}) {
                   4369:                                 $values[$i] =~ s/^\s+//;
                   4370:                             }
                   4371:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4372:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4373:                                     $values[$i] = '0'.$values[$i];
                   4374:                                 }
                   4375:                             }
                   4376:                             $found{$csvbynum{$i}} = $values[$i];
                   4377:                         }
                   4378:                     }
                   4379:                     foreach my $item (@ordered) {
                   4380:                         my $currlength = 1+length($record);
                   4381:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4382:                         if ($numspaces > 0) {
                   4383:                             $record .= (' ' x $numspaces);
                   4384:                         }
                   4385:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4386:                             unless ($item eq 'Qstart') {
                   4387:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4388:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4389:                                 }
                   4390:                             }
                   4391:                             $record .= $found{$mapstart{$item}};
                   4392:                         }
                   4393:                     }
                   4394:                     $output .= "$record\n";
                   4395:                 }
                   4396:                 close($fh);
                   4397:                 if ($output) {
                   4398:                     if (open(my $fh,'>',$fullpath)) {
                   4399:                         print $fh $output;
                   4400:                         close($fh);
                   4401:                     }
                   4402:                 }
                   4403:             }
                   4404:         }
                   4405:         return;
                   4406:     }
                   4407: }
                   4408: 
                   4409: sub letter_to_digits {
                   4410:     my %lettdig = (
                   4411:                     A => 1,
                   4412:                     B => 2,
                   4413:                     C => 3,
                   4414:                     D => 4,
                   4415:                     E => 5,
                   4416:                     F => 6,
                   4417:                     G => 7,
                   4418:                     H => 8,
                   4419:                     I => 9,
                   4420:                     J => 0,
                   4421:                   );
                   4422:     return %lettdig;
                   4423: }
                   4424: 
                   4425: sub get_scantron_config {
                   4426:     my ($which,$cdom) = @_;
                   4427:     my @lines = &get_scantronformat_file($cdom);
                   4428:     my %config;
                   4429:     #FIXME probably should move to XML it has already gotten a bit much now
                   4430:     foreach my $line (@lines) {
                   4431:         my ($name,$descrip)=split(/:/,$line);
                   4432:         if ($name ne $which ) { next; }
                   4433:         chomp($line);
                   4434:         my @config=split(/:/,$line);
                   4435:         $config{'name'}=$config[0];
                   4436:         $config{'description'}=$config[1];
                   4437:         $config{'CODElocation'}=$config[2];
                   4438:         $config{'CODEstart'}=$config[3];
                   4439:         $config{'CODElength'}=$config[4];
                   4440:         $config{'IDstart'}=$config[5];
                   4441:         $config{'IDlength'}=$config[6];
                   4442:         $config{'Qstart'}=$config[7];
                   4443:         $config{'Qlength'}=$config[8];
                   4444:         $config{'Qoff'}=$config[9];
                   4445:         $config{'Qon'}=$config[10];
                   4446:         $config{'PaperID'}=$config[11];
                   4447:         $config{'PaperIDlength'}=$config[12];
                   4448:         $config{'FirstName'}=$config[13];
                   4449:         $config{'FirstNamelength'}=$config[14];
                   4450:         $config{'LastName'}=$config[15];
                   4451:         $config{'LastNamelength'}=$config[16];
                   4452:         $config{'BubblesPerRow'}=$config[17];
                   4453:         last;
                   4454:     }
                   4455:     return %config;
                   4456: }
                   4457: 
                   4458: sub get_scantronformat_file {
                   4459:     my ($cdom) = @_;
                   4460:     if ($cdom eq '') {
                   4461:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4462:     }
                   4463:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4464:     my $gottab = 0;
                   4465:     my @lines;
                   4466:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4467:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4468:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4469:             if ($formatfile ne '-1') {
                   4470:                 @lines = split("\n",$formatfile,-1);
                   4471:                 $gottab = 1;
                   4472:             }
                   4473:         }
                   4474:     }
                   4475:     if (!$gottab) {
                   4476:         my $confname = $cdom.'-domainconfig';
                   4477:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4478:         my $formatfile = &getfile($default);
                   4479:         if ($formatfile ne '-1') {
                   4480:             @lines = split("\n",$formatfile,-1);
                   4481:             $gottab = 1;
                   4482:         }
                   4483:     }
                   4484:     if (!$gottab) {
                   4485:         my @domains = &current_machine_domains();
                   4486:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4487:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4488:                 @lines = <$fh>;
                   4489:                 close($fh);
                   4490:             }
                   4491:         } else {
                   4492:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4493:                 @lines = <$fh>;
                   4494:                 close($fh);
                   4495:             }
                   4496:         }
                   4497:     }
                   4498:     return @lines;
                   4499: }
                   4500: 
1.493     albertel 4501: sub removeuploadedurl {
1.984     neumanie 4502:     my ($url)=@_;	
                   4503:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4504:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4505: }
                   4506: 
                   4507: sub removeuserfile {
                   4508:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4509:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4510:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4511:     if ($result eq 'ok') {	
1.798     raeburn  4512:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4513:             my $metafile = $fname.'.meta';
                   4514:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4515: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4516:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4517:             my $sqlresult = 
1.823     albertel 4518:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4519:                                         'portfolio_metadata',$group,
                   4520:                                         'delete');
1.798     raeburn  4521:         }
                   4522:     }
                   4523:     return $result;
1.257     www      4524: }
1.15      www      4525: 
1.530     albertel 4526: sub mkdiruserfile {
                   4527:     my ($docuname,$docudom,$dir)=@_;
                   4528:     my $home=&homeserver($docuname,$docudom);
                   4529:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4530: }
                   4531: 
1.531     albertel 4532: sub renameuserfile {
                   4533:     my ($docuname,$docudom,$old,$new)=@_;
                   4534:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4535:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4536:                         &escape("$old").':'.&escape("$new"),$home);
                   4537:     if ($result eq 'ok') {
                   4538:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4539:             my $oldmeta = $old.'.meta';
                   4540:             my $newmeta = $new.'.meta';
                   4541:             my $metaresult = 
                   4542:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4543: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4544:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4545:             my $sqlresult = 
1.823     albertel 4546:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4547:                                         'portfolio_metadata',$group,
                   4548:                                         'delete');
1.798     raeburn  4549:         }
                   4550:     }
                   4551:     return $result;
1.531     albertel 4552: }
                   4553: 
1.14      www      4554: # ------------------------------------------------------------------------- Log
                   4555: 
                   4556: sub log {
                   4557:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4558:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4559: }
                   4560: 
                   4561: # ------------------------------------------------------------------ Course Log
1.352     www      4562: #
                   4563: # This routine flushes several buffers of non-mission-critical nature
                   4564: #
1.157     www      4565: 
                   4566: sub flushcourselogs {
1.352     www      4567:     &logthis('Flushing log buffers');
                   4568: #
                   4569: # course logs
                   4570: # This is a log of all transactions in a course, which can be used
                   4571: # for data mining purposes
                   4572: #
                   4573: # It also collects the courseid database, which lists last transaction
                   4574: # times and course titles for all courseids
                   4575: #
                   4576:     my %courseidbuffer=();
1.921     raeburn  4577:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4578:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4579: 		          &escape($courselogs{$crsid}),
                   4580: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4581: 	    delete $courselogs{$crsid};
                   4582:         } else {
                   4583:             &logthis('Failed to flush log buffer for '.$crsid);
                   4584:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4585:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4586:                         " exceeded maximum size, deleting.</font>");
                   4587:                delete $courselogs{$crsid};
                   4588:             }
1.352     www      4589:         }
1.920     raeburn  4590:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4591:             'description' => $coursedescrbuf{$crsid},
                   4592:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4593:             'type'        => $coursetypebuf{$crsid},
                   4594:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4595:         };
1.191     harris41 4596:     }
1.352     www      4597: #
                   4598: # Write course id database (reverse lookup) to homeserver of courses 
                   4599: # Is used in pickcourse
                   4600: #
1.840     albertel 4601:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4602:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4603:                                     $courseidbuffer{$crs_home},
                   4604:                                     $crs_home,'timeonly');
1.352     www      4605:     }
                   4606: #
                   4607: # File accesses
                   4608: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4609: #
1.449     matthew  4610:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4611:         if ($entry =~ /___count$/) {
                   4612:             my ($dom,$name);
1.807     albertel 4613:             ($dom,$name,undef)=
1.811     albertel 4614: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4615:             if (! defined($dom) || $dom eq '' || 
                   4616:                 ! defined($name) || $name eq '') {
1.620     albertel 4617:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4618: #
                   4619: # FIXME 11/29/2021
                   4620: # Typo in rev. 1.458 (2003/12/09)??
                   4621: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4622: #
                   4623: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4624: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4625: # in a nohist_accesscount.db file for the user rather than the course.
                   4626: #
                   4627: # That said there is a lot of noise in the data being stored.
                   4628: # So counts for prtspool/  and adm/ etc. are recorded.
                   4629: #
                   4630: # A review of which items ending '___count' are written to %accesshash should likely be
                   4631: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4632: #
                   4633: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4634: # accesses for things which are not published resources, regardless of course, and
                   4635: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4636: # anyone in the course for things which are not published resources.
                   4637: #
                   4638: # For an author, nohist_accesscount.db ends up having records for other items
                   4639: # mixed up with the legitimate access counts for the author's published resources.
                   4640: #
1.620     albertel 4641:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4642:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4643:             }
1.450     matthew  4644:             my $value = $accesshash{$entry};
                   4645:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4646:             my %temphash=($url => $value);
1.449     matthew  4647:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4648:             if ($result eq 'ok') {
                   4649:                 delete $accesshash{$entry};
                   4650:             }
                   4651:         } else {
1.811     albertel 4652:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4653:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4654:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4655:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4656:                 delete $accesshash{$entry};
                   4657:             }
1.185     www      4658:         }
1.191     harris41 4659:     }
1.352     www      4660: #
                   4661: # Roles
                   4662: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4663: #
1.800     albertel 4664:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4665:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4666: 	    split(/\:/,$entry);
                   4667:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4668:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4669:                 $rudom,$runame) eq 'ok') {
                   4670: 	    delete $userrolehash{$entry};
                   4671:         }
                   4672:     }
1.662     raeburn  4673: #
1.1172.2.90  raeburn  4674: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4675: #
                   4676:     my %domrolebuffer = ();
1.1000    raeburn  4677:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4678:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4679:         if ($domrolebuffer{$rudom}) {
                   4680:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4681:                       '='.&escape($domainrolehash{$entry});
                   4682:         } else {
                   4683:             $domrolebuffer{$rudom}.=&escape($entry).
                   4684:                       '='.&escape($domainrolehash{$entry});
                   4685:         }
                   4686:         delete $domainrolehash{$entry};
                   4687:     }
                   4688:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4689:         my %servers;
                   4690:         if (defined(&domain($dom,'primary'))) {
                   4691:             my $primary=&domain($dom,'primary');
                   4692:             my $hostname=&hostname($primary);
                   4693:             $servers{$primary} = $hostname;
                   4694:         } else {
                   4695:             %servers = &get_servers($dom,'library');
                   4696:         }
1.841     albertel 4697: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4698: 	    if (&reply('domroleput:'.$dom.':'.
                   4699: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4700: 	        last;
                   4701: 	    } else {
1.841     albertel 4702: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4703: 	    }
1.662     raeburn  4704:         }
                   4705:     }
1.186     www      4706:     $dumpcount++;
1.157     www      4707: }
                   4708: 
                   4709: sub courselog {
                   4710:     my $what=shift;
1.158     www      4711:     $what=time.':'.$what;
1.620     albertel 4712:     unless ($env{'request.course.id'}) { return ''; }
                   4713:     $coursedombuf{$env{'request.course.id'}}=
                   4714:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4715:     $coursenumbuf{$env{'request.course.id'}}=
                   4716:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4717:     $coursehombuf{$env{'request.course.id'}}=
                   4718:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4719:     $coursedescrbuf{$env{'request.course.id'}}=
                   4720:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4721:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4722:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4723:     $courseownerbuf{$env{'request.course.id'}}=
                   4724:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4725:     $coursetypebuf{$env{'request.course.id'}}=
                   4726:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4727:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4728: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4729:     } else {
1.620     albertel 4730: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4731:     }
1.620     albertel 4732:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4733: 	&flushcourselogs();
                   4734:     }
1.158     www      4735: }
                   4736: 
                   4737: sub courseacclog {
                   4738:     my $fnsymb=shift;
1.620     albertel 4739:     unless ($env{'request.course.id'}) { return ''; }
                   4740:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4741:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4742:         $what.=':POST';
1.583     matthew  4743:         # FIXME: Probably ought to escape things....
1.800     albertel 4744: 	foreach my $key (keys(%env)) {
                   4745:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4746:                 my $formitem = $1;
                   4747:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4748:                     $what.=':'.$formitem.'='.$env{$key};
                   4749:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4750:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4751:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4752:                     } else {
                   4753:                         $what.=':'.$formitem.'='.$env{$key};
                   4754:                     }
1.975     raeburn  4755:                 }
1.158     www      4756:             }
1.191     harris41 4757:         }
1.583     matthew  4758:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4759:         # FIXME: We should not be depending on a form parameter that someone
                   4760:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4761:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4762:             $what.= ':POST';
                   4763:             # FIXME: Probably ought to escape things....
                   4764:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4765:                                  'crsdiscuss') {
1.620     albertel 4766:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4767:             }
                   4768:         }
1.158     www      4769:     }
                   4770:     &courselog($what);
1.149     www      4771: }
                   4772: 
1.185     www      4773: sub countacc {
                   4774:     my $url=&declutter(shift);
1.458     matthew  4775:     return if (! defined($url) || $url eq '');
1.620     albertel 4776:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4777: #
                   4778: # Mark that this url was used in this course
                   4779: #
1.620     albertel 4780:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4781: #
                   4782: # Increase the access count for this resource in this child process
                   4783: #
1.281     www      4784:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4785:     $accesshash{$key}++;
1.185     www      4786: }
1.349     www      4787: 
1.361     www      4788: sub linklog {
                   4789:     my ($from,$to)=@_;
                   4790:     $from=&declutter($from);
                   4791:     $to=&declutter($to);
                   4792:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4793:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4794: }
1.1160    www      4795: 
                   4796: sub statslog {
                   4797:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4798:     if ($users<2) { return; }
                   4799:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4800:             'course'       => $env{'request.course.id'},
                   4801:             'sections'     => '"all"',
                   4802:             'num_students' => $users,
                   4803:             'part'         => $part,
                   4804:             'symb'         => $symb,
                   4805:             'mean_tries'   => $av_attempts,
                   4806:             'deg_of_diff'  => $degdiff});
                   4807:     foreach my $key (keys(%dynstore)) {
                   4808:         $accesshash{$key}=$dynstore{$key};
                   4809:     }
                   4810: }
1.361     www      4811:   
1.349     www      4812: sub userrolelog {
                   4813:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4814:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4815:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4816:        $userrolehash
                   4817:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4818:                     =$tend.':'.$tstart;
1.662     raeburn  4819:     }
1.1169    droeschl 4820:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4821:        $userrolehash
                   4822:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4823:                     =$tend.':'.$tstart;
                   4824:     }
1.1172.2.90  raeburn  4825:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4826:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4827:        $domainrolehash
                   4828:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4829:                     = $tend.':'.$tstart;
                   4830:     }
1.351     www      4831: }
                   4832: 
1.957     raeburn  4833: sub courserolelog {
                   4834:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4835:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4836:         my $cdom = $1;
                   4837:         my $cnum = $2;
                   4838:         my $sec = $3;
                   4839:         my $namespace = 'rolelog';
                   4840:         my %storehash = (
                   4841:                            role    => $trole,
                   4842:                            start   => $tstart,
                   4843:                            end     => $tend,
                   4844:                            selfenroll => $selfenroll,
                   4845:                            context    => $context,
                   4846:                         );
                   4847:         if ($trole eq 'gr') {
                   4848:             $namespace = 'groupslog';
                   4849:             $storehash{'group'} = $sec;
                   4850:         } else {
                   4851:             $storehash{'section'} = $sec;
                   4852:         }
                   4853:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4854:                    $domain,$cnum,$cdom);
                   4855:         if (($trole ne 'st') || ($sec ne '')) {
                   4856:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4857:         }
                   4858:     }
                   4859:     return;
                   4860: }
                   4861: 
1.1172.2.9  raeburn  4862: sub domainrolelog {
                   4863:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4864:     if ($area =~ m{^/($match_domain)/$}) {
                   4865:         my $cdom = $1;
                   4866:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4867:         my $namespace = 'rolelog';
                   4868:         my %storehash = (
                   4869:                            role    => $trole,
                   4870:                            start   => $tstart,
                   4871:                            end     => $tend,
                   4872:                            context => $context,
                   4873:                         );
                   4874:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4875:                    $domain,$domconfiguser,$cdom);
                   4876:     }
                   4877:     return;
                   4878: 
                   4879: }
                   4880: 
                   4881: sub coauthorrolelog {
                   4882:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4883:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4884:         my $audom = $1;
                   4885:         my $auname = $2;
                   4886:         my $namespace = 'rolelog';
                   4887:         my %storehash = (
                   4888:                            role    => $trole,
                   4889:                            start   => $tstart,
                   4890:                            end     => $tend,
                   4891:                            context => $context,
                   4892:                         );
                   4893:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4894:                    $domain,$auname,$audom);
                   4895:     }
                   4896:     return;
                   4897: }
                   4898: 
1.351     www      4899: sub get_course_adv_roles {
1.948     raeburn  4900:     my ($cid,$codes) = @_;
1.620     albertel 4901:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4902:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4903:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4904:     my %nothide=();
1.800     albertel 4905:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4906:         if ($user !~ /:/) {
                   4907: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4908:         } else {
                   4909:             $nothide{$user}=1;
                   4910:         }
1.470     www      4911:     }
1.1172.2.23  raeburn  4912:     my @possdoms = ($coursehash{'domain'});
                   4913:     if ($coursehash{'checkforpriv'}) {
                   4914:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4915:     }
1.351     www      4916:     my %returnhash=();
                   4917:     my %dumphash=
                   4918:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4919:     my $now=time;
1.997     raeburn  4920:     my %privileged;
1.1000    raeburn  4921:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4922: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4923:         if (($tstart) && ($tstart<0)) { next; }
                   4924:         if (($tend) && ($tend<$now)) { next; }
                   4925:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4926:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4927: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4928:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4929:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4930: 	if ($role eq 'cr') { next; }
1.948     raeburn  4931:         if ($codes) {
                   4932:             if ($section) { $role .= ':'.$section; }
                   4933:             if ($returnhash{$role}) {
                   4934:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4935:             } else {
                   4936:                 $returnhash{$role}=$username.':'.$domain;
                   4937:             }
1.351     www      4938:         } else {
1.988     raeburn  4939:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4940:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4941:             if ($returnhash{$key}) {
                   4942: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4943:             } else {
                   4944:                 $returnhash{$key}=$username.':'.$domain;
                   4945:             }
1.351     www      4946:         }
1.948     raeburn  4947:     }
1.400     www      4948:     return %returnhash;
                   4949: }
                   4950: 
                   4951: sub get_my_roles {
1.937     raeburn  4952:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4953:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4954:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4955:     my (%dumphash,%nothide);
1.1086    raeburn  4956:     if ($context eq 'userroles') {
1.1166    raeburn  4957:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4958:     } else {
1.1172.2.23  raeburn  4959:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4960:         if ($hidepriv) {
                   4961:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4962:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4963:                 if ($user !~ /:/) {
                   4964:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4965:                 } else {
                   4966:                     $nothide{$user} = 1;
                   4967:                 }
                   4968:             }
                   4969:         }
1.858     raeburn  4970:     }
1.400     www      4971:     my %returnhash=();
                   4972:     my $now=time;
1.999     raeburn  4973:     my %privileged;
1.800     albertel 4974:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4975:         my ($role,$tend,$tstart);
                   4976:         if ($context eq 'userroles') {
1.1149    raeburn  4977:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4978: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4979:         } else {
                   4980:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4981:         }
1.400     www      4982:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4983:         my $status = 'active';
1.939     raeburn  4984:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4985:             $status = 'previous';
                   4986:         } 
                   4987:         if (($tstart) && ($now<$tstart)) {
                   4988:             $status = 'future';
                   4989:         }
                   4990:         if (ref($types) eq 'ARRAY') {
                   4991:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4992:                 next;
                   4993:             } 
                   4994:         } else {
                   4995:             if ($status ne 'active') {
                   4996:                 next;
                   4997:             }
                   4998:         }
1.867     raeburn  4999:         my ($rolecode,$username,$domain,$section,$area);
                   5000:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5001:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5002:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5003:         } else {
                   5004:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5005:         }
1.832     raeburn  5006:         if (ref($roledoms) eq 'ARRAY') {
                   5007:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5008:                 next;
                   5009:             }
                   5010:         }
                   5011:         if (ref($roles) eq 'ARRAY') {
                   5012:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5013:                 if ($role =~ /^cr\//) {
                   5014:                     if (!grep(/^cr$/,@{$roles})) {
                   5015:                         next;
                   5016:                     }
1.1104    raeburn  5017:                 } elsif ($role =~ /^gr\//) {
                   5018:                     if (!grep(/^gr$/,@{$roles})) {
                   5019:                         next;
                   5020:                     }
1.922     raeburn  5021:                 } else {
                   5022:                     next;
                   5023:                 }
1.832     raeburn  5024:             }
1.867     raeburn  5025:         }
1.937     raeburn  5026:         if ($hidepriv) {
1.1172.2.23  raeburn  5027:             my @privroles = ('dc','su');
1.999     raeburn  5028:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5029:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5030:             } else {
1.1172.2.23  raeburn  5031:                 my $possdoms = [$domain];
                   5032:                 if (ref($roledoms) eq 'ARRAY') {
                   5033:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5034:                 }
1.1172.2.23  raeburn  5035:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5036:                     if (!$nothide{$username.':'.$domain}) {
                   5037:                         next;
                   5038:                     }
                   5039:                 }
1.937     raeburn  5040:             }
                   5041:         }
1.933     raeburn  5042:         if ($withsec) {
                   5043:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5044:                 $tstart.':'.$tend;
                   5045:         } else {
                   5046:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5047:         }
1.832     raeburn  5048:     }
1.373     www      5049:     return %returnhash;
1.399     www      5050: }
                   5051: 
1.1172.2.89  raeburn  5052: sub get_all_adhocroles {
                   5053:     my ($dom) = @_;
                   5054:     my @roles_by_num = ();
                   5055:     my %domdefaults = &get_domain_defaults($dom);
                   5056:     my (%description,%access_in_dom,%access_info);
                   5057:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5058:         my $count = 0;
                   5059:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5060:         my %ordered;
                   5061:         foreach my $role (sort(keys(%domcurrent))) {
                   5062:             my ($order,$desc,$access_in_dom);
                   5063:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5064:                 $order = $domcurrent{$role}{'order'};
                   5065:                 $desc = $domcurrent{$role}{'desc'};
                   5066:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5067:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5068:             }
                   5069:             if ($order eq '') {
                   5070:                 $order = $count;
                   5071:             }
                   5072:             $ordered{$order} = $role;
                   5073:             if ($desc ne '') {
                   5074:                 $description{$role} = $desc;
                   5075:             } else {
                   5076:                 $description{$role}= $role;
                   5077:             }
                   5078:             $count++;
                   5079:         }
                   5080:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5081:             push(@roles_by_num,$ordered{$item});
                   5082:         }
                   5083:     }
                   5084:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5085: }
                   5086: 
                   5087: sub get_my_adhocroles {
                   5088:     my ($cid,$checkreg) = @_;
                   5089:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5090:     if ($env{'request.course.id'} eq $cid) {
                   5091:         $cdom = $env{'course.'.$cid.'.domain'};
                   5092:         $cnum = $env{'course.'.$cid.'.num'};
                   5093:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5094:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5095:         $cdom = $1;
                   5096:         $cnum = $2;
                   5097:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5098:                                      $cdom,$cnum);
                   5099:     }
                   5100:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5101:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5102:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5103:         if ($rosterhash{$user} ne '') {
                   5104:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5105:             return ([],{}) if ($type eq 'auto');
                   5106:         }
                   5107:     }
                   5108:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5109:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5110:             my $then=$env{'user.login.time'};
                   5111:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5112:             if (!$update) {
                   5113:                 $update = $then;
                   5114:             }
                   5115:             my @liveroles;
                   5116:             foreach my $role ('dh','da') {
                   5117:                 if ($env{"user.role.$role./$cdom/"}) {
                   5118:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5119:                     my $limit = $update;
                   5120:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5121:                         $limit = $then;
                   5122:                     }
                   5123:                     my $activerole = 1;
                   5124:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5125:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5126:                     if ($activerole) {
                   5127:                         push(@liveroles,$role);
                   5128:                     }
                   5129:                 }
                   5130:             }
                   5131:             if (@liveroles) {
1.1172.2.89  raeburn  5132:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5133:                     my ($accessref,$accessinfo,%access_in_dom);
                   5134:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5135:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5136:                         if (@{$roles_by_num}) {
                   5137:                             my %settings;
                   5138:                             if ($env{'request.course.id'} eq $cid) {
                   5139:                                 foreach my $envkey (keys(%env)) {
                   5140:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5141:                                         $settings{$1} = $env{$envkey};
                   5142:                                     }
                   5143:                                 }
                   5144:                             } else {
                   5145:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5146:                             }
                   5147:                             my %setincrs;
                   5148:                             if ($settings{'internal.adhocaccess'}) {
                   5149:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5150:                             }
                   5151:                             my @statuses;
                   5152:                             if ($env{'environment.inststatus'}) {
                   5153:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5154:                             }
                   5155:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5156:                             if (ref($accessref) eq 'HASH') {
                   5157:                                 %access_in_dom = %{$accessref};
                   5158:                             }
                   5159:                             foreach my $role (@{$roles_by_num}) {
                   5160:                                 my ($curraccess,@okstatus,@personnel);
                   5161:                                 if ($setincrs{$role}) {
                   5162:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5163:                                     if ($curraccess eq 'status') {
                   5164:                                         @okstatus = split(/\&/,$rest);
                   5165:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5166:                                         @personnel = split(/\&/,$rest);
                   5167:                                     }
                   5168:                                 } else {
                   5169:                                     $curraccess = $access_in_dom{$role};
                   5170:                                     if (ref($accessinfo) eq 'HASH') {
                   5171:                                         if ($curraccess eq 'status') {
                   5172:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5173:                                                 @okstatus = @{$accessinfo->{$role}};
                   5174:                                             }
                   5175:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5176:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5177:                                                 @personnel = @{$accessinfo->{$role}};
                   5178:                                             }
                   5179:                                         }
                   5180:                                     }
                   5181:                                 }
                   5182:                                 if ($curraccess eq 'none') {
                   5183:                                     next;
                   5184:                                 } elsif ($curraccess eq 'all') {
                   5185:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5186:                                 } elsif ($curraccess eq 'dh') {
                   5187:                                     if (grep(/^dh$/,@liveroles)) {
                   5188:                                         push(@possroles,$role);
                   5189:                                     } else {
                   5190:                                         next;
                   5191:                                     }
                   5192:                                 } elsif ($curraccess eq 'da') {
                   5193:                                     if (grep(/^da$/,@liveroles)) {
                   5194:                                         push(@possroles,$role);
                   5195:                                     } else {
                   5196:                                         next;
                   5197:                                     }
1.1172.2.89  raeburn  5198:                                 } elsif ($curraccess eq 'status') {
                   5199:                                     if (@okstatus) {
                   5200:                                         if (!@statuses) {
                   5201:                                             if (grep(/^default$/,@okstatus)) {
                   5202:                                                 push(@possroles,$role);
                   5203:                                             }
                   5204:                                         } else {
                   5205:                                             foreach my $status (@okstatus) {
                   5206:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5207:                                                     push(@possroles,$role);
                   5208:                                                     last;
                   5209:                                                 }
                   5210:                                             }
                   5211:                                         }
                   5212:                                     }
                   5213:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5214:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5215:                                         if ($curraccess eq 'exc') {
                   5216:                                             push(@possroles,$role);
                   5217:                                         }
                   5218:                                     } elsif ($curraccess eq 'inc') {
                   5219:                                         push(@possroles,$role);
                   5220:                                     }
                   5221:                                 }
                   5222:                             }
                   5223:                         }
                   5224:                     }
                   5225:                 }
                   5226:             }
                   5227:         }
                   5228:     }
                   5229:     unless (ref($description) eq 'HASH') {
                   5230:         if (ref($roles_by_num) eq 'ARRAY') {
                   5231:             my %desc;
                   5232:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5233:             $description = \%desc;
                   5234:         } else {
                   5235:             $description = {};
                   5236:         }
                   5237:     }
                   5238:     return (\@possroles,$description);
                   5239: }
                   5240: 
1.399     www      5241: # ----------------------------------------------------- Frontpage Announcements
                   5242: #
                   5243: #
                   5244: 
                   5245: sub postannounce {
                   5246:     my ($server,$text)=@_;
1.844     albertel 5247:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5248:     unless ($text=~/\w/) { $text=''; }
                   5249:     return &reply('setannounce:'.&escape($text),$server);
                   5250: }
                   5251: 
                   5252: sub getannounce {
1.448     albertel 5253: 
1.1172.2.96  raeburn  5254:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5255: 	my $announcement='';
1.800     albertel 5256: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5257: 	close($fh);
1.399     www      5258: 	if ($announcement=~/\w/) { 
                   5259: 	    return 
                   5260:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5261:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5262: 	} else {
                   5263: 	    return '';
                   5264: 	}
                   5265:     } else {
                   5266: 	return '';
                   5267:     }
1.351     www      5268: }
1.353     www      5269: 
                   5270: # ---------------------------------------------------------- Course ID routines
                   5271: # Deal with domain's nohist_courseid.db files
                   5272: #
                   5273: 
                   5274: sub courseidput {
1.921     raeburn  5275:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5276:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5277:     my $outcome;
                   5278:     if ($caller eq 'timeonly') {
                   5279:         my $cids = '';
                   5280:         foreach my $item (keys(%$storehash)) {
                   5281:             $cids.=&escape($item).'&';
                   5282:         }
                   5283:         $cids=~s/\&$//;
                   5284:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5285:                           $coursehome);       
                   5286:     } else {
                   5287:         my $items = '';
                   5288:         foreach my $item (keys(%$storehash)) {
                   5289:             $items.= &escape($item).'='.
                   5290:                      &freeze_escape($$storehash{$item}).'&';
                   5291:         }
                   5292:         $items=~s/\&$//;
                   5293:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5294:                           $coursehome);
1.918     raeburn  5295:     }
                   5296:     if ($outcome eq 'unknown_cmd') {
                   5297:         my $what;
                   5298:         foreach my $cid (keys(%$storehash)) {
                   5299:             $what .= &escape($cid).'=';
1.921     raeburn  5300:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5301:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5302:             }
                   5303:             $what =~ s/\:$/&/;
                   5304:         }
                   5305:         $what =~ s/\&$//;  
                   5306:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5307:     } else {
                   5308:         return $outcome;
                   5309:     }
1.353     www      5310: }
                   5311: 
                   5312: sub courseiddump {
1.921     raeburn  5313:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5314:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5315:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5316:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5317:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5318:     my $as_hash = 1;
                   5319:     my %returnhash;
                   5320:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5321:     my %libserv = &all_library();
                   5322:     foreach my $tryserver (keys(%libserv)) {
                   5323:         if ( (  $hostidflag == 1 
                   5324: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5325: 	     || (!defined($hostidflag)) ) {
                   5326: 
1.918     raeburn  5327: 	    if (($domfilter eq '') ||
                   5328: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5329:                 my $rep;
                   5330:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5331:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5332:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5333:                                 &escape($descfilter), &escape($instcodefilter),
                   5334:                                 &escape($ownerfilter), &escape($coursefilter),
                   5335:                                 &escape($typefilter), &escape($regexp_ok),
                   5336:                                 $as_hash, &escape($selfenrollonly),
                   5337:                                 &escape($catfilter), $showhidden, $caller,
                   5338:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5339:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5340:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5341:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5342:                 } else {
                   5343:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5344:                              $sincefilter.':'.&escape($descfilter).':'.
                   5345:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5346:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5347:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5348:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5349:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5350:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5351:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5352:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5353:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5354:                 }
                   5355: 
1.918     raeburn  5356:                 my @pairs=split(/\&/,$rep);
                   5357:                 foreach my $item (@pairs) {
                   5358:                     my ($key,$value)=split(/\=/,$item,2);
                   5359:                     $key = &unescape($key);
                   5360:                     next if ($key =~ /^error: 2 /);
                   5361:                     my $result = &thaw_unescape($value);
                   5362:                     if (ref($result) eq 'HASH') {
                   5363:                         $returnhash{$key}=$result;
                   5364:                     } else {
1.921     raeburn  5365:                         my @responses = split(/:/,$value);
                   5366:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5367:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5368:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5369:                         }
1.1008    raeburn  5370:                     }
1.353     www      5371:                 }
                   5372:             }
                   5373:         }
                   5374:     }
                   5375:     return %returnhash;
                   5376: }
                   5377: 
1.1055    raeburn  5378: sub courselastaccess {
                   5379:     my ($cdom,$cnum,$hostidref) = @_;
                   5380:     my %returnhash;
                   5381:     if ($cdom && $cnum) {
                   5382:         my $chome = &homeserver($cnum,$cdom);
                   5383:         if ($chome ne 'no_host') {
                   5384:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5385:             &extract_lastaccess(\%returnhash,$rep);
                   5386:         }
                   5387:     } else {
                   5388:         if (!$cdom) { $cdom=''; }
                   5389:         my %libserv = &all_library();
                   5390:         foreach my $tryserver (keys(%libserv)) {
                   5391:             if (ref($hostidref) eq 'ARRAY') {
                   5392:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5393:             } 
                   5394:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5395:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5396:                 &extract_lastaccess(\%returnhash,$rep);
                   5397:             }
                   5398:         }
                   5399:     }
                   5400:     return %returnhash;
                   5401: }
                   5402: 
                   5403: sub extract_lastaccess {
                   5404:     my ($returnhash,$rep) = @_;
                   5405:     if (ref($returnhash) eq 'HASH') {
                   5406:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5407:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5408:                  $rep eq '') {
                   5409:             my @pairs=split(/\&/,$rep);
                   5410:             foreach my $item (@pairs) {
                   5411:                 my ($key,$value)=split(/\=/,$item,2);
                   5412:                 $key = &unescape($key);
                   5413:                 next if ($key =~ /^error: 2 /);
                   5414:                 $returnhash->{$key} = &thaw_unescape($value);
                   5415:             }
                   5416:         }
                   5417:     }
                   5418:     return;
                   5419: }
                   5420: 
1.658     raeburn  5421: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5422: 
                   5423: sub dcmailput {
1.685     raeburn  5424:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5425:     my $status = &Apache::lonnet::critical(
1.740     www      5426:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5427:        &escape($message),$server);
1.662     raeburn  5428:     return $status;
                   5429: }
                   5430: 
1.658     raeburn  5431: sub dcmaildump {
                   5432:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5433:     my %returnhash=();
1.846     albertel 5434: 
                   5435:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5436:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5437:                                                          &escape($enddate).':';
                   5438: 	my @esc_senders=map { &escape($_)} @$senders;
                   5439: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5440: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5441:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5442:             if (($key) && ($value)) {
                   5443:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5444:             }
                   5445:         }
                   5446:     }
                   5447:     return %returnhash;
                   5448: }
1.662     raeburn  5449: # ---------------------------------------------------------- Domain roles
                   5450: 
                   5451: sub get_domain_roles {
                   5452:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5453:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5454:         $startdate = '.';
                   5455:     }
1.1018    raeburn  5456:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5457:         $enddate = '.';
                   5458:     }
1.922     raeburn  5459:     my $rolelist;
                   5460:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5461:         $rolelist = join('&',@{$roles});
1.922     raeburn  5462:     }
1.662     raeburn  5463:     my %personnel = ();
1.841     albertel 5464: 
                   5465:     my %servers = &get_servers($dom,'library');
                   5466:     foreach my $tryserver (keys(%servers)) {
                   5467: 	%{$personnel{$tryserver}}=();
                   5468: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5469: 					    &escape($startdate).':'.
                   5470: 					    &escape($enddate).':'.
                   5471: 					    &escape($rolelist), $tryserver))) {
                   5472: 	    my ($key,$value) = split(/\=/,$line,2);
                   5473: 	    if (($key) && ($value)) {
                   5474: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5475: 	    }
                   5476: 	}
1.662     raeburn  5477:     }
                   5478:     return %personnel;
                   5479: }
1.658     raeburn  5480: 
1.1172.2.89  raeburn  5481: sub get_active_domroles {
                   5482:     my ($dom,$roles) = @_;
                   5483:     return () unless (ref($roles) eq 'ARRAY');
                   5484:     my $now = time;
                   5485:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5486:     my %domroles;
                   5487:     foreach my $server (keys(%dompersonnel)) {
                   5488:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5489:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5490:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5491:         }
                   5492:     }
                   5493:     return %domroles;
                   5494: }
                   5495: 
1.1057    www      5496: # ----------------------------------------------------------- Interval timing 
1.149     www      5497: 
1.1153    www      5498: {
                   5499: # Caches needed for speedup of navmaps
                   5500: # We don't want to cache this for very long at all (5 seconds at most)
                   5501: # 
                   5502: # The user for whom we cache
                   5503: my $cachedkey='';
                   5504: # The cached times for this user
                   5505: my %cachedtimes=();
                   5506: # When this was last done
1.1172.2.66  raeburn  5507: my $cachedtime='';
1.1153    www      5508: 
                   5509: sub load_all_first_access {
1.1154    raeburn  5510:     my ($uname,$udom)=@_;
1.1156    www      5511:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5512:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5513:         return;
                   5514:     }
                   5515:     $cachedtime=time;
                   5516:     $cachedkey=$uname.':'.$udom;
                   5517:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5518: }
                   5519: 
1.504     albertel 5520: sub get_first_access {
1.1162    raeburn  5521:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5522:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5523:     if ($argsymb) { $symb=$argsymb; }
                   5524:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5525:     if ($argmap) { $map = $argmap; }
1.926     albertel 5526:     if ($type eq 'course') {
                   5527: 	$res='course';
                   5528:     } elsif ($type eq 'map') {
1.588     albertel 5529: 	$res=&symbread($map);
                   5530:     } else {
                   5531: 	$res=$symb;
                   5532:     }
1.1153    www      5533:     &load_all_first_access($uname,$udom);
                   5534:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5535: }
                   5536: 
                   5537: sub set_first_access {
1.1162    raeburn  5538:     my ($type,$interval)=@_;
1.790     albertel 5539:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5540:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5541:     if ($type eq 'course') {
                   5542: 	$res='course';
                   5543:     } elsif ($type eq 'map') {
1.588     albertel 5544: 	$res=&symbread($map);
                   5545:     } else {
                   5546: 	$res=$symb;
                   5547:     }
1.1153    www      5548:     $cachedkey='';
1.1162    raeburn  5549:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5550:     if ($firstaccess) {
                   5551:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5552:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5553:                  "in $courseid");
                   5554:         return 'already_set';
                   5555:     } else {
1.1162    raeburn  5556:         my $start = time;
                   5557: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5558:                           $udom,$uname);
                   5559:         if ($putres eq 'ok') {
                   5560:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5561:                  $udom,$uname); 
                   5562:             &appenv(
                   5563:                      {
                   5564:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5565:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5566:                      }
                   5567:                   );
1.1172.2.97  raeburn  5568:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5569:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5570:             }
1.1172.2.102  raeburn  5571:         } elsif ($putres ne 'refused') {
                   5572:             &logthis("Result: $putres when attempting to set first access time ".
                   5573:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5574:         }
                   5575:         return $putres;
1.505     albertel 5576:     }
                   5577:     return 'already_set';
1.504     albertel 5578: }
1.1153    www      5579: }
1.1172.2.32  raeburn  5580: 
                   5581: sub checkout {
                   5582:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5583:     my $now=time;
                   5584:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5585:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5586:     my $infostr=&escape(
                   5587:                  'CHECKOUTTOKEN&'.
                   5588:                  $tuname.'&'.
                   5589:                  $tudom.'&'.
                   5590:                  $tcrsid.'&'.
                   5591:                  $symb.'&'.
1.1172.2.134  raeburn  5592:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5593:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5594:     if ($token=~/^error\:/) {
                   5595:         &logthis("<font color=\"blue\">WARNING: ".
                   5596:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5597:                  "</font>");
                   5598:         return '';
                   5599:     }
                   5600: 
                   5601:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5602:     $token=~tr/a-z/A-Z/;
                   5603: 
                   5604:     my %infohash=('resource.0.outtoken' => $token,
                   5605:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5606:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5607: 
                   5608:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5609:        return '';
                   5610:     } else {
                   5611:         &logthis("<font color=\"blue\">WARNING: ".
                   5612:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5613:                  "</font>");
                   5614:     }
                   5615: 
                   5616:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5617:                          &escape('Checkout '.$infostr.' - '.
                   5618:                                                  $token)) ne 'ok') {
                   5619:         return '';
                   5620:     } else {
                   5621:         &logthis("<font color=\"blue\">WARNING: ".
                   5622:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5623:                  "</font>");
                   5624:     }
                   5625:     return $token;
                   5626: }
                   5627: 
                   5628: # ------------------------------------------------------------ Check in an item
                   5629: 
                   5630: sub checkin {
                   5631:     my $token=shift;
                   5632:     my $now=time;
                   5633:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5634:     $lonhost=~tr/A-Z/a-z/;
                   5635:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5636:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5637:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5638:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5639:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5640: 
                   5641:     unless (($tuname) && ($tudom)) {
                   5642:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5643:         return '';
                   5644:     }
                   5645: 
                   5646:     unless (&allowed('mgr',$tcrsid)) {
                   5647:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5648:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5649:         return '';
                   5650:     }
                   5651: 
                   5652:     my %infohash=('resource.0.intoken' => $token,
                   5653:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5654:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5655: 
                   5656:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5657:        return '';
                   5658:     }
                   5659: 
                   5660:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5661:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5662:         return '';
                   5663:     }
                   5664: 
                   5665:     return ($symb,$tuname,$tudom,$tcrsid);
                   5666: }
                   5667: 
1.110     www      5668: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5669: 
                   5670: sub expirespread {
                   5671:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5672:     my $cid=$env{'request.course.id'}; 
1.110     www      5673:     if ($cid) {
                   5674:        my $now=time;
                   5675:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5676:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5677:                             $env{'course.'.$cid.'.num'}.
1.110     www      5678: 	        	    ':nohist_expirationdates:'.
                   5679:                             &escape($key).'='.$now,
1.620     albertel 5680:                             $env{'course.'.$cid.'.home'})
1.110     www      5681:     }
                   5682:     return 'ok';
1.14      www      5683: }
                   5684: 
1.109     www      5685: # ----------------------------------------------------- Devalidate Spreadsheets
                   5686: 
                   5687: sub devalidate {
1.325     www      5688:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5689:     my $cid=$env{'request.course.id'}; 
1.109     www      5690:     if ($cid) {
1.391     matthew  5691:         # delete the stored spreadsheets for
                   5692:         # - the student level sheet of this user in course's homespace
                   5693:         # - the assessment level sheet for this resource 
                   5694:         #   for this user in user's homespace
1.553     albertel 5695: 	# - current conditional state info
1.325     www      5696: 	my $key=$uname.':'.$udom.':';
1.109     www      5697:         my $status=
1.299     matthew  5698: 	    &del('nohist_calculatedsheets',
1.391     matthew  5699: 		 [$key.'studentcalc:'],
1.620     albertel 5700: 		 $env{'course.'.$cid.'.domain'},
                   5701: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5702: 		.' '.
                   5703: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5704: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5705:         unless ($status eq 'ok ok') {
                   5706:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5707:                     $uname.' at '.$udom.' for '.
1.109     www      5708: 		    $symb.': '.$status);
1.133     albertel 5709:         }
1.553     albertel 5710: 	&delenv('user.state.'.$cid);
1.109     www      5711:     }
                   5712: }
                   5713: 
1.265     albertel 5714: sub get_scalar {
                   5715:     my ($string,$end) = @_;
                   5716:     my $value;
                   5717:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5718: 	$value = $1;
                   5719:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5720: 	$value = $1;
                   5721:     }
                   5722:     return &unescape($value);
                   5723: }
                   5724: 
                   5725: sub array2str {
                   5726:   my (@array) = @_;
                   5727:   my $result=&arrayref2str(\@array);
                   5728:   $result=~s/^__ARRAY_REF__//;
                   5729:   $result=~s/__END_ARRAY_REF__$//;
                   5730:   return $result;
                   5731: }
                   5732: 
1.204     albertel 5733: sub arrayref2str {
                   5734:   my ($arrayref) = @_;
1.265     albertel 5735:   my $result='__ARRAY_REF__';
1.204     albertel 5736:   foreach my $elem (@$arrayref) {
1.265     albertel 5737:     if(ref($elem) eq 'ARRAY') {
                   5738:       $result.=&arrayref2str($elem).'&';
                   5739:     } elsif(ref($elem) eq 'HASH') {
                   5740:       $result.=&hashref2str($elem).'&';
                   5741:     } elsif(ref($elem)) {
                   5742:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5743:     } else {
                   5744:       $result.=&escape($elem).'&';
                   5745:     }
                   5746:   }
                   5747:   $result=~s/\&$//;
1.265     albertel 5748:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5749:   return $result;
                   5750: }
                   5751: 
1.168     albertel 5752: sub hash2str {
1.204     albertel 5753:   my (%hash) = @_;
                   5754:   my $result=&hashref2str(\%hash);
1.265     albertel 5755:   $result=~s/^__HASH_REF__//;
                   5756:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5757:   return $result;
                   5758: }
                   5759: 
                   5760: sub hashref2str {
                   5761:   my ($hashref)=@_;
1.265     albertel 5762:   my $result='__HASH_REF__';
1.800     albertel 5763:   foreach my $key (sort(keys(%$hashref))) {
                   5764:     if (ref($key) eq 'ARRAY') {
                   5765:       $result.=&arrayref2str($key).'=';
                   5766:     } elsif (ref($key) eq 'HASH') {
                   5767:       $result.=&hashref2str($key).'=';
                   5768:     } elsif (ref($key)) {
1.265     albertel 5769:       $result.='=';
1.800     albertel 5770:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5771:     } else {
1.1132    raeburn  5772: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5773:     }
                   5774: 
1.800     albertel 5775:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5776:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5777:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5778:       $result.=&hashref2str($hashref->{$key}).'&';
                   5779:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5780:        $result.='&';
1.800     albertel 5781:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5782:     } else {
1.800     albertel 5783:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5784:     }
                   5785:   }
1.168     albertel 5786:   $result=~s/\&$//;
1.265     albertel 5787:   $result .= '__END_HASH_REF__';
1.168     albertel 5788:   return $result;
                   5789: }
                   5790: 
                   5791: sub str2hash {
1.265     albertel 5792:     my ($string)=@_;
                   5793:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5794:     return %$hash;
                   5795: }
                   5796: 
                   5797: sub str2hashref {
1.168     albertel 5798:   my ($string) = @_;
1.265     albertel 5799: 
                   5800:   my %hash;
                   5801: 
                   5802:   if($string !~ /^__HASH_REF__/) {
                   5803:       if (! ($string eq '' || !defined($string))) {
                   5804: 	  $hash{'error'}='Not hash reference';
                   5805:       }
                   5806:       return (\%hash, $string);
                   5807:   }
                   5808: 
                   5809:   $string =~ s/^__HASH_REF__//;
                   5810: 
                   5811:   while($string !~ /^__END_HASH_REF__/) {
                   5812:       #key
                   5813:       my $key='';
                   5814:       if($string =~ /^__HASH_REF__/) {
                   5815:           ($key, $string)=&str2hashref($string);
                   5816:           if(defined($key->{'error'})) {
                   5817:               $hash{'error'}='Bad data';
                   5818:               return (\%hash, $string);
                   5819:           }
                   5820:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5821:           ($key, $string)=&str2arrayref($string);
                   5822:           if($key->[0] eq 'Array reference error') {
                   5823:               $hash{'error'}='Bad data';
                   5824:               return (\%hash, $string);
                   5825:           }
                   5826:       } else {
                   5827:           $string =~ s/^(.*?)=//;
1.267     albertel 5828: 	  $key=&unescape($1);
1.265     albertel 5829:       }
                   5830:       $string =~ s/^=//;
                   5831: 
                   5832:       #value
                   5833:       my $value='';
                   5834:       if($string =~ /^__HASH_REF__/) {
                   5835:           ($value, $string)=&str2hashref($string);
                   5836:           if(defined($value->{'error'})) {
                   5837:               $hash{'error'}='Bad data';
                   5838:               return (\%hash, $string);
                   5839:           }
                   5840:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5841:           ($value, $string)=&str2arrayref($string);
                   5842:           if($value->[0] eq 'Array reference error') {
                   5843:               $hash{'error'}='Bad data';
                   5844:               return (\%hash, $string);
                   5845:           }
                   5846:       } else {
                   5847: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5848:       }
                   5849:       $string =~ s/^&//;
                   5850: 
                   5851:       $hash{$key}=$value;
1.204     albertel 5852:   }
1.265     albertel 5853: 
                   5854:   $string =~ s/^__END_HASH_REF__//;
                   5855: 
                   5856:   return (\%hash, $string);
1.204     albertel 5857: }
                   5858: 
                   5859: sub str2array {
1.265     albertel 5860:     my ($string)=@_;
                   5861:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5862:     return @$array;
                   5863: }
                   5864: 
                   5865: sub str2arrayref {
1.204     albertel 5866:   my ($string) = @_;
1.265     albertel 5867:   my @array;
                   5868: 
                   5869:   if($string !~ /^__ARRAY_REF__/) {
                   5870:       if (! ($string eq '' || !defined($string))) {
                   5871: 	  $array[0]='Array reference error';
                   5872:       }
                   5873:       return (\@array, $string);
                   5874:   }
                   5875: 
                   5876:   $string =~ s/^__ARRAY_REF__//;
                   5877: 
                   5878:   while($string !~ /^__END_ARRAY_REF__/) {
                   5879:       my $value='';
                   5880:       if($string =~ /^__HASH_REF__/) {
                   5881:           ($value, $string)=&str2hashref($string);
                   5882:           if(defined($value->{'error'})) {
                   5883:               $array[0] ='Array reference error';
                   5884:               return (\@array, $string);
                   5885:           }
                   5886:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5887:           ($value, $string)=&str2arrayref($string);
                   5888:           if($value->[0] eq 'Array reference error') {
                   5889:               $array[0] ='Array reference error';
                   5890:               return (\@array, $string);
                   5891:           }
                   5892:       } else {
                   5893: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5894:       }
                   5895:       $string =~ s/^&//;
                   5896: 
                   5897:       push(@array, $value);
1.191     harris41 5898:   }
1.265     albertel 5899: 
                   5900:   $string =~ s/^__END_ARRAY_REF__//;
                   5901: 
                   5902:   return (\@array, $string);
1.168     albertel 5903: }
                   5904: 
1.167     albertel 5905: # -------------------------------------------------------------------Temp Store
                   5906: 
1.168     albertel 5907: sub tmpreset {
                   5908:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5909:   if (!$symb) {
                   5910:     $symb=&symbread();
1.620     albertel 5911:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5912:   }
                   5913:   $symb=escape($symb);
                   5914: 
1.620     albertel 5915:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5916:   $namespace=~s/\//\_/g;
                   5917:   $namespace=~s/\W//g;
                   5918: 
1.620     albertel 5919:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5920:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5921:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5922:       $stuname=&get_requestor_ip();
1.591     albertel 5923:   }
1.1117    foxr     5924:   my $path=LONCAPA::tempdir();
1.168     albertel 5925:   my %hash;
                   5926:   if (tie(%hash,'GDBM_File',
                   5927: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5928: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5929:     foreach my $key (keys(%hash)) {
1.180     albertel 5930:       if ($key=~ /:$symb/) {
1.168     albertel 5931: 	delete($hash{$key});
                   5932:       }
                   5933:     }
                   5934:   }
                   5935: }
                   5936: 
1.167     albertel 5937: sub tmpstore {
1.168     albertel 5938:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5939: 
                   5940:   if (!$symb) {
                   5941:     $symb=&symbread();
1.620     albertel 5942:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5943:   }
                   5944:   $symb=escape($symb);
                   5945: 
                   5946:   if (!$namespace) {
                   5947:     # I don't think we would ever want to store this for a course.
                   5948:     # it seems this will only be used if we don't have a course.
1.620     albertel 5949:     #$namespace=$env{'request.course.id'};
1.168     albertel 5950:     #if (!$namespace) {
1.620     albertel 5951:       $namespace=$env{'request.state'};
1.168     albertel 5952:     #}
                   5953:   }
                   5954:   $namespace=~s/\//\_/g;
                   5955:   $namespace=~s/\W//g;
1.620     albertel 5956:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5957:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5958:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5959:       $stuname=&get_requestor_ip();
1.591     albertel 5960:   }
1.168     albertel 5961:   my $now=time;
                   5962:   my %hash;
1.1117    foxr     5963:   my $path=LONCAPA::tempdir();
1.168     albertel 5964:   if (tie(%hash,'GDBM_File',
                   5965: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5966: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5967:     $hash{"version:$symb"}++;
                   5968:     my $version=$hash{"version:$symb"};
                   5969:     my $allkeys=''; 
                   5970:     foreach my $key (keys(%$storehash)) {
                   5971:       $allkeys.=$key.':';
1.591     albertel 5972:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5973:     }
                   5974:     $hash{"$version:$symb:timestamp"}=$now;
                   5975:     $allkeys.='timestamp';
                   5976:     $hash{"$version:keys:$symb"}=$allkeys;
                   5977:     if (untie(%hash)) {
                   5978:       return 'ok';
                   5979:     } else {
                   5980:       return "error:$!";
                   5981:     }
                   5982:   } else {
                   5983:     return "error:$!";
                   5984:   }
                   5985: }
1.167     albertel 5986: 
1.168     albertel 5987: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5988: 
1.168     albertel 5989: sub tmprestore {
                   5990:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5991: 
1.168     albertel 5992:   if (!$symb) {
                   5993:     $symb=&symbread();
1.620     albertel 5994:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5995:   }
                   5996:   $symb=escape($symb);
                   5997: 
1.620     albertel 5998:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5999: 
1.620     albertel 6000:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6001:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6002:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6003:       $stuname=&get_requestor_ip();
1.591     albertel 6004:   }
1.168     albertel 6005:   my %returnhash;
                   6006:   $namespace=~s/\//\_/g;
                   6007:   $namespace=~s/\W//g;
                   6008:   my %hash;
1.1117    foxr     6009:   my $path=LONCAPA::tempdir();
1.168     albertel 6010:   if (tie(%hash,'GDBM_File',
                   6011: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6012: 	  &GDBM_READER(),0640)) {
1.168     albertel 6013:     my $version=$hash{"version:$symb"};
                   6014:     $returnhash{'version'}=$version;
                   6015:     my $scope;
                   6016:     for ($scope=1;$scope<=$version;$scope++) {
                   6017:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6018:       my @keys=split(/:/,$vkeys);
                   6019:       my $key;
                   6020:       $returnhash{"$scope:keys"}=$vkeys;
                   6021:       foreach $key (@keys) {
1.591     albertel 6022: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6023: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6024:       }
                   6025:     }
1.168     albertel 6026:     if (!(untie(%hash))) {
                   6027:       return "error:$!";
                   6028:     }
                   6029:   } else {
                   6030:     return "error:$!";
                   6031:   }
                   6032:   return %returnhash;
1.167     albertel 6033: }
                   6034: 
1.9       www      6035: # ----------------------------------------------------------------------- Store
                   6036: 
                   6037: sub store {
1.1172.2.64  raeburn  6038:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6039:     my $home='';
                   6040: 
1.168     albertel 6041:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6042: 
1.213     www      6043:     $symb=&symbclean($symb);
1.122     albertel 6044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6045: 
1.620     albertel 6046:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6047:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6048: 
                   6049:     &devalidate($symb,$stuname,$domain);
1.109     www      6050: 
                   6051:     $symb=escape($symb);
1.187     www      6052:     if (!$namespace) { 
1.620     albertel 6053:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6054:           return ''; 
                   6055:        } 
                   6056:     }
1.620     albertel 6057:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6058: 
1.1172.2.138  raeburn  6059:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6060:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6061: 
1.12      www      6062:     my $namevalue='';
1.800     albertel 6063:     foreach my $key (keys(%$storehash)) {
                   6064:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6065:     }
1.12      www      6066:     $namevalue=~s/\&$//;
1.187     www      6067:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6068:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6069: }
                   6070: 
1.47      www      6071: # -------------------------------------------------------------- Critical Store
                   6072: 
                   6073: sub cstore {
1.1172.2.64  raeburn  6074:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6075:     my $home='';
                   6076: 
1.168     albertel 6077:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6078: 
1.213     www      6079:     $symb=&symbclean($symb);
1.122     albertel 6080:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6081: 
1.620     albertel 6082:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6083:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6084: 
                   6085:     &devalidate($symb,$stuname,$domain);
1.109     www      6086: 
                   6087:     $symb=escape($symb);
1.187     www      6088:     if (!$namespace) { 
1.620     albertel 6089:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6090:           return ''; 
                   6091:        } 
                   6092:     }
1.620     albertel 6093:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6094: 
1.1172.2.138  raeburn  6095:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6096:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6097: 
1.47      www      6098:     my $namevalue='';
1.800     albertel 6099:     foreach my $key (keys(%$storehash)) {
                   6100:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6101:     }
1.47      www      6102:     $namevalue=~s/\&$//;
1.187     www      6103:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6104:     return critical
1.1172.2.64  raeburn  6105:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6106: }
                   6107: 
1.9       www      6108: # --------------------------------------------------------------------- Restore
                   6109: 
                   6110: sub restore {
1.124     www      6111:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6112:     my $home='';
                   6113: 
1.168     albertel 6114:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6115: 
1.122     albertel 6116:     if (!$symb) {
1.1172.2.26  raeburn  6117:         return if ($namespace eq 'courserequests');
                   6118:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6119:     } else {
1.1172.2.26  raeburn  6120:         unless ($namespace eq 'courserequests') {
                   6121:             $symb=&escape(&symbclean($symb));
                   6122:         }
1.122     albertel 6123:     }
1.188     www      6124:     if (!$namespace) { 
1.620     albertel 6125:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6126:           return ''; 
                   6127:        } 
                   6128:     }
1.620     albertel 6129:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6130:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6131:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6132:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6133: 
1.12      www      6134:     my %returnhash=();
1.800     albertel 6135:     foreach my $line (split(/\&/,$answer)) {
                   6136: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6137:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6138:     }
1.75      www      6139:     my $version;
                   6140:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6141:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6142:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6143:        }
1.75      www      6144:     }
1.13      www      6145:     return %returnhash;
1.34      www      6146: }
                   6147: 
                   6148: # ---------------------------------------------------------- Course Description
1.1118    foxr     6149: #
                   6150: #  
1.34      www      6151: 
                   6152: sub coursedescription {
1.731     albertel 6153:     my ($courseid,$args)=@_;
1.34      www      6154:     $courseid=~s/^\///;
1.49      www      6155:     $courseid=~s/\_/\//g;
1.34      www      6156:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6157:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6158:     my $normalid=$cdomain.'_'.$cnum;
                   6159:     # need to always cache even if we get errors otherwise we keep 
                   6160:     # trying and trying and trying to get the course description.
                   6161:     my %envhash=();
                   6162:     my %returnhash=();
1.731     albertel 6163:     
                   6164:     my $expiretime=600;
                   6165:     if ($env{'request.course.id'} eq $normalid) {
                   6166: 	$expiretime=120;
                   6167:     }
                   6168: 
                   6169:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6170:     if (!$args->{'freshen_cache'}
                   6171: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6172: 	foreach my $key (keys(%env)) {
                   6173: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6174: 	    my ($setting) = $1;
                   6175: 	    $returnhash{$setting} = $env{$key};
                   6176: 	}
                   6177: 	return %returnhash;
                   6178:     }
                   6179: 
1.1118    foxr     6180:     # get the data again
                   6181: 
1.731     albertel 6182:     if (!$args->{'one_time'}) {
                   6183: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6184:     }
1.811     albertel 6185: 
1.34      www      6186:     if ($chome ne 'no_host') {
1.302     albertel 6187:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6188:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6189: 	   my $username = $env{'user.name'}; # Defult username
                   6190: 	   if(defined $args->{'user'}) {
                   6191: 	       $username = $args->{'user'};
                   6192: 	   }
1.129     albertel 6193:            $returnhash{'home'}= $chome;
                   6194: 	   $returnhash{'domain'} = $cdomain;
                   6195: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6196:            if (!defined($returnhash{'type'})) {
                   6197:                $returnhash{'type'} = 'Course';
                   6198:            }
1.130     albertel 6199:            while (my ($name,$value) = each %returnhash) {
1.53      www      6200:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6201:            }
1.270     www      6202:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6203:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6204: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6205:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6206:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6207:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6208:        }
                   6209:     }
1.731     albertel 6210:     if (!$args->{'one_time'}) {
1.949     raeburn  6211: 	&appenv(\%envhash);
1.731     albertel 6212:     }
1.302     albertel 6213:     return %returnhash;
1.461     www      6214: }
                   6215: 
1.1080    raeburn  6216: sub update_released_required {
                   6217:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6218:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6219:         $cid = $env{'request.course.id'};
                   6220:         $cdom = $env{'course.'.$cid.'.domain'};
                   6221:         $cnum = $env{'course.'.$cid.'.num'};
                   6222:         $chome = $env{'course.'.$cid.'.home'};
                   6223:     }
                   6224:     if ($needsrelease) {
                   6225:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6226:         my $needsupdate;
                   6227:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6228:             $needsupdate = 1;
                   6229:         } else {
                   6230:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6231:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6232:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6233:                 $needsupdate = 1;
                   6234:             }
                   6235:         }
                   6236:         if ($needsupdate) {
                   6237:             my %needshash = (
                   6238:                              'internal.releaserequired' => $needsrelease,
                   6239:                             );
                   6240:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6241:             if ($putresult eq 'ok') {
                   6242:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6243:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6244:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6245:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6246:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6247:                 }
                   6248:             }
                   6249:         }
                   6250:     }
                   6251:     return;
                   6252: }
                   6253: 
1.461     www      6254: # -------------------------------------------------See if a user is privileged
                   6255: 
                   6256: sub privileged {
1.1172.2.23  raeburn  6257:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6258:     my $now = time;
1.1172.2.23  raeburn  6259:     my $roles;
                   6260:     if (ref($possroles) eq 'ARRAY') {
                   6261:         $roles = $possroles;
                   6262:     } else {
                   6263:         $roles = ['dc','su'];
                   6264:     }
                   6265:     if (ref($possdomains) eq 'ARRAY') {
                   6266:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6267:         foreach my $dom (@{$possdomains}) {
                   6268:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6269:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6270:                 foreach my $role (@{$roles}) {
                   6271:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6272:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6273:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6274:                             return 1 unless (($end && $end < $now) ||
                   6275:                                              ($start && $start > $now));
                   6276:                         }
                   6277:                     }
                   6278:                 }
                   6279:             }
                   6280:         }
                   6281:     } else {
                   6282:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6283:         my $now = time;
1.1170    droeschl 6284: 
1.1172.2.58  raeburn  6285:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6286:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6287:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6288:                 return 1 unless ($tend && $tend < $now)
                   6289:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6290:             }
1.1172.2.23  raeburn  6291:         }
                   6292:     }
1.461     www      6293:     return 0;
1.9       www      6294: }
1.1       albertel 6295: 
1.1172.2.23  raeburn  6296: sub privileged_by_domain {
                   6297:     my ($domains,$roles) = @_;
                   6298:     my %privileged = ();
                   6299:     my $cachetime = 60*60*24;
                   6300:     my $now = time;
                   6301:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6302:         return %privileged;
                   6303:     }
                   6304:     foreach my $dom (@{$domains}) {
                   6305:         next if (ref($privileged{$dom}) eq 'HASH');
                   6306:         my $needroles;
                   6307:         foreach my $role (@{$roles}) {
                   6308:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6309:             if (defined($cached)) {
                   6310:                 if (ref($result) eq 'HASH') {
                   6311:                     $privileged{$dom}{$role} = $result;
                   6312:                 }
                   6313:             } else {
                   6314:                 $needroles = 1;
                   6315:             }
                   6316:         }
                   6317:         if ($needroles) {
                   6318:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6319:             $privileged{$dom} = {};
                   6320:             foreach my $server (keys(%dompersonnel)) {
                   6321:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6322:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6323:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6324:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6325:                         next if ($end && $end < $now);
                   6326:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6327:                             $dompersonnel{$server}{$item};
                   6328:                     }
                   6329:                 }
                   6330:             }
                   6331:             if (ref($privileged{$dom}) eq 'HASH') {
                   6332:                 foreach my $role (@{$roles}) {
                   6333:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6334:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6335:                     } else {
                   6336:                         my %hash = ();
                   6337:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6338:                     }
                   6339:                 }
                   6340:             }
                   6341:         }
                   6342:     }
                   6343:     return %privileged;
                   6344: }
                   6345: 
1.103     harris41 6346: # -------------------------------------------------------- Get user privileges
1.11      www      6347: 
                   6348: sub rolesinit {
1.1169    droeschl 6349:     my ($domain, $username) = @_;
                   6350:     my %userroles = ('user.login.time' => time);
                   6351:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6352: 
                   6353:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6354:     # also, blocking can be triggered by an activating timer
                   6355:     # it's saved in the user's %env.
                   6356:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6357:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6358:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6359:         %timerintchk, %timerintenv);
                   6360: 
1.1162    raeburn  6361:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6362:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6363:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6364:     }
1.1169    droeschl 6365: 
1.1162    raeburn  6366:     foreach my $key (keys(%timerinterval)) {
                   6367:         my ($cid,$rest) = split(/\0/,$key);
                   6368:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6369:     }
1.1169    droeschl 6370: 
1.11      www      6371:     my %allroles=();
1.1162    raeburn  6372:     my %allgroups=();
1.11      www      6373: 
1.1172.2.58  raeburn  6374:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6375:         my $role = $rolesdump{$area};
                   6376:         $area =~ s/\_\w\w$//;
                   6377: 
                   6378:         my ($trole, $tend, $tstart, $group_privs);
                   6379: 
                   6380:         if ($role =~ /^cr/) {
                   6381:         # Custom role, defined by a user 
                   6382:         # e.g., user.role.cr/msu/smith/mynewrole
                   6383:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6384:                 $trole = $1;
                   6385:                 ($tend, $tstart) = split('_', $2);
                   6386:             } else {
                   6387:                 $trole = $role;
                   6388:             }
                   6389:         } elsif ($role =~ m|^gr/|) {
                   6390:         # Role of member in a group, defined within a course/community
                   6391:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6392:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6393:             next if $tstart eq '-1';
                   6394:             ($trole, $group_privs) = split(/\//, $trole);
                   6395:             $group_privs = &unescape($group_privs);
                   6396:         } else {
                   6397:         # Just a normal role, defined in roles.tab
                   6398:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6399:         }
                   6400: 
                   6401:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6402:                  $username);
                   6403:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6404: 
                   6405:         # role expired or not available yet?
                   6406:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6407:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6408: 
                   6409:         next if $area eq '' or $trole eq '';
                   6410: 
                   6411:         my $spec = "$trole.$area";
                   6412:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6413: 
                   6414:         if ($trole =~ /^cr\//) {
                   6415:         # Custom role, defined by a user
                   6416:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6417:         } elsif ($trole eq 'gr') {
                   6418:         # Role of a member in a group, defined within a course/community
                   6419:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6420:             next;
                   6421:         } else {
                   6422:         # Normal role, defined in roles.tab
                   6423:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6424:         }
                   6425: 
                   6426:         my $cid = $tdomain.'_'.$trest;
                   6427:         unless ($firstaccchk{$cid}) {
                   6428:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6429:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6430:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6431:                         $coursetimerstarts{$cid}{$item}; 
                   6432:                 }
                   6433:             }
                   6434:             $firstaccchk{$cid} = 1;
                   6435:         }
                   6436:         unless ($timerintchk{$cid}) {
                   6437:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6438:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6439:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6440:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6441:                 }
1.12      www      6442:             }
1.1169    droeschl 6443:             $timerintchk{$cid} = 1;
1.191     harris41 6444:         }
1.11      www      6445:     }
1.1169    droeschl 6446: 
1.1172.2.91  raeburn  6447:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6448:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6449:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6450:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6451: 
1.1162    raeburn  6452:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6453: }
                   6454: 
1.567     raeburn  6455: sub set_arearole {
1.1172.2.19  raeburn  6456:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6457:     unless ($nolog) {
1.567     raeburn  6458: # log the associated role with the area
1.1172.2.19  raeburn  6459:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6460:     }
1.743     albertel 6461:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6462: }
                   6463: 
                   6464: sub custom_roleprivs {
                   6465:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6466:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6467:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6468:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6469:         my ($rdummy,$roledef)=
                   6470:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6471:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6472:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6473:             if (defined($syspriv)) {
1.1043    raeburn  6474:                 if ($trest =~ /^$match_community$/) {
                   6475:                     $syspriv =~ s/bre\&S//; 
                   6476:                 }
1.567     raeburn  6477:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6478:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6479:             }
                   6480:             if ($tdomain ne '') {
                   6481:                 if (defined($dompriv)) {
                   6482:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6483:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6484:                 }
                   6485:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6486:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6487:                         my $rolename = $1;
                   6488:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6489:                     }
1.567     raeburn  6490:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6491:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6492:                 }
                   6493:             }
                   6494:         }
                   6495:     }
                   6496: }
                   6497: 
1.1172.2.89  raeburn  6498: sub course_adhocrole_privs {
                   6499:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6500:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6501:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6502:         my (%currprivs,%storeprivs);
                   6503:         foreach my $item (split(/:/,$coursepriv)) {
                   6504:             my ($priv,$restrict) = split(/\&/,$item);
                   6505:             $currprivs{$priv} = $restrict;
                   6506:         }
                   6507:         my (%possadd,%possremove,%full);
                   6508:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6509:             my ($priv,$restrict)=split(/\&/,$item);
                   6510:             $full{$priv} = $restrict;
                   6511:         }
                   6512:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6513:              next if ($item eq '');
                   6514:              my ($rule,$rest) = split(/=/,$item);
                   6515:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6516:              foreach my $priv (split(/:/,$rest)) {
                   6517:                  if ($priv ne '') {
                   6518:                      if ($rule eq 'off') {
                   6519:                          $possremove{$priv} = 1;
                   6520:                      } else {
                   6521:                          $possadd{$priv} = 1;
                   6522:                      }
                   6523:                  }
                   6524:              }
                   6525:          }
                   6526:          foreach my $priv (sort(keys(%full))) {
                   6527:              if (exists($currprivs{$priv})) {
                   6528:                  unless (exists($possremove{$priv})) {
                   6529:                      $storeprivs{$priv} = $currprivs{$priv};
                   6530:                  }
                   6531:              } elsif (exists($possadd{$priv})) {
                   6532:                  $storeprivs{$priv} = $full{$priv};
                   6533:              }
                   6534:          }
                   6535:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6536:      }
                   6537:      return $coursepriv;
                   6538: }
                   6539: 
1.678     raeburn  6540: sub group_roleprivs {
                   6541:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6542:     my $access = 1;
                   6543:     my $now = time;
                   6544:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6545:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6546:     if ($access) {
1.811     albertel 6547:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6548:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6549:     }
                   6550: }
1.567     raeburn  6551: 
                   6552: sub standard_roleprivs {
                   6553:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6554:     if (defined($pr{$trole.':s'})) {
                   6555:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6556:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6557:     }
                   6558:     if ($tdomain ne '') {
                   6559:         if (defined($pr{$trole.':d'})) {
                   6560:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6561:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6562:         }
                   6563:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6564:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6565:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6566:         }
                   6567:     }
                   6568: }
                   6569: 
                   6570: sub set_userprivs {
1.1064    raeburn  6571:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6572:     my $author=0;
                   6573:     my $adv=0;
1.1172.2.91  raeburn  6574:     my $rar=0;
1.678     raeburn  6575:     my %grouproles = ();
                   6576:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6577:         my @groupkeys; 
1.1000    raeburn  6578:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6579:             push(@groupkeys,$role);
                   6580:         }
                   6581:         if (ref($groups_roles) eq 'HASH') {
                   6582:             foreach my $key (keys(%{$groups_roles})) {
                   6583:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6584:                     push(@groupkeys,$key);
                   6585:                 }
                   6586:             }
                   6587:         }
                   6588:         if (@groupkeys > 0) {
                   6589:             foreach my $role (@groupkeys) {
                   6590:                 my ($trole,$area,$sec,$extendedarea);
                   6591:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6592:                     $trole = $1;
                   6593:                     $area = $2;
                   6594:                     $sec = $3;
                   6595:                     $extendedarea = $area.$sec;
                   6596:                     if (exists($$allgroups{$area})) {
                   6597:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6598:                             my $spec = $trole.'.'.$extendedarea;
                   6599:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6600:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6601:                         }
1.678     raeburn  6602:                     }
                   6603:                 }
                   6604:             }
                   6605:         }
                   6606:     }
1.800     albertel 6607:     foreach my $group (keys(%grouproles)) {
                   6608:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6609:     }
1.800     albertel 6610:     foreach my $role (keys(%{$allroles})) {
                   6611:         my %thesepriv;
1.941     raeburn  6612:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6613:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6614:             if ($item ne '') {
                   6615:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6616:                 if ($restrictions eq '') {
                   6617:                     $thesepriv{$privilege}='F';
                   6618:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6619:                     $thesepriv{$privilege}.=$restrictions;
                   6620:                 }
                   6621:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6622:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6623:             }
                   6624:         }
                   6625:         my $thesestr='';
1.1104    raeburn  6626:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6627: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6628: 	}
                   6629:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6630:     }
1.1172.2.91  raeburn  6631:     return ($author,$adv,$rar);
1.567     raeburn  6632: }
                   6633: 
1.994     raeburn  6634: sub role_status {
1.1104    raeburn  6635:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6636:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6637:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6638:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6639:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6640:             $$where = '/'.$two;
1.994     raeburn  6641:             $$trolecode=$$role.'.'.$$where;
                   6642:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6643:             $$tstatus='is';
1.1104    raeburn  6644:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6645:                 $$tstatus='future';
1.1034    raeburn  6646:                 if ($$tstart<$now) {
                   6647:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6648:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6649:                             my (%allroles,%allgroups,$group_privs,
                   6650:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6651:                             my %userroles = (
                   6652:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6653:                             );
1.1064    raeburn  6654:                             @rolecodes = ('cm'); 
1.1002    raeburn  6655:                             my $spec=$$role.'.'.$$where;
                   6656:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6657:                             if ($$role =~ /^cr\//) {
                   6658:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6659:                                 push(@rolecodes,'cr');
1.1002    raeburn  6660:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6661:                                 push(@rolecodes,$$role);
1.1002    raeburn  6662:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6663:                                                     $env{'user.name'});
1.1064    raeburn  6664:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6665:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6666:                                 $group_privs = &unescape($group_privs);
                   6667:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6668:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  6669:                                 &get_groups_roles($tdomain,$trest,
                   6670:                                                   \%course_roles,\@rolecodes,
                   6671:                                                   \%groups_roles);
1.1002    raeburn  6672:                             } else {
1.1064    raeburn  6673:                                 push(@rolecodes,$$role);
1.1002    raeburn  6674:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6675:                             }
1.1172.2.91  raeburn  6676:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6677:                                                                    \%groups_roles);
1.1064    raeburn  6678:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6679:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6680:                         }
                   6681:                     }
1.1034    raeburn  6682:                     $$tstatus = 'is';
1.1002    raeburn  6683:                 }
1.994     raeburn  6684:             }
                   6685:             if ($$tend) {
1.1104    raeburn  6686:                 if ($$tend<$update) {
1.994     raeburn  6687:                     $$tstatus='expired';
                   6688:                 } elsif ($$tend<$now) {
                   6689:                     $$tstatus='will_not';
                   6690:                 }
                   6691:             }
                   6692:         }
                   6693:     }
                   6694: }
                   6695: 
1.1104    raeburn  6696: sub get_groups_roles {
                   6697:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6698:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6699:                   (ref($rolecodes) eq 'ARRAY') && 
                   6700:                   (ref($groups_roles) eq 'HASH')); 
                   6701:     if (keys(%{$cdom_courseroles}) > 0) {
                   6702:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6703:         if ($cdom ne '' && $cnum ne '') {
                   6704:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6705:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6706:                     my $crsrole = $1;
                   6707:                     my $crssec = $2;
                   6708:                     if ($crsrole =~ /^cr/) {
                   6709:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6710:                             push(@{$rolecodes},'cr');
                   6711:                         }
                   6712:                     } else {
                   6713:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6714:                             push(@{$rolecodes},$crsrole);
                   6715:                         }
                   6716:                     }
                   6717:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6718:                     if ($crssec ne '') {
                   6719:                         $rolekey .= "/$crssec";
                   6720:                     }
                   6721:                     $rolekey .= './';
                   6722:                     $groups_roles->{$rolekey} = $rolecodes;
                   6723:                 }
                   6724:             }
                   6725:         }
                   6726:     }
                   6727:     return;
                   6728: }
                   6729: 
                   6730: sub delete_env_groupprivs {
                   6731:     my ($where,$courseroles,$possroles) = @_;
                   6732:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6733:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6734:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6735:         %{$courseroles->{$udom}} =
                   6736:             &get_my_roles('','','userroles',['active'],
                   6737:                           $possroles,[$udom],1);
                   6738:     }
                   6739:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6740:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6741:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6742:             my $area = '/'.$cdom.'/'.$cnum;
                   6743:             my $privkey = "user.priv.$crsrole.$area";
                   6744:             if ($crssec ne '') {
                   6745:                 $privkey .= '/'.$crssec;
                   6746:             }
                   6747:             $privkey .= ".$area/$group";
                   6748:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6749:         }
                   6750:     }
                   6751:     return;
                   6752: }
                   6753: 
1.994     raeburn  6754: sub check_adhoc_privs {
1.1172.2.86  raeburn  6755:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6756:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6757:     if ($sec) {
                   6758:         $cckey .= '/'.$sec;
                   6759:     }
1.1172.2.9  raeburn  6760:     my $setprivs;
1.994     raeburn  6761:     if ($env{$cckey}) {
                   6762:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6763:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6764:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6765:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6766:             $setprivs = 1;
1.994     raeburn  6767:         }
                   6768:     } else {
1.1172.2.87  raeburn  6769:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6770:         $setprivs = 1;
1.994     raeburn  6771:     }
1.1172.2.9  raeburn  6772:     return $setprivs;
1.994     raeburn  6773: }
                   6774: 
                   6775: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6776: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6777:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6778:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6779:     if ($sec ne '') {
                   6780:         $area .= '/'.$sec;
                   6781:     }
1.994     raeburn  6782:     my $spec = $role.'.'.$area;
                   6783:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6784:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6785:     my %rolehash = ();
1.1172.2.89  raeburn  6786:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6787:         my $rolename = $1;
1.1172.2.84  raeburn  6788:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6789:         my %domdef = &get_domain_defaults($dcdom);
                   6790:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6791:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6792:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6793:             }
                   6794:         }
1.1172.2.84  raeburn  6795:     } else {
                   6796:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6797:     }
1.1172.2.91  raeburn  6798:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6799:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6800:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6801:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6802:         &appenv( {'request.role'        => $spec,
                   6803:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6804:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6805:                  }
                   6806:                );
                   6807:         my $tadv=0;
                   6808:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6809:         &appenv({'request.role.adv'    => $tadv});
                   6810:     }
1.994     raeburn  6811: }
                   6812: 
1.12      www      6813: # --------------------------------------------------------------- get interface
                   6814: 
                   6815: sub get {
1.131     albertel 6816:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6817:    my $items='';
1.800     albertel 6818:    foreach my $item (@$storearr) {
                   6819:        $items.=&escape($item).'&';
1.191     harris41 6820:    }
1.12      www      6821:    $items=~s/\&$//;
1.620     albertel 6822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6823:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6824:    my $uhome=&homeserver($uname,$udomain);
                   6825: 
1.133     albertel 6826:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6827:    my @pairs=split(/\&/,$rep);
1.273     albertel 6828:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6829:      return @pairs;
                   6830:    }
1.15      www      6831:    my %returnhash=();
1.42      www      6832:    my $i=0;
1.800     albertel 6833:    foreach my $item (@$storearr) {
                   6834:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6835:       $i++;
1.191     harris41 6836:    }
1.15      www      6837:    return %returnhash;
1.27      www      6838: }
                   6839: 
                   6840: # --------------------------------------------------------------- del interface
                   6841: 
                   6842: sub del {
1.133     albertel 6843:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6844:    my $items='';
1.800     albertel 6845:    foreach my $item (@$storearr) {
                   6846:        $items.=&escape($item).'&';
1.191     harris41 6847:    }
1.984     neumanie 6848: 
1.27      www      6849:    $items=~s/\&$//;
1.620     albertel 6850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6851:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6852:    my $uhome=&homeserver($uname,$udomain);
                   6853:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6854: }
                   6855: 
                   6856: # -------------------------------------------------------------- dump interface
                   6857: 
1.1172.2.22  raeburn  6858: sub unserialize {
                   6859:     my ($rep, $escapedkeys) = @_;
                   6860: 
                   6861:     return {} if $rep =~ /^error/;
                   6862: 
                   6863:     my %returnhash=();
                   6864:     foreach my $item (split(/\&/,$rep)) {
                   6865:         my ($key, $value) = split(/=/, $item, 2);
                   6866:         $key = unescape($key) unless $escapedkeys;
                   6867:         next if $key =~ /^error: 2 /;
                   6868:         $returnhash{$key} = &thaw_unescape($value);
                   6869:     }
                   6870:     return \%returnhash;
                   6871: }
                   6872: 
                   6873: # see Lond::dump_with_regexp
                   6874: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6875: sub dump {
1.1172.2.22  raeburn  6876:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6878:     if (!$uname) { $uname=$env{'user.name'}; }
                   6879:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6880: 
1.1172.2.55  raeburn  6881:     if ($regexp) {
                   6882:         $regexp=&escape($regexp);
                   6883:     } else {
                   6884:         $regexp='.';
                   6885:     }
1.1172.2.22  raeburn  6886:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6887:         # user is hosted on this machine
1.1172.2.55  raeburn  6888:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6889:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6890:         return %{&unserialize($reply, $escapedkeys)};
                   6891:     }
1.1166    raeburn  6892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6893:     my @pairs=split(/\&/,$rep);
                   6894:     my %returnhash=();
1.1098    foxr     6895:     if (!($rep =~ /^error/ )) {
                   6896: 	foreach my $item (@pairs) {
                   6897: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6898:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6899: 	    next if ($key =~ /^error: 2 /);
                   6900: 	    $returnhash{$key}=&thaw_unescape($value);
                   6901: 	}
1.755     albertel 6902:     }
                   6903:     return %returnhash;
1.407     www      6904: }
                   6905: 
1.1098    foxr     6906: 
1.717     albertel 6907: # --------------------------------------------------------- dumpstore interface
                   6908: 
                   6909: sub dumpstore {
                   6910:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6911:    # same as dump but keys must be escaped. They may contain colon separated
                   6912:    # lists of values that may themself contain colons (e.g. symbs).
                   6913:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6914: }
                   6915: 
1.407     www      6916: # -------------------------------------------------------------- keys interface
                   6917: 
                   6918: sub getkeys {
                   6919:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6921:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6922:    my $uhome=&homeserver($uname,$udomain);
                   6923:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6924:    my @keyarray=();
1.800     albertel 6925:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6926:       next if ($key =~ /^error: 2 /);
1.800     albertel 6927:       push(@keyarray,&unescape($key));
1.407     www      6928:    }
                   6929:    return @keyarray;
1.318     matthew  6930: }
                   6931: 
1.319     matthew  6932: # --------------------------------------------------------------- currentdump
                   6933: sub currentdump {
1.328     matthew  6934:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6935:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6936:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6937:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6938:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6939:    my $rep;
                   6940: 
                   6941:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6942:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6943:                    $courseid)));
                   6944:    } else {
                   6945:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6946:    }
                   6947: 
1.318     matthew  6948:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6949:    #
1.318     matthew  6950:    my %returnhash=();
1.319     matthew  6951:    #
                   6952:    if ($rep eq "unknown_cmd") { 
                   6953:        # an old lond will not know currentdump
                   6954:        # Do a dump and make it look like a currentdump
1.822     albertel 6955:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6956:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6957:        my %hash = @tmp;
                   6958:        @tmp=();
1.424     matthew  6959:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6960:    } else {
                   6961:        my @pairs=split(/\&/,$rep);
1.800     albertel 6962:        foreach my $pair (@pairs) {
                   6963:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6964:            my ($symb,$param) = split(/:/,$key);
                   6965:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6966:                                                         &thaw_unescape($value);
1.319     matthew  6967:        }
1.191     harris41 6968:    }
1.12      www      6969:    return %returnhash;
1.424     matthew  6970: }
                   6971: 
                   6972: sub convert_dump_to_currentdump{
                   6973:     my %hash = %{shift()};
                   6974:     my %returnhash;
                   6975:     # Code ripped from lond, essentially.  The only difference
                   6976:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6977:     # we might run in to problems with parameter names =~ /^v\./
                   6978:     while (my ($key,$value) = each(%hash)) {
                   6979:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6980: 	$symb  = &unescape($symb);
                   6981: 	$param = &unescape($param);
1.424     matthew  6982:         next if ($v eq 'version' || $symb eq 'keys');
                   6983:         next if (exists($returnhash{$symb}) &&
                   6984:                  exists($returnhash{$symb}->{$param}) &&
                   6985:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6986:         $returnhash{$symb}->{$param}=$value;
                   6987:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6988:     }
                   6989:     #
                   6990:     # Remove all of the keys in the hashes which keep track of
                   6991:     # the version of the parameter.
                   6992:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6993:         # use a foreach because we are going to delete from the hash.
                   6994:         foreach my $key (keys(%$param_hash)) {
                   6995:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6996:         }
                   6997:     }
                   6998:     return \%returnhash;
1.12      www      6999: }
                   7000: 
1.627     albertel 7001: # ------------------------------------------------------ critical inc interface
                   7002: 
                   7003: sub cinc {
                   7004:     return &inc(@_,'critical');
                   7005: }
                   7006: 
1.449     matthew  7007: # --------------------------------------------------------------- inc interface
                   7008: 
                   7009: sub inc {
1.627     albertel 7010:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7011:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7012:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7013:     my $uhome=&homeserver($uname,$udomain);
                   7014:     my $items='';
                   7015:     if (! ref($store)) {
                   7016:         # got a single value, so use that instead
                   7017:         $items = &escape($store).'=&';
                   7018:     } elsif (ref($store) eq 'SCALAR') {
                   7019:         $items = &escape($$store).'=&';        
                   7020:     } elsif (ref($store) eq 'ARRAY') {
                   7021:         $items = join('=&',map {&escape($_);} @{$store});
                   7022:     } elsif (ref($store) eq 'HASH') {
                   7023:         while (my($key,$value) = each(%{$store})) {
                   7024:             $items.= &escape($key).'='.&escape($value).'&';
                   7025:         }
                   7026:     }
                   7027:     $items=~s/\&$//;
1.627     albertel 7028:     if ($critical) {
                   7029: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7030:     } else {
                   7031: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7032:     }
1.449     matthew  7033: }
                   7034: 
1.12      www      7035: # --------------------------------------------------------------- put interface
                   7036: 
                   7037: sub put {
1.134     albertel 7038:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7040:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7041:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7042:    my $items='';
1.800     albertel 7043:    foreach my $item (keys(%$storehash)) {
                   7044:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7045:    }
1.12      www      7046:    $items=~s/\&$//;
1.134     albertel 7047:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7048: }
                   7049: 
1.631     albertel 7050: # ------------------------------------------------------------ newput interface
                   7051: 
                   7052: sub newput {
                   7053:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7055:    if (!$uname) { $uname=$env{'user.name'}; }
                   7056:    my $uhome=&homeserver($uname,$udomain);
                   7057:    my $items='';
                   7058:    foreach my $key (keys(%$storehash)) {
                   7059:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7060:    }
                   7061:    $items=~s/\&$//;
                   7062:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7063: }
                   7064: 
                   7065: # ---------------------------------------------------------  putstore interface
                   7066: 
1.524     raeburn  7067: sub putstore {
1.1172.2.59  raeburn  7068:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7070:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7071:    my $uhome=&homeserver($uname,$udomain);
                   7072:    my $items='';
1.715     albertel 7073:    foreach my $key (keys(%$storehash)) {
                   7074:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7075:    }
1.715     albertel 7076:    $items=~s/\&$//;
1.716     albertel 7077:    my $esc_symb=&escape($symb);
                   7078:    my $esc_v=&escape($version);
1.715     albertel 7079:    my $reply =
1.716     albertel 7080:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7081: 	      $uhome);
1.1172.2.59  raeburn  7082:    if (($tolog) && ($reply eq 'ok')) {
                   7083:        my $namevalue='';
                   7084:        foreach my $key (keys(%{$storehash})) {
                   7085:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7086:        }
1.1172.2.134  raeburn  7087:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7088:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7089:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7090:                      '&version='.$esc_v.
                   7091:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7092:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7093:    }
1.715     albertel 7094:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7095:        # gfall back to way things use to be done
1.715     albertel 7096:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7097: 			    $uname);
1.524     raeburn  7098:    }
1.715     albertel 7099:    return $reply;
                   7100: }
                   7101: 
                   7102: sub old_putstore {
1.716     albertel 7103:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7104:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7105:     if (!$uname) { $uname=$env{'user.name'}; }
                   7106:     my $uhome=&homeserver($uname,$udomain);
                   7107:     my %newstorehash;
1.800     albertel 7108:     foreach my $item (keys(%$storehash)) {
                   7109: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7110: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7111:     }
                   7112:     my $items='';
                   7113:     my %allitems = ();
1.800     albertel 7114:     foreach my $item (keys(%newstorehash)) {
                   7115: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7116: 	    my $key = $1.':keys:'.$2;
                   7117: 	    $allitems{$key} .= $3.':';
                   7118: 	}
1.800     albertel 7119: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7120:     }
1.800     albertel 7121:     foreach my $item (keys(%allitems)) {
                   7122: 	$allitems{$item} =~ s/\:$//;
                   7123: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7124:     }
                   7125:     $items=~s/\&$//;
                   7126:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7127: }
                   7128: 
1.47      www      7129: # ------------------------------------------------------ critical put interface
                   7130: 
                   7131: sub cput {
1.134     albertel 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7134:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7135:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7136:    my $items='';
1.800     albertel 7137:    foreach my $item (keys(%$storehash)) {
                   7138:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7139:    }
1.47      www      7140:    $items=~s/\&$//;
1.134     albertel 7141:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7142: }
                   7143: 
                   7144: # -------------------------------------------------------------- eget interface
                   7145: 
                   7146: sub eget {
1.133     albertel 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7148:    my $items='';
1.800     albertel 7149:    foreach my $item (@$storearr) {
                   7150:        $items.=&escape($item).'&';
1.191     harris41 7151:    }
1.12      www      7152:    $items=~s/\&$//;
1.620     albertel 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7155:    my $uhome=&homeserver($uname,$udomain);
                   7156:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7157:    my @pairs=split(/\&/,$rep);
                   7158:    my %returnhash=();
1.42      www      7159:    my $i=0;
1.800     albertel 7160:    foreach my $item (@$storearr) {
                   7161:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7162:       $i++;
1.191     harris41 7163:    }
1.12      www      7164:    return %returnhash;
                   7165: }
                   7166: 
1.667     albertel 7167: # ------------------------------------------------------------ tmpput interface
                   7168: sub tmpput {
1.802     raeburn  7169:     my ($storehash,$server,$context)=@_;
1.667     albertel 7170:     my $items='';
1.800     albertel 7171:     foreach my $item (keys(%$storehash)) {
                   7172: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7173:     }
                   7174:     $items=~s/\&$//;
1.802     raeburn  7175:     if (defined($context)) {
                   7176:         $items .= ':'.&escape($context);
                   7177:     }
1.667     albertel 7178:     return &reply("tmpput:$items",$server);
                   7179: }
                   7180: 
                   7181: # ------------------------------------------------------------ tmpget interface
                   7182: sub tmpget {
1.688     albertel 7183:     my ($token,$server)=@_;
                   7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7185:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7186:     my %returnhash;
1.1172.2.85  raeburn  7187:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7188:         return %returnhash;
                   7189:     }
1.667     albertel 7190:     foreach my $item (split(/\&/,$rep)) {
                   7191: 	my ($key,$value)=split(/=/,$item);
                   7192: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7193:     }
                   7194:     return %returnhash;
                   7195: }
                   7196: 
1.1113    raeburn  7197: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7198: sub tmpdel {
                   7199:     my ($token,$server)=@_;
                   7200:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7201:     return &reply("tmpdel:$token",$server);
                   7202: }
                   7203: 
1.1172.2.13  raeburn  7204: # ------------------------------------------------------------ get_timebased_id
                   7205: 
                   7206: sub get_timebased_id {
                   7207:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7208:         $maxtries) = @_;
                   7209:     my ($newid,$error,$dellock);
                   7210:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7211:         return ('','ok','invalid call to get suffix');
                   7212:     }
                   7213: 
                   7214: # set defaults for any optional args for which values were not supplied
                   7215:     if ($who eq '') {
                   7216:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7217:     }
                   7218:     if (!$locktries) {
                   7219:         $locktries = 3;
                   7220:     }
                   7221:     if (!$maxtries) {
                   7222:         $maxtries = 10;
                   7223:     }
                   7224: 
                   7225:     if (($cdom eq '') || ($cnum eq '')) {
                   7226:         if ($env{'request.course.id'}) {
                   7227:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7228:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7229:         }
                   7230:         if (($cdom eq '') || ($cnum eq '')) {
                   7231:             return ('','ok','call to get suffix not in course context');
                   7232:         }
                   7233:     }
                   7234: 
                   7235: # construct locking item
                   7236:     my $lockhash = {
                   7237:                       $prefix."\0".'locked_'.$keyid => $who,
                   7238:                    };
                   7239:     my $tries = 0;
                   7240: 
                   7241: # attempt to get lock on nohist_$namespace file
                   7242:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7243:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7244:         $tries ++;
                   7245:         sleep 1;
                   7246:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7247:     }
                   7248: 
                   7249: # attempt to get unique identifier, based on current timestamp
                   7250:     if ($gotlock eq 'ok') {
                   7251:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7252:         my $id = time;
                   7253:         $newid = $id;
1.1172.2.56  raeburn  7254:         if ($idtype eq 'addcode') {
                   7255:             $newid .= &sixnum_code();
                   7256:         }
1.1172.2.13  raeburn  7257:         my $idtries = 0;
                   7258:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7259:             if ($idtype eq 'concat') {
                   7260:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7261:             } elsif ($idtype eq 'addcode') {
                   7262:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7263:             } else {
                   7264:                 $newid ++;
                   7265:             }
                   7266:             $idtries ++;
                   7267:         }
                   7268:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7269:             my %new_item =  (
                   7270:                               $prefix."\0".$newid => $who,
                   7271:                             );
                   7272:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7273:                                                  $cdom,$cnum);
                   7274:             if ($putresult ne 'ok') {
                   7275:                 undef($newid);
                   7276:                 $error = 'error saving new item: '.$putresult;
                   7277:             }
                   7278:         } else {
1.1172.2.56  raeburn  7279:              undef($newid);
1.1172.2.13  raeburn  7280:              $error = ('error: no unique suffix available for the new item ');
                   7281:         }
                   7282: #  remove lock
                   7283:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7284:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7285:     } else {
                   7286:         $error = "error: could not obtain lockfile\n";
                   7287:         $dellock = 'ok';
1.1172.2.58  raeburn  7288:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7289:             $dellock = 'nolock';
                   7290:         }
1.1172.2.13  raeburn  7291:     }
                   7292:     return ($newid,$dellock,$error);
                   7293: }
                   7294: 
1.1172.2.56  raeburn  7295: sub sixnum_code {
                   7296:     my $code;
                   7297:     for (0..6) {
                   7298:         $code .= int( rand(9) );
                   7299:     }
                   7300:     return $code;
                   7301: }
                   7302: 
1.765     albertel 7303: # -------------------------------------------------- portfolio access checking
                   7304: 
                   7305: sub portfolio_access {
1.1172.2.77  raeburn  7306:     my ($requrl,$clientip) = @_;
1.765     albertel 7307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7309:     if ($result) {
                   7310:         my %setters;
                   7311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7312:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7313:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7314:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7315:                 return 'B';
                   7316:             }
                   7317:         } else {
1.1172.2.142  raeburn  7318:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7319:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7320:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7321:                 return 'B';
                   7322:             }
                   7323:         }
                   7324:     }
1.765     albertel 7325:     if ($result eq 'ok') {
1.766     albertel 7326:        return 'F';
1.765     albertel 7327:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7328:        return 'A';
1.765     albertel 7329:     }
1.766     albertel 7330:     return '';
1.765     albertel 7331: }
                   7332: 
                   7333: sub get_portfolio_access {
1.1172.2.77  raeburn  7334:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7335: 
                   7336:     if (!ref($access_hash)) {
                   7337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7338: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7339: 						   $file_name);
                   7340: 	$access_hash = $access_controls{$file_name};
                   7341:     }
                   7342: 
1.1172.2.77  raeburn  7343:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7344:     my $now = time;
                   7345:     if (ref($access_hash) eq 'HASH') {
                   7346:         foreach my $key (keys(%{$access_hash})) {
                   7347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7348:             if ($start > $now) {
                   7349:                 next;
                   7350:             }
                   7351:             if ($end && $end<$now) {
                   7352:                 next;
                   7353:             }
                   7354:             if ($scope eq 'public') {
                   7355:                 $public = $key;
                   7356:                 last;
                   7357:             } elsif ($scope eq 'guest') {
                   7358:                 $guest = $key;
                   7359:             } elsif ($scope eq 'domains') {
                   7360:                 push(@domains,$key);
                   7361:             } elsif ($scope eq 'users') {
                   7362:                 push(@users,$key);
                   7363:             } elsif ($scope eq 'course') {
                   7364:                 push(@courses,$key);
                   7365:             } elsif ($scope eq 'group') {
                   7366:                 push(@groups,$key);
1.1172.2.77  raeburn  7367:             } elsif ($scope eq 'ip') {
                   7368:                 push(@ips,$key);
1.765     albertel 7369:             }
                   7370:         }
                   7371:         if ($public) {
                   7372:             return 'ok';
1.1172.2.77  raeburn  7373:         } elsif (@ips > 0) {
                   7374:             my $allowed;
                   7375:             foreach my $ipkey (@ips) {
                   7376:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7377:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7378:                         $allowed = 1;
                   7379:                         last;
                   7380:                     }
                   7381:                 }
                   7382:             }
                   7383:             if ($allowed) {
                   7384:                 return 'ok';
                   7385:             }
1.765     albertel 7386:         }
                   7387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7388:             if ($guest) {
                   7389:                 return $guest;
                   7390:             }
                   7391:         } else {
                   7392:             if (@domains > 0) {
                   7393:                 foreach my $domkey (@domains) {
                   7394:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7395:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7396:                             return 'ok';
                   7397:                         }
                   7398:                     }
                   7399:                 }
                   7400:             }
                   7401:             if (@users > 0) {
                   7402:                 foreach my $userkey (@users) {
1.865     raeburn  7403:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7404:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7405:                             if (ref($item) eq 'HASH') {
                   7406:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7407:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7408:                                     return 'ok';
                   7409:                                 }
                   7410:                             }
                   7411:                         }
                   7412:                     } 
1.765     albertel 7413:                 }
                   7414:             }
                   7415:             my %roleshash;
                   7416:             my @courses_and_groups = @courses;
                   7417:             push(@courses_and_groups,@groups); 
                   7418:             if (@courses_and_groups > 0) {
                   7419:                 my (%allgroups,%allroles); 
                   7420:                 my ($start,$end,$role,$sec,$group);
                   7421:                 foreach my $envkey (%env) {
1.1060    raeburn  7422:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7423:                         my $cid = $2.'_'.$3; 
                   7424:                         if ($1 eq 'gr') {
                   7425:                             $group = $4;
                   7426:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7427:                         } else {
                   7428:                             if ($4 eq '') {
                   7429:                                 $sec = 'none';
                   7430:                             } else {
                   7431:                                 $sec = $4;
                   7432:                             }
                   7433:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7434:                         }
1.811     albertel 7435:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7436:                         my $cid = $2.'_'.$3;
                   7437:                         if ($4 eq '') {
                   7438:                             $sec = 'none';
                   7439:                         } else {
                   7440:                             $sec = $4;
                   7441:                         }
                   7442:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7443:                     }
                   7444:                 }
                   7445:                 if (keys(%allroles) == 0) {
                   7446:                     return;
                   7447:                 }
                   7448:                 foreach my $key (@courses_and_groups) {
                   7449:                     my %content = %{$$access_hash{$key}};
                   7450:                     my $cnum = $content{'number'};
                   7451:                     my $cdom = $content{'domain'};
                   7452:                     my $cid = $cdom.'_'.$cnum;
                   7453:                     if (!exists($allroles{$cid})) {
                   7454:                         next;
                   7455:                     }    
                   7456:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7457:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7458:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7459:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7460:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7461:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7462:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7463:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7464:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7465:                                         if (grep/^all$/,@sections) {
                   7466:                                             return 'ok';
                   7467:                                         } else {
                   7468:                                             if (grep/^$sec$/,@sections) {
                   7469:                                                 return 'ok';
                   7470:                                             }
                   7471:                                         }
                   7472:                                     }
                   7473:                                 }
                   7474:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7475:                                     if (grep/^none$/,@groups) {
                   7476:                                         return 'ok';
                   7477:                                     }
                   7478:                                 } else {
                   7479:                                     if (grep/^all$/,@groups) {
                   7480:                                         return 'ok';
                   7481:                                     } 
                   7482:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7483:                                         if (grep/^$group$/,@groups) {
                   7484:                                             return 'ok';
                   7485:                                         }
                   7486:                                     }
                   7487:                                 } 
                   7488:                             }
                   7489:                         }
                   7490:                     }
                   7491:                 }
                   7492:             }
                   7493:             if ($guest) {
                   7494:                 return $guest;
                   7495:             }
                   7496:         }
                   7497:     }
                   7498:     return;
                   7499: }
                   7500: 
                   7501: sub course_group_datechecker {
                   7502:     my ($dates,$now,$status) = @_;
                   7503:     my ($start,$end) = split(/\./,$dates);
                   7504:     if (!$start && !$end) {
                   7505:         return 'ok';
                   7506:     }
                   7507:     if (grep/^active$/,@{$status}) {
                   7508:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7509:             return 'ok';
                   7510:         }
                   7511:     }
                   7512:     if (grep/^previous$/,@{$status}) {
                   7513:         if ($end > $now ) {
                   7514:             return 'ok';
                   7515:         }
                   7516:     }
                   7517:     if (grep/^future$/,@{$status}) {
                   7518:         if ($start > $now) {
                   7519:             return 'ok';
                   7520:         }
                   7521:     }
                   7522:     return; 
                   7523: }
                   7524: 
                   7525: sub parse_portfolio_url {
                   7526:     my ($url) = @_;
                   7527: 
                   7528:     my ($type,$udom,$unum,$group,$file_name);
                   7529:     
1.823     albertel 7530:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7531: 	$type = 1;
                   7532:         $udom = $1;
                   7533:         $unum = $2;
                   7534:         $file_name = $3;
1.823     albertel 7535:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7536: 	$type = 2;
                   7537:         $udom = $1;
                   7538:         $unum = $2;
                   7539:         $group = $3;
                   7540:         $file_name = $3.'/'.$4;
                   7541:     }
                   7542:     if (wantarray) {
                   7543: 	return ($type,$udom,$unum,$file_name,$group);
                   7544:     }
                   7545:     return $type;
                   7546: }
                   7547: 
                   7548: sub is_portfolio_url {
                   7549:     my ($url) = @_;
                   7550:     return scalar(&parse_portfolio_url($url));
                   7551: }
                   7552: 
1.798     raeburn  7553: sub is_portfolio_file {
                   7554:     my ($file) = @_;
1.820     raeburn  7555:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7556:         return 1;
                   7557:     }
                   7558:     return;
                   7559: }
                   7560: 
1.976     raeburn  7561: sub usertools_access {
1.1084    raeburn  7562:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7563:     my ($access,%tools);
                   7564:     if ($context eq '') {
                   7565:         $context = 'tools';
                   7566:     }
                   7567:     if ($context eq 'requestcourses') {
                   7568:         %tools = (
                   7569:                       official   => 1,
                   7570:                       unofficial => 1,
1.1006    raeburn  7571:                       community  => 1,
1.1172.2.37  raeburn  7572:                       textbook   => 1,
1.985     raeburn  7573:                  );
1.1172.2.9  raeburn  7574:     } elsif ($context eq 'requestauthor') {
                   7575:         %tools = (
                   7576:                       requestauthor => 1,
                   7577:                  );
1.985     raeburn  7578:     } else {
                   7579:         %tools = (
                   7580:                       aboutme   => 1,
                   7581:                       blog      => 1,
1.1172.2.6  raeburn  7582:                       webdav    => 1,
1.985     raeburn  7583:                       portfolio => 1,
                   7584:                  );
                   7585:     }
1.976     raeburn  7586:     return if (!defined($tools{$tool}));
                   7587: 
1.1172.2.35  raeburn  7588:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7589:         $udom = $env{'user.domain'};
                   7590:         $uname = $env{'user.name'};
                   7591:     }
                   7592: 
1.978     raeburn  7593:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7594:         if ($action ne 'reload') {
1.985     raeburn  7595:             if ($context eq 'requestcourses') {
                   7596:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7597:             } elsif ($context eq 'requestauthor') {
                   7598:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7599:             } else {
                   7600:                 return $env{'environment.availabletools.'.$tool};
                   7601:             }
                   7602:         }
1.976     raeburn  7603:     }
                   7604: 
1.1172.2.9  raeburn  7605:     my ($toolstatus,$inststatus,$envkey);
                   7606:     if ($context eq 'requestauthor') {
                   7607:         $envkey = $context;
                   7608:     } else {
                   7609:         $envkey = $context.'.'.$tool;
                   7610:     }
1.976     raeburn  7611: 
1.985     raeburn  7612:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7613:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7614:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7615:         $inststatus = $env{'environment.inststatus'};
                   7616:     } else {
1.1084    raeburn  7617:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7618:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7619:             $inststatus = $userenvref->{'inststatus'};
                   7620:         } else {
1.1172.2.9  raeburn  7621:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7622:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7623:             $inststatus = $userenv{'inststatus'};
                   7624:         }
1.976     raeburn  7625:     }
                   7626: 
                   7627:     if ($toolstatus ne '') {
                   7628:         if ($toolstatus) {
                   7629:             $access = 1;
                   7630:         } else {
                   7631:             $access = 0;
                   7632:         }
                   7633:         return $access;
                   7634:     }
                   7635: 
1.1084    raeburn  7636:     my ($is_adv,%domdef);
                   7637:     if (ref($is_advref) eq 'HASH') {
                   7638:         $is_adv = $is_advref->{'is_adv'};
                   7639:     } else {
                   7640:         $is_adv = &is_advanced_user($udom,$uname);
                   7641:     }
                   7642:     if (ref($domdefref) eq 'HASH') {
                   7643:         %domdef = %{$domdefref};
                   7644:     } else {
                   7645:         %domdef = &get_domain_defaults($udom);
                   7646:     }
1.976     raeburn  7647:     if (ref($domdef{$tool}) eq 'HASH') {
                   7648:         if ($is_adv) {
                   7649:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7650:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7651:                     $access = 1;
                   7652:                 } else {
                   7653:                     $access = 0;
                   7654:                 }
                   7655:                 return $access;
                   7656:             }
                   7657:         }
                   7658:         if ($inststatus ne '') {
                   7659:             my ($hasaccess,$hasnoaccess);
                   7660:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7661:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7662:                     if ($domdef{$tool}{$affiliation}) {
                   7663:                         $hasaccess = 1;
                   7664:                     } else {
                   7665:                         $hasnoaccess = 1;
                   7666:                     }
                   7667:                 }
                   7668:             }
                   7669:             if ($hasaccess || $hasnoaccess) {
                   7670:                 if ($hasaccess) {
                   7671:                     $access = 1;
                   7672:                 } elsif ($hasnoaccess) {
                   7673:                     $access = 0; 
                   7674:                 }
                   7675:                 return $access;
                   7676:             }
                   7677:         } else {
                   7678:             if ($domdef{$tool}{'default'} ne '') {
                   7679:                 if ($domdef{$tool}{'default'}) {
                   7680:                     $access = 1;
                   7681:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7682:                     $access = 0;
                   7683:                 }
                   7684:                 return $access;
                   7685:             }
                   7686:         }
                   7687:     } else {
1.1172.2.6  raeburn  7688:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7689:             $access = 1;
                   7690:         } else {
                   7691:             $access = 0;
                   7692:         }
1.976     raeburn  7693:         return $access;
                   7694:     }
                   7695: }
                   7696: 
1.1050    raeburn  7697: sub is_course_owner {
                   7698:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7699:     if (($udom eq '') || ($uname eq '')) {
                   7700:         $udom = $env{'user.domain'};
                   7701:         $uname = $env{'user.name'};
                   7702:     }
                   7703:     unless (($udom eq '') || ($uname eq '')) {
                   7704:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7705:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7706:                 return 1;
                   7707:             } else {
                   7708:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7709:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7710:                     return 1;
                   7711:                 }
                   7712:             }
                   7713:         }
                   7714:     }
                   7715:     return;
                   7716: }
                   7717: 
1.976     raeburn  7718: sub is_advanced_user {
                   7719:     my ($udom,$uname) = @_;
1.1085    raeburn  7720:     if ($udom ne '' && $uname ne '') {
                   7721:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7722:             if (wantarray) {
                   7723:                 return ($env{'user.adv'},$env{'user.author'});
                   7724:             } else {
                   7725:                 return $env{'user.adv'};
                   7726:             }
1.1085    raeburn  7727:         }
                   7728:     }
1.976     raeburn  7729:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7730:     my %allroles;
1.1128    raeburn  7731:     my ($is_adv,$is_author);
1.976     raeburn  7732:     foreach my $role (keys(%roleshash)) {
                   7733:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7734:         my $area = '/'.$tdomain.'/'.$trest;
                   7735:         if ($sec ne '') {
                   7736:             $area .= '/'.$sec;
                   7737:         }
                   7738:         if (($area ne '') && ($trole ne '')) {
                   7739:             my $spec=$trole.'.'.$area;
                   7740:             if ($trole =~ /^cr\//) {
                   7741:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7742:             } elsif ($trole ne 'gr') {
                   7743:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7744:             }
1.1128    raeburn  7745:             if ($trole eq 'au') {
                   7746:                 $is_author = 1;
                   7747:             }
1.976     raeburn  7748:         }
                   7749:     }
                   7750:     foreach my $role (keys(%allroles)) {
                   7751:         last if ($is_adv);
                   7752:         foreach my $item (split(/:/,$allroles{$role})) {
                   7753:             if ($item ne '') {
                   7754:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7755:                 if ($privilege eq 'adv') {
                   7756:                     $is_adv = 1;
                   7757:                     last;
                   7758:                 }
                   7759:             }
                   7760:         }
                   7761:     }
1.1128    raeburn  7762:     if (wantarray) {
                   7763:         return ($is_adv,$is_author);
                   7764:     }
1.976     raeburn  7765:     return $is_adv;
                   7766: }
1.798     raeburn  7767: 
1.1035    raeburn  7768: sub check_can_request {
1.1036    raeburn  7769:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7770:     my $canreq = 0;
                   7771:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7772:     my @options = ('approval','validate','autolimit');
                   7773:     my $optregex = join('|',@options);
                   7774:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7775:         foreach my $type (@{$types}) {
                   7776:             if (&usertools_access($env{'user.name'},
                   7777:                                   $env{'user.domain'},
                   7778:                                   $type,undef,'requestcourses')) {
                   7779:                 $canreq ++;
1.1036    raeburn  7780:                 if (ref($request_domains) eq 'HASH') {
                   7781:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7782:                 }
1.1035    raeburn  7783:                 if ($dom eq $env{'user.domain'}) {
                   7784:                     $can_request->{$type} = 1;
                   7785:                 }
                   7786:             }
                   7787:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7788:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7789:                 if (@curr > 0) {
1.1036    raeburn  7790:                     foreach my $item (@curr) {
                   7791:                         if (ref($request_domains) eq 'HASH') {
                   7792:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7793:                             if ($otherdom ne '') {
                   7794:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7795:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7796:                                         push(@{$request_domains->{$type}},$otherdom);
                   7797:                                     }
                   7798:                                 } else {
                   7799:                                     push(@{$request_domains->{$type}},$otherdom);
                   7800:                                 }
                   7801:                             }
                   7802:                         }
                   7803:                     }
                   7804:                     unless($dom eq $env{'user.domain'}) {
                   7805:                         $canreq ++;
1.1035    raeburn  7806:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7807:                             $can_request->{$type} = 1;
                   7808:                         }
                   7809:                     }
                   7810:                 }
                   7811:             }
                   7812:         }
                   7813:     }
                   7814:     return $canreq;
                   7815: }
                   7816: 
1.341     www      7817: # ---------------------------------------------- Custom access rule evaluation
                   7818: 
                   7819: sub customaccess {
                   7820:     my ($priv,$uri)=@_;
1.807     albertel 7821:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7822:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7823:     $udom = &LONCAPA::clean_domain($udom);
                   7824:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7825:     my $access=0;
1.800     albertel 7826:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7827: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7828: 	if ($type eq 'user') {
                   7829: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7830: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7831: 		if ($tdom) {
                   7832: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7833: 		}
1.896     albertel 7834: 		if ($tuname) {
                   7835: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7836: 		}
                   7837: 		$access=($effect eq 'allow');
                   7838: 		last;
                   7839: 	    }
                   7840: 	} else {
                   7841: 	    if ($role) {
                   7842: 		if ($role ne $urole) { next; }
                   7843: 	    }
                   7844: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7845: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7846: 		if ($tdom) {
                   7847: 		    if ($tdom ne $udom) { next; }
                   7848: 		}
                   7849: 		if ($tcrs) {
                   7850: 		    if ($tcrs ne $ucrs) { next; }
                   7851: 		}
                   7852: 		if ($tsec) {
                   7853: 		    if ($tsec ne $usec) { next; }
                   7854: 		}
                   7855: 		$access=($effect eq 'allow');
                   7856: 		last;
                   7857: 	    }
                   7858: 	    if ($realm eq '' && $role eq '') {
                   7859: 		$access=($effect eq 'allow');
                   7860: 	    }
1.402     bowersj2 7861: 	}
1.341     www      7862:     }
                   7863:     return $access;
                   7864: }
                   7865: 
1.103     harris41 7866: # ------------------------------------------------- Check for a user privilege
1.12      www      7867: 
                   7868: sub allowed {
1.1172.2.126  raeburn  7869:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7870:     my $ver_orguri=$uri;
1.439     www      7871:     $uri=&deversion($uri);
1.152     www      7872:     my $orguri=$uri;
1.52      www      7873:     $uri=&declutter($uri);
1.809     raeburn  7874: 
1.810     raeburn  7875:     if ($priv eq 'evb') {
                   7876: # Evade communication block restrictions for specified role in a course
                   7877:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7878:             return $1;
                   7879:         } else {
                   7880:             return;
                   7881:         }
                   7882:     }
                   7883: 
1.620     albertel 7884:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7885: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7886:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7887: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7888: 	&& ($priv eq 'bre')) {
1.14      www      7889: 	return 'F';
1.159     www      7890:     }
                   7891: 
1.545     banghart 7892: # Free bre access to user's own portfolio contents
1.714     raeburn  7893:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7894:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7895: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7896:         my %setters;
1.1172.2.142  raeburn  7897:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   7898:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7899:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7900:             return 'B';
                   7901:         } else {
                   7902:             return 'F';
                   7903:         }
1.545     banghart 7904:     }
                   7905: 
1.762     raeburn  7906: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7907:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7908:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7909:         if (exists($env{'request.course.id'})) {
                   7910:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7911:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7912:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7913:                 my $courseprivid=$env{'request.course.id'};
                   7914:                 $courseprivid=~s/\_/\//;
                   7915:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7916:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7917:                     return $1; 
1.762     raeburn  7918:                 } else {
                   7919:                     if ($env{'request.course.sec'}) {
                   7920:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7921:                     }
                   7922:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7923:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7924:                         return $2;
                   7925:                     }
1.714     raeburn  7926:                 }
                   7927:             }
                   7928:         }
                   7929:     }
                   7930: 
1.159     www      7931: # Free bre to public access
                   7932: 
                   7933:     if ($priv eq 'bre') {
1.238     www      7934:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7935: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7936:            return 'F'; 
                   7937:         }
1.238     www      7938:         if ($copyright eq 'priv') {
                   7939:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7940: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7941: 		return '';
                   7942:             }
                   7943:         }
                   7944:         if ($copyright eq 'domain') {
                   7945:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7946: 	    unless (($env{'user.domain'} eq $1) ||
                   7947:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7948: 		return '';
                   7949:             }
1.262     matthew  7950:         }
1.620     albertel 7951:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7952:             # Library role, so allow browsing of resources in this domain.
                   7953:             return 'F';
1.238     www      7954:         }
1.341     www      7955:         if ($copyright eq 'custom') {
                   7956: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7957:         }
1.14      www      7958:     }
1.264     matthew  7959:     # Domain coordinator is trying to create a course
1.620     albertel 7960:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7961:         # uri is the requested domain in this case.
                   7962:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7963:         # a role of dc for the domain in question.
1.620     albertel 7964:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7965:     }
1.29      www      7966: 
1.52      www      7967:     my $thisallowed='';
                   7968:     my $statecond=0;
                   7969:     my $courseprivid='';
                   7970: 
1.1039    raeburn  7971:     my $ownaccess;
1.1043    raeburn  7972:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7973:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7974:         if ($uri eq '') {
                   7975:             $ownaccess = 1;
                   7976:         } else {
                   7977:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7978:                 my $udom = $env{'user.domain'};
                   7979:                 my $uname = $env{'user.name'};
                   7980:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7981:                     $ownaccess = 1;
1.1040    raeburn  7982:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7983:                     unless ($uri =~ m{\.\./}) {
                   7984:                         $ownaccess = 1;
                   7985:                     }
                   7986:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7987:                     my $now = time;
                   7988:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7989:                         my $adom = $1;
                   7990:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7991:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  7992:                                 my ($start,$end) = split(/\./,$env{$key});
                   7993:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  7994:                                     $ownaccess = 1;
                   7995:                                     last;
                   7996:                                 }
                   7997:                             }
                   7998:                         }
                   7999:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8000:                         my $adom = $1;
                   8001:                         my $aname = $2;
1.1042    raeburn  8002:                         foreach my $role ('ca','aa') { 
                   8003:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8004:                                 my ($start,$end) =
1.1172.2.142  raeburn  8005:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8006:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8007:                                     $ownaccess = 1;
                   8008:                                     last;
                   8009:                                 }
1.1039    raeburn  8010:                             }
                   8011:                         }
                   8012:                     }
                   8013:                 }
                   8014:             }
                   8015:         }
                   8016:     }
                   8017: 
1.52      www      8018: # Course
                   8019: 
1.620     albertel 8020:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8021:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8022:             $thisallowed.=$1;
                   8023:         }
1.52      www      8024:     }
1.29      www      8025: 
1.52      www      8026: # Domain
                   8027: 
1.620     albertel 8028:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8029:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8031:             $thisallowed.=$1;
                   8032:         }
1.12      www      8033:     }
1.52      www      8034: 
1.1141    raeburn  8035: # User who is not author or co-author might still be able to edit
                   8036: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8037:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8038:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8039:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8040:             $thisallowed.=$1;
                   8041:         }
                   8042:     }
                   8043: 
1.52      www      8044: # Course: uri itself is a course
1.66      www      8045:     my $courseuri=$uri;
                   8046:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8047:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8048: 
1.620     albertel 8049:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8050:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8051:         if ($priv eq 'mip') {
                   8052:             my $rem = $1;
                   8053:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8054:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8055:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8056:                 if ($cdom ne '') {
                   8057:                     my %passwdconf = &get_passwdconf($cdom);
                   8058:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8059:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8060:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8061:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8062:                                 unless (@inststatuses) {
                   8063:                                     @inststatuses = ('default');
                   8064:                                 }
                   8065:                                 foreach my $status (@inststatuses) {
                   8066:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8067:                                         $thisallowed.=$rem;
                   8068:                                     }
                   8069:                                 }
                   8070:                             }
                   8071:                         }
                   8072:                     }
                   8073:                 }
                   8074:             }
                   8075:         } else {
                   8076:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8077:                 $thisallowed.=$1;
                   8078:             }
1.1039    raeburn  8079:         }
1.12      www      8080:     }
1.29      www      8081: 
1.665     albertel 8082: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8083: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8084:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8085: 	$thisallowed='';
1.671     raeburn  8086:         my ($match)=&is_on_map($uri);
                   8087:         if ($match) {
                   8088:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8089:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8090:                 my $value = $1;
                   8091:                 if ($noblockcheck) {
                   8092:                     $thisallowed.=$value;
1.1162    raeburn  8093:                 } else {
1.1172.2.126  raeburn  8094:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8095:                     if (@blockers > 0) {
                   8096:                         $thisallowed = 'B';
                   8097:                     } else {
                   8098:                         $thisallowed.=$value;
                   8099:                     }
1.1162    raeburn  8100:                 }
1.671     raeburn  8101:             }
                   8102:         } else {
1.705     albertel 8103:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8104:             if ($refuri) {
                   8105:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8106:                     $thisallowed='F';
1.671     raeburn  8107:                 } else {
                   8108:                     $refuri=&declutter($refuri);
                   8109:                     my ($match) = &is_on_map($refuri);
                   8110:                     if ($match) {
1.1172.2.65  raeburn  8111:                         if ($noblockcheck) {
1.1162    raeburn  8112:                             $thisallowed='F';
1.1172.2.65  raeburn  8113:                         } else {
1.1172.2.127  raeburn  8114:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8115:                             if (@blockers > 0) {
                   8116:                                 $thisallowed = 'B';
                   8117:                             } else {
                   8118:                                 $thisallowed='F';
                   8119:                             }
1.1162    raeburn  8120:                         }
1.671     raeburn  8121:                     }
1.669     raeburn  8122:                 }
1.671     raeburn  8123:             }
                   8124:         }
1.314     www      8125:     }
1.492     albertel 8126: 
1.766     albertel 8127:     if ($priv eq 'bre'
                   8128: 	&& $thisallowed ne 'F' 
                   8129: 	&& $thisallowed ne '2'
                   8130: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8131: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8132:     }
                   8133:     
1.52      www      8134: # Full access at system, domain or course-wide level? Exit.
1.29      www      8135:     if ($thisallowed=~/F/) {
                   8136: 	return 'F';
                   8137:     }
                   8138: 
1.52      www      8139: # If this is generating or modifying users, exit with special codes
1.29      www      8140: 
1.643     www      8141:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8142: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8143: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8144: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8145: 	    unless ($auname) { return $thisallowed; }
                   8146: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8147: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8148: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8149: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8150: 	}
1.52      www      8151: 	return $thisallowed;
                   8152:     }
                   8153: #
1.103     harris41 8154: # Gathered so far: system, domain and course wide privileges
1.52      www      8155: #
                   8156: # Course: See if uri or referer is an individual resource that is part of 
                   8157: # the course
                   8158: 
1.620     albertel 8159:     if ($env{'request.course.id'}) {
1.232     www      8160: 
1.1172.2.115  raeburn  8161: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8162: 
                   8163:         if ($priv eq 'mip') {
                   8164:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8165:                 return $thisallowed;
                   8166:             } else {
                   8167:                 return '';
                   8168:             }
                   8169:         }
                   8170: 
1.620     albertel 8171:        $courseprivid=$env{'request.course.id'};
                   8172:        if ($env{'request.course.sec'}) {
                   8173:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8174:        }
                   8175:        $courseprivid=~s/\_/\//;
                   8176:        my $checkreferer=1;
1.232     www      8177:        my ($match,$cond)=&is_on_map($uri);
                   8178:        if ($match) {
                   8179:            $statecond=$cond;
1.620     albertel 8180:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8181:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8182:                my $value = $1;
                   8183:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8184:                    if ($noblockcheck) {
1.1162    raeburn  8185:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8186:                    } else {
1.1172.2.126  raeburn  8187:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8188:                        if (@blockers > 0) {
                   8189:                            $thisallowed = 'B';
                   8190:                        } else {
                   8191:                            $thisallowed.=$value;
                   8192:                        }
1.1162    raeburn  8193:                    }
                   8194:                } else {
                   8195:                    $thisallowed.=$value;
                   8196:                }
1.52      www      8197:                $checkreferer=0;
                   8198:            }
1.29      www      8199:        }
1.1172.2.126  raeburn  8200: 
1.148     www      8201:        if ($checkreferer) {
1.620     albertel 8202: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8203:             unless ($refuri) {
1.800     albertel 8204:                 foreach my $key (keys(%env)) {
                   8205: 		    if ($key=~/^httpref\..*\*/) {
                   8206: 			my $pattern=$key;
1.156     www      8207:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8208:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8209:                         $pattern=~s/\//\\\//g;
1.152     www      8210:                         if ($orguri=~/$pattern/) {
1.800     albertel 8211: 			    $refuri=$env{$key};
1.148     www      8212:                         }
                   8213:                     }
1.191     harris41 8214:                 }
1.148     www      8215:             }
1.232     www      8216: 
1.148     www      8217:          if ($refuri) { 
1.152     www      8218: 	  $refuri=&declutter($refuri);
1.232     www      8219:           my ($match,$cond)=&is_on_map($refuri);
                   8220:             if ($match) {
                   8221:               my $refstatecond=$cond;
1.620     albertel 8222:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8223:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8224:                   my $value = $1;
                   8225:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8226:                       if ($noblockcheck) {
1.1162    raeburn  8227:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8228:                       } else {
1.1172.2.127  raeburn  8229:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8230:                           if (@blockers > 0) {
                   8231:                               $thisallowed = 'B';
                   8232:                           } else {
                   8233:                               $thisallowed.=$value;
                   8234:                           }
1.1162    raeburn  8235:                       }
                   8236:                   } else {
                   8237:                       $thisallowed.=$value;
                   8238:                   }
1.53      www      8239:                   $uri=$refuri;
                   8240:                   $statecond=$refstatecond;
1.52      www      8241:               }
                   8242:           }
1.148     www      8243:         }
1.29      www      8244:        }
1.52      www      8245:    }
1.29      www      8246: 
1.52      www      8247: #
1.103     harris41 8248: # Gathered now: all privileges that could apply, and condition number
1.52      www      8249: # 
                   8250: #
                   8251: # Full or no access?
                   8252: #
1.29      www      8253: 
1.52      www      8254:     if ($thisallowed=~/F/) {
                   8255: 	return 'F';
                   8256:     }
1.29      www      8257: 
1.52      www      8258:     unless ($thisallowed) {
                   8259:         return '';
                   8260:     }
1.29      www      8261: 
1.52      www      8262: # Restrictions exist, deal with them
                   8263: #
                   8264: #   C:according to course preferences
                   8265: #   R:according to resource settings
                   8266: #   L:unless locked
                   8267: #   X:according to user session state
                   8268: #
                   8269: 
                   8270: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8271: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8272: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8273: # courses, and 2 minutes for current course, in which user has st or ta role
                   8274: # which is neither expired nor a future role (unless current course).
1.52      www      8275: 
1.1172.2.142  raeburn  8276:     my ($needlockcheck,$now,$crsonly);
1.52      www      8277:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8278:         $now = time;
                   8279:         if ($priv eq 'bre') {
                   8280:             if ($uri ne '') {
                   8281:                 if ($orguri =~ m{^/+res/}) {
                   8282:                     if ($uri =~ m{^lib/templates/}) {
                   8283:                         if ($env{'request.course.id'}) {
                   8284:                             $crsonly = 1;
                   8285:                             $needlockcheck = 1;
                   8286:                         }
                   8287:                     } else {
                   8288:                         $needlockcheck = 1;
                   8289:                     }
                   8290:                 } elsif ($env{'request.course.id'}) {
                   8291:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8292:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8293:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8294:                         $crsonly = 1;
                   8295:                     }
                   8296:                     $needlockcheck = 1;
                   8297:                 }
                   8298:             }
                   8299:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8300:             $needlockcheck = 1;
                   8301:         }
                   8302:     }
                   8303:     if ($needlockcheck) {
                   8304:         foreach my $envkey (keys(%env)) {
1.54      www      8305:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8306:                my $courseid=$2;
                   8307:                my $roleid=$1.'.'.$2;
1.92      www      8308:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8309:                unless ($env{'request.role'} eq $roleid) {
                   8310:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8311:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8312:                }
1.54      www      8313:                my $expiretime=600;
1.620     albertel 8314:                if ($env{'request.role'} eq $roleid) {
1.54      www      8315: 		  $expiretime=120;
                   8316:                }
                   8317: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8318:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8319:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8320: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8321:                }
1.620     albertel 8322:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8323:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8324: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8325:                        &log($env{'user.domain'},$env{'user.name'},
                   8326:                             $env{'user.home'},
1.57      www      8327:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8328:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8329:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8330: 		       return '';
                   8331:                    }
                   8332:                }
1.620     albertel 8333:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8334:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8335: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8336:                        &log($env{'user.domain'},$env{'user.name'},
                   8337:                             $env{'user.home'},
1.57      www      8338:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8339:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8340:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8341: 		       return '';
                   8342:                    }
                   8343:                }
                   8344: 	   }
1.29      www      8345:        }
1.52      www      8346:     }
1.1172.2.126  raeburn  8347: 
1.52      www      8348: #
                   8349: # Rest of the restrictions depend on selected course
                   8350: #
                   8351: 
1.620     albertel 8352:     unless ($env{'request.course.id'}) {
1.766     albertel 8353: 	if ($thisallowed eq 'A') {
                   8354: 	    return 'A';
1.814     raeburn  8355:         } elsif ($thisallowed eq 'B') {
                   8356:             return 'B';
1.766     albertel 8357: 	} else {
                   8358: 	    return '1';
                   8359: 	}
1.52      www      8360:     }
1.29      www      8361: 
1.52      www      8362: #
                   8363: # Now user is definitely in a course
                   8364: #
1.53      www      8365: 
                   8366: 
                   8367: # Course preferences
                   8368: 
                   8369:    if ($thisallowed=~/C/) {
1.620     albertel 8370:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8371:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8372:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8373: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8374: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8375: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8376: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8377: 			$env{'request.course.id'});
                   8378: 	   }
1.237     www      8379:            return '';
                   8380:        }
                   8381: 
1.620     albertel 8382:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8383: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8384: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8385: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8386: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8387: 			$env{'request.course.id'});
                   8388: 	   }
1.54      www      8389:            return '';
                   8390:        }
1.53      www      8391:    }
                   8392: 
                   8393: # Resource preferences
                   8394: 
                   8395:    if ($thisallowed=~/R/) {
1.620     albertel 8396:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8397:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8398: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8399: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8400: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8401: 	   }
                   8402: 	   return '';
1.54      www      8403:        }
1.53      www      8404:    }
1.30      www      8405: 
1.246     www      8406: # Restricted by state or randomout?
1.30      www      8407: 
1.52      www      8408:    if ($thisallowed=~/X/) {
1.620     albertel 8409:       if ($env{'acc.randomout'}) {
1.579     albertel 8410: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8411:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8412:             return ''; 
                   8413:          }
1.247     www      8414:       }
                   8415:       if (&condval($statecond)) {
1.52      www      8416: 	 return '2';
                   8417:       } else {
                   8418:          return '';
                   8419:       }
                   8420:    }
1.30      www      8421: 
1.766     albertel 8422:     if ($thisallowed eq 'A') {
                   8423: 	return 'A';
1.814     raeburn  8424:     } elsif ($thisallowed eq 'B') {
                   8425:         return 'B';
1.766     albertel 8426:     }
1.52      www      8427:    return 'F';
1.232     www      8428: }
1.1162    raeburn  8429: 
1.1172.2.13  raeburn  8430: # ------------------------------------------- Check construction space access
                   8431: 
                   8432: sub constructaccess {
                   8433:     my ($url,$setpriv)=@_;
                   8434: 
                   8435: # We do not allow editing of previous versions of files
                   8436:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8437: 
                   8438: # Get username and domain from URL
                   8439:     my ($ownername,$ownerdomain,$ownerhome);
                   8440: 
                   8441:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8442:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8443: 
                   8444: # The URL does not really point to any authorspace, forget it
                   8445:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8446: 
                   8447: # Now we need to see if the user has access to the authorspace of
                   8448: # $ownername at $ownerdomain
                   8449: 
                   8450:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8451: # Real author for this?
                   8452:        $ownerhome = $env{'user.home'};
                   8453:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8454:           return ($ownername,$ownerdomain,$ownerhome);
                   8455:        }
                   8456:     } else {
                   8457: # Co-author for this?
                   8458:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8459:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8460:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8461:             return ($ownername,$ownerdomain,$ownerhome);
                   8462:         }
                   8463:     }
                   8464: 
                   8465: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8466: # we might as well leave
                   8467:    unless ($setpriv) { return ''; }
                   8468: 
                   8469: # Backdoor access?
                   8470:     my $allowed=&allowed('eco',$ownerdomain);
                   8471: # Nope
                   8472:     unless ($allowed) { return ''; }
                   8473: # Looks like we may have access, but could be locked by the owner of the construction space
                   8474:     if ($allowed eq 'U') {
                   8475:         my %blocked=&get('environment',['domcoord.author'],
                   8476:                          $ownerdomain,$ownername);
                   8477: # Is blocked by owner
                   8478:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8479:     }
                   8480:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8481: # Grant temporary access
                   8482:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8483:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8484:         if (!$update) { $update = $then; }
                   8485:         my $refresh=$env{'user.refresh.time'};
                   8486:         if (!$refresh) { $refresh = $update; }
                   8487:         my $now = time;
                   8488:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8489:                            $now,'ca','constructaccess');
                   8490:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8491:         return($ownername,$ownerdomain,$ownerhome);
                   8492:     }
                   8493: # No business here
                   8494:     return '';
                   8495: }
                   8496: 
1.1172.2.66  raeburn  8497: # ----------------------------------------------------------- Content Blocking
                   8498: 
                   8499: {
                   8500: # Caches for faster Course Contents display where content blocking
                   8501: # is in operation (i.e., interval param set) for timed quiz.
                   8502: #
                   8503: # User for whom data are being temporarily cached.
                   8504: my $cacheduser='';
1.1172.2.126  raeburn  8505: # Course for which data are being temporarily cached.
                   8506: my $cachedcid='';
1.1172.2.66  raeburn  8507: # Cached blockers for this user (a hash of blocking items).
                   8508: my %cachedblockers=();
                   8509: # When the data were last cached.
                   8510: my $cachedlast='';
                   8511: 
                   8512: sub load_all_blockers {
1.1172.2.128  raeburn  8513:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8514:     if (($uname ne '') && ($udom ne '')) {
                   8515:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8516:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8517:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8518:             return;
                   8519:         }
                   8520:     }
                   8521:     $cachedlast=time;
                   8522:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8523:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8524:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8525:     return;
1.1172.2.66  raeburn  8526: }
                   8527: 
1.1162    raeburn  8528: sub get_comm_blocks {
                   8529:     my ($cdom,$cnum) = @_;
                   8530:     if ($cdom eq '' || $cnum eq '') {
                   8531:         return unless ($env{'request.course.id'});
                   8532:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8533:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8534:     }
                   8535:     my %commblocks;
                   8536:     my $hashid=$cdom.'_'.$cnum;
                   8537:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8538:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8539:         %commblocks = %{$blocksref};
                   8540:     } else {
                   8541:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8542:         my $cachetime = 600;
                   8543:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8544:     }
                   8545:     return %commblocks;
                   8546: }
                   8547: 
1.1172.2.66  raeburn  8548: sub get_commblock_resources {
                   8549:     my ($blocks) = @_;
                   8550:     my %blockers = ();
                   8551:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8552:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8553:     if ($env{'request.course.sec'}) {
                   8554:         $courseurl .= '/'.$env{'request.course.sec'};
                   8555:     }
                   8556:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8557:     my %commblocks;
                   8558:     if (ref($blocks) eq 'HASH') {
                   8559:         %commblocks = %{$blocks};
                   8560:     } else {
                   8561:         %commblocks = &get_comm_blocks();
                   8562:     }
1.1172.2.66  raeburn  8563:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8564:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8565:     return %blockers unless (ref($navmap));
                   8566:     my $now = time;
1.1162    raeburn  8567:     foreach my $block (keys(%commblocks)) {
                   8568:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8569:             my ($start,$end) = ($1,$2);
                   8570:             if ($start <= $now && $end >= $now) {
                   8571:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8572:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8573:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8574:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8575:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8576:                             }
                   8577:                         }
                   8578:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8579:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8580:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8581:                             }
                   8582:                         }
                   8583:                     }
                   8584:                 }
                   8585:             }
                   8586:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8587:             my $item = $1;
                   8588:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8589:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8590:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8591:                     my $type = 'map';
                   8592:                     if ($item eq 'course') {
                   8593:                         $type = 'course';
                   8594:                         @interval=&EXT("resource.0.interval");
                   8595:                     } else {
                   8596:                         if ($item =~ /___\d+___/) {
                   8597:                             $type = 'resource';
                   8598:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8599:                         } else {
1.1172.2.142  raeburn  8600:                             $mapname = &deversion($item);
                   8601:                             if (ref($navmap)) {
                   8602:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8603:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8604:                             }
                   8605:                         }
1.1172.2.66  raeburn  8606:                     }
                   8607:                     if ($interval[0] =~ /^\d+$/) {
                   8608:                         my $first_access;
                   8609:                         if ($type eq 'resource') {
                   8610:                             $first_access=&get_first_access($interval[1],$item);
                   8611:                         } elsif ($type eq 'map') {
                   8612:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8613:                         } else {
                   8614:                             $first_access=&get_first_access($interval[1]);
                   8615:                         }
                   8616:                         if ($first_access) {
                   8617:                             my $timesup = $first_access+$interval[0];
                   8618:                             if ($timesup > $now) {
                   8619:                                 my $activeblock;
1.1172.2.142  raeburn  8620:                                 if ($type eq 'resource') {
                   8621:                                     if (ref($navmap)) {
                   8622:                                         my $res = $navmap->getBySymb($item);
                   8623:                                         if ($res->answerable()) {
                   8624:                                             $activeblock = 1;
                   8625:                                         }
                   8626:                                     }
                   8627:                                 } elsif ($type eq 'map') {
                   8628:                                     my $mapsymb = &symbread($mapname,1);
                   8629:                                     if (($mapsymb) && (ref($navmap))) {
                   8630:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8631:                                         if (ref($mapres)) {
                   8632:                                             my $first = $mapres->map_start();
                   8633:                                             my $finish = $mapres->map_finish();
                   8634:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8635:                                             if (ref($it)) {
                   8636:                                                 my $res;
                   8637:                                                 while ($res = $it->next(undef,1)) {
                   8638:                                                     next unless (ref($res));
                   8639:                                                     my $symb = $res->symb();
                   8640:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8641:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8642:                                                     if ($interval[1] eq 'map') {
                   8643:                                                         if ($res->answerable()) {
                   8644:                                                             $activeblock = 1;
                   8645:                                                             last;
                   8646:                                                         }
                   8647:                                                     }
                   8648:                                                 }
                   8649:                                             }
                   8650:                                         }
1.1172.2.66  raeburn  8651:                                     }
                   8652:                                 }
                   8653:                                 if ($activeblock) {
                   8654:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8655:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8656:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8657:                                          }
                   8658:                                     }
                   8659:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8660:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8661:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8662:                                         }
1.1162    raeburn  8663:                                     }
                   8664:                                 }
                   8665:                             }
                   8666:                         }
                   8667:                     }
                   8668:                 }
                   8669:             }
                   8670:         }
                   8671:     }
1.1172.2.66  raeburn  8672:     return %blockers;
1.1162    raeburn  8673: }
                   8674: 
1.1172.2.66  raeburn  8675: sub has_comm_blocking {
1.1172.2.128  raeburn  8676:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8677:     my @blockers;
                   8678:     return unless ($env{'request.course.id'});
                   8679:     return unless ($priv eq 'bre');
                   8680:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8681:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8682:     if ($env{'request.course.sec'}) {
                   8683:         $courseurl .= '/'.$env{'request.course.sec'};
                   8684:     }
                   8685:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8686:     my %blockinfo;
                   8687:     if (ref($blocks) eq 'HASH') {
                   8688:         %blockinfo = &get_commblock_resources($blocks);
                   8689:     } else {
                   8690:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8691:         %blockinfo = %cachedblockers;
                   8692:     }
                   8693:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8694:     my (%possibles,@symbs);
                   8695:     if (!$symb) {
1.1172.2.128  raeburn  8696:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8697:     }
1.1172.2.66  raeburn  8698:     if ($symb) {
                   8699:         @symbs = ($symb);
                   8700:     } elsif (keys(%possibles)) {
                   8701:         @symbs = keys(%possibles);
                   8702:     }
                   8703:     my $noblock;
                   8704:     foreach my $symb (@symbs) {
                   8705:         last if ($noblock);
                   8706:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8707:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8708:             if ($block =~ /^firstaccess____(.+)$/) {
                   8709:                 my $item = $1;
1.1172.2.126  raeburn  8710:                 unless ($blocked) {
                   8711:                     if (($item eq $map) || ($item eq $symb)) {
                   8712:                         $noblock = 1;
                   8713:                         last;
                   8714:                     }
1.1172.2.66  raeburn  8715:                 }
1.1162    raeburn  8716:             }
1.1172.2.128  raeburn  8717:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8718:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8719:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8720:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8721:                             push(@blockers,$block);
                   8722:                         }
                   8723:                     }
                   8724:                 }
1.1172.2.128  raeburn  8725:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8726:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8727:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8728:                             push(@blockers,$block);
                   8729:                         }
1.1172.2.66  raeburn  8730:                     }
                   8731:                 }
1.1162    raeburn  8732:             }
                   8733:         }
                   8734:     }
1.1172.2.126  raeburn  8735:     unless ($noblock) {
                   8736:         return @blockers;
                   8737:     }
                   8738:     return;
1.1172.2.66  raeburn  8739: }
1.1162    raeburn  8740: }
                   8741: 
1.1172.2.66  raeburn  8742: # -------------------------------- Deversion and split uri into path an filename
                   8743: 
1.1133    foxr     8744: #
1.1172.2.66  raeburn  8745: #   Removes the version from a URI and
1.1133    foxr     8746: #   splits it in to its filename and path to the filename.
                   8747: #   Seems like File::Basename could have done this more clearly.
                   8748: #   Parameters:
                   8749: #      $uri   - input URI
                   8750: #   Returns:
                   8751: #     Two element list consisting of 
                   8752: #     $pathname  - the URI up to and excluding the trailing /
                   8753: #     $filename  - The part of the URI following the last /
                   8754: #  NOTE:
                   8755: #    Another realization of this is simply:
                   8756: #    use File::Basename;
                   8757: #    ...
                   8758: #    $uri = shift;
                   8759: #    $filename = basename($uri);
                   8760: #    $path     = dirname($uri);
                   8761: #    return ($filename, $path);
                   8762: #
                   8763: #     The implementation below is probably faster however.
                   8764: #
1.710     albertel 8765: sub split_uri_for_cond {
                   8766:     my $uri=&deversion(&declutter(shift));
                   8767:     my @uriparts=split(/\//,$uri);
                   8768:     my $filename=pop(@uriparts);
                   8769:     my $pathname=join('/',@uriparts);
                   8770:     return ($pathname,$filename);
                   8771: }
1.232     www      8772: # --------------------------------------------------- Is a resource on the map?
                   8773: 
                   8774: sub is_on_map {
1.710     albertel 8775:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8776:     #Trying to find the conditional for the file
1.620     albertel 8777:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8778: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8779:     if ($match) {
1.289     bowersj2 8780: 	return (1,$1);
                   8781:     } else {
1.434     www      8782: 	return (0,0);
1.289     bowersj2 8783:     }
1.12      www      8784: }
                   8785: 
1.427     www      8786: # --------------------------------------------------------- Get symb from alias
                   8787: 
                   8788: sub get_symb_from_alias {
                   8789:     my $symb=shift;
                   8790:     my ($map,$resid,$url)=&decode_symb($symb);
                   8791: # Already is a symb
                   8792:     if ($url) { return $symb; }
                   8793: # Must be an alias
                   8794:     my $aliassymb='';
                   8795:     my %bighash;
1.620     albertel 8796:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8797:                             &GDBM_READER(),0640)) {
                   8798:         my $rid=$bighash{'mapalias_'.$symb};
                   8799: 	if ($rid) {
                   8800: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8801: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8802: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8803: 	}
                   8804:         untie %bighash;
                   8805:     }
                   8806:     return $aliassymb;
                   8807: }
                   8808: 
1.12      www      8809: # ----------------------------------------------------------------- Define Role
                   8810: 
                   8811: sub definerole {
                   8812:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8813:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8814:     foreach my $role (split(':',$sysrole)) {
                   8815: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8816:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8817:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8818: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8819:                return "refused:s:$crole&$cqual"; 
                   8820:             }
                   8821:         }
1.191     harris41 8822:     }
1.800     albertel 8823:     foreach my $role (split(':',$domrole)) {
                   8824: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8825:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8826:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8827: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8828:                return "refused:d:$crole&$cqual"; 
                   8829:             }
                   8830:         }
1.191     harris41 8831:     }
1.800     albertel 8832:     foreach my $role (split(':',$courole)) {
                   8833: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8834:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8835:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8836: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8837:                return "refused:c:$crole&$cqual"; 
                   8838:             }
                   8839:         }
1.191     harris41 8840:     }
1.1172.2.84  raeburn  8841:     my $uhome;
                   8842:     if (($uname ne '') && ($udom ne '')) {
                   8843:         $uhome = &homeserver($uname,$udom);
                   8844:         return $uhome if ($uhome eq 'no_host');
                   8845:     } else {
                   8846:         $uname = $env{'user.name'};
                   8847:         $udom = $env{'user.domain'};
                   8848:         $uhome = $env{'user.home'};
                   8849:     }
1.620     albertel 8850:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8851:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8852:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8853:     return reply($command,$uhome);
1.12      www      8854:   } else {
                   8855:     return 'refused';
                   8856:   }
1.105     harris41 8857: }
                   8858: 
                   8859: # ---------------- Make a metadata query against the network of library servers
                   8860: 
                   8861: sub metadata_query {
1.1172.2.33  raeburn  8862:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8863:     my %rhash;
1.845     albertel 8864:     my %libserv = &all_library();
1.244     matthew  8865:     my @server_list = (defined($server_array) ? @$server_array
                   8866:                                               : keys(%libserv) );
                   8867:     for my $server (@server_list) {
1.1172.2.33  raeburn  8868:         my $domains = '';
                   8869:         if (ref($domains_hash) eq 'HASH') {
                   8870:             $domains = $domains_hash->{$server};    
                   8871:         }
1.118     harris41 8872: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8873: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8874: 	    $rhash{$server}=$reply;
                   8875: 	}
                   8876: 	else {
                   8877: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8878: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8879: 			     $server);
                   8880: 	    $rhash{$server}=$reply;
                   8881: 	}
1.112     harris41 8882:     }
1.118     harris41 8883:     return \%rhash;
1.240     www      8884: }
                   8885: 
                   8886: # ----------------------------------------- Send log queries and wait for reply
                   8887: 
                   8888: sub log_query {
                   8889:     my ($uname,$udom,$query,%filters)=@_;
                   8890:     my $uhome=&homeserver($uname,$udom);
                   8891:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8892:     my $uhost=&hostname($uhome);
1.800     albertel 8893:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8894:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8895:                        $uhome);
1.479     albertel 8896:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8897:     return get_query_reply($queryid);
                   8898: }
                   8899: 
1.818     raeburn  8900: # -------------------------- Update MySQL table for portfolio file
                   8901: 
                   8902: sub update_portfolio_table {
1.821     raeburn  8903:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8904:     if ($group ne '') {
                   8905:         $file_name =~s /^\Q$group\E//;
                   8906:     }
1.818     raeburn  8907:     my $homeserver = &homeserver($uname,$udom);
                   8908:     my $queryid=
1.821     raeburn  8909:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8910:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8911:     my $reply = &get_query_reply($queryid);
                   8912:     return $reply;
                   8913: }
                   8914: 
1.899     raeburn  8915: # -------------------------- Update MySQL allusers table
                   8916: 
                   8917: sub update_allusers_table {
                   8918:     my ($uname,$udom,$names) = @_;
                   8919:     my $homeserver = &homeserver($uname,$udom);
                   8920:     my $queryid=
                   8921:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8922:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8923:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8924:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8925:                'generation='.&escape($names->{'generation'}).'%%'.
                   8926:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8927:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8928:     return;
1.899     raeburn  8929: }
                   8930: 
1.508     raeburn  8931: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8932: 
                   8933: sub fetch_enrollment_query {
1.511     raeburn  8934:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8935:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8936:     my $maxtries = 1;
1.508     raeburn  8937:     if ($context eq 'automated') {
                   8938:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8939:         $sleep = 2;
                   8940:         $loopmax = 100;
1.547     raeburn  8941:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8942:     } else {
                   8943:         $homeserver = &homeserver($cnum,$dom);
                   8944:     }
1.838     albertel 8945:     my $host=&hostname($homeserver);
1.506     raeburn  8946:     my $cmd = '';
1.1000    raeburn  8947:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8948:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8949:     }
                   8950:     $cmd =~ s/%%$//;
                   8951:     $cmd = &escape($cmd);
                   8952:     my $query = 'fetchenrollment';
1.620     albertel 8953:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8954:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8955:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8956:         return 'error: '.$queryid;
                   8957:     }
1.1172.2.93  raeburn  8958:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8959:     my $tries = 1;
                   8960:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8961:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8962:         $tries ++;
                   8963:     }
1.526     raeburn  8964:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8965:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8966:     } else {
1.901     albertel 8967:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8968:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8969:             foreach my $line (@responses) {
                   8970:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8971:                 $$replyref{$key} = $value;
                   8972:             }
                   8973:         } else {
1.1117    foxr     8974:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8975:             foreach my $line (@responses) {
                   8976:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8977:                 $$replyref{$key} = $value;
                   8978:                 if ($value > 0) {
1.800     albertel 8979:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8980:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8981:                         my $destname = $pathname.'/'.$filename;
                   8982:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8983:                         if ($xml_classlist =~ /^error/) {
                   8984:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8985:                         } else {
1.1172.2.96  raeburn  8986:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8987:                                 print FILE &unescape($xml_classlist);
                   8988:                                 close(FILE);
1.526     raeburn  8989:                             } else {
                   8990:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8991:                             }
                   8992:                         }
                   8993:                     }
                   8994:                 }
                   8995:             }
                   8996:         }
                   8997:         return 'ok';
                   8998:     }
                   8999:     return 'error';
                   9000: }
                   9001: 
1.242     www      9002: sub get_query_reply {
1.1172.2.79  raeburn  9003:     my ($queryid,$sleep,$loopmax) = @_;
                   9004:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9005:         $sleep = 0.2;
                   9006:     }
                   9007:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9008:         $loopmax = 100;
                   9009:     }
1.1117    foxr     9010:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9011:     my $reply='';
1.1172.2.79  raeburn  9012:     for (1..$loopmax) {
                   9013: 	sleep($sleep);
1.240     www      9014:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9015: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9016: 		$reply = join('',<$fh>);
                   9017: 		close($fh);
1.240     www      9018: 	   } else { return 'error: reply_file_error'; }
1.242     www      9019:            return &unescape($reply);
                   9020: 	}
1.240     www      9021:     }
1.242     www      9022:     return 'timeout:'.$queryid;
1.240     www      9023: }
                   9024: 
                   9025: sub courselog_query {
1.241     www      9026: #
                   9027: # possible filters:
                   9028: # url: url or symb
                   9029: # username
                   9030: # domain
                   9031: # action: view, submit, grade
                   9032: # start: timestamp
                   9033: # end: timestamp
                   9034: #
1.240     www      9035:     my (%filters)=@_;
1.620     albertel 9036:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9037:     if ($filters{'url'}) {
                   9038: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9039:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9040:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9041:     }
1.620     albertel 9042:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9043:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9044:     return &log_query($cname,$cdom,'courselog',%filters);
                   9045: }
                   9046: 
                   9047: sub userlog_query {
1.858     raeburn  9048: #
                   9049: # possible filters:
                   9050: # action: log check role
                   9051: # start: timestamp
                   9052: # end: timestamp
                   9053: #
1.240     www      9054:     my ($uname,$udom,%filters)=@_;
                   9055:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9056: }
                   9057: 
1.506     raeburn  9058: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9059: 
                   9060: sub auto_run {
1.508     raeburn  9061:     my ($cnum,$cdom) = @_;
1.876     raeburn  9062:     my $response = 0;
                   9063:     my $settings;
                   9064:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9065:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9066:         $settings = $domconfig{'autoenroll'};
                   9067:         if ($settings->{'run'} eq '1') {
                   9068:             $response = 1;
                   9069:         }
                   9070:     } else {
1.934     raeburn  9071:         my $homeserver;
                   9072:         if (&is_course($cdom,$cnum)) {
                   9073:             $homeserver = &homeserver($cnum,$cdom);
                   9074:         } else {
                   9075:             $homeserver = &domain($cdom,'primary');
                   9076:         }
                   9077:         if ($homeserver ne 'no_host') {
                   9078:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9079:         }
1.876     raeburn  9080:     }
1.506     raeburn  9081:     return $response;
                   9082: }
1.776     albertel 9083: 
1.506     raeburn  9084: sub auto_get_sections {
1.508     raeburn  9085:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9086:     my $homeserver;
                   9087:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9088:         $homeserver = &homeserver($cnum,$cdom);
                   9089:     }
                   9090:     if (!defined($homeserver)) { 
                   9091:         if ($cdom =~ /^$match_domain$/) {
                   9092:             $homeserver = &domain($cdom,'primary');
                   9093:         }
                   9094:     }
                   9095:     my @secs;
                   9096:     if (defined($homeserver)) {
                   9097:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9098:         unless ($response eq 'refused') {
                   9099:             @secs = split(/:/,$response);
                   9100:         }
1.506     raeburn  9101:     }
                   9102:     return @secs;
                   9103: }
1.776     albertel 9104: 
1.506     raeburn  9105: sub auto_new_course {
1.1099    raeburn  9106:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9107:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9108:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9109:     return $response;
                   9110: }
1.776     albertel 9111: 
1.506     raeburn  9112: sub auto_validate_courseID {
1.508     raeburn  9113:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9114:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9115:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9116:     return $response;
                   9117: }
1.776     albertel 9118: 
1.1007    raeburn  9119: sub auto_validate_instcode {
1.1020    raeburn  9120:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9121:     my ($homeserver,$response);
                   9122:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9123:         $homeserver = &homeserver($cnum,$cdom);
                   9124:     }
                   9125:     if (!defined($homeserver)) {
                   9126:         if ($cdom =~ /^$match_domain$/) {
                   9127:             $homeserver = &domain($cdom,'primary');
                   9128:         }
                   9129:     }
1.1065    raeburn  9130:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9131:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9132:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9133:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9134: }
                   9135: 
1.1172.2.141  raeburn  9136: sub auto_validate_inst_crosslist {
                   9137:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9138:     my ($homeserver,$response);
                   9139:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9140:         $homeserver = &homeserver($cnum,$cdom);
                   9141:     }
                   9142:     if (!defined($homeserver)) {
                   9143:         if ($cdom =~ /^$match_domain$/) {
                   9144:             $homeserver = &domain($cdom,'primary');
                   9145:         }
                   9146:     }
                   9147:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9148:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9149:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9150:                          &escape($coowner),$homeserver);
                   9151:     }
                   9152:     return $response;
                   9153: }
                   9154: 
1.506     raeburn  9155: sub auto_create_password {
1.873     raeburn  9156:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9157:     my ($homeserver,$response);
1.506     raeburn  9158:     my $create_passwd = 0;
                   9159:     my $authchk = '';
1.873     raeburn  9160:     if ($udom =~ /^$match_domain$/) {
                   9161:         $homeserver = &domain($udom,'primary');
                   9162:     }
                   9163:     if ($homeserver eq '') {
                   9164:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9165:             $homeserver = &homeserver($cnum,$cdom);
                   9166:         }
                   9167:     }
                   9168:     if ($homeserver eq '') {
                   9169:         $authchk = 'nodomain';
1.506     raeburn  9170:     } else {
1.873     raeburn  9171:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9172:         if ($response eq 'refused') {
                   9173:             $authchk = 'refused';
                   9174:         } else {
1.901     albertel 9175:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9176:         }
1.506     raeburn  9177:     }
                   9178:     return ($authparam,$create_passwd,$authchk);
                   9179: }
                   9180: 
1.706     raeburn  9181: sub auto_photo_permission {
                   9182:     my ($cnum,$cdom,$students) = @_;
                   9183:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9184:     my ($outcome,$perm_reqd,$conditions) = 
                   9185: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9186:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9187: 	return (undef,undef);
                   9188:     }
1.706     raeburn  9189:     return ($outcome,$perm_reqd,$conditions);
                   9190: }
                   9191: 
                   9192: sub auto_checkphotos {
                   9193:     my ($uname,$udom,$pid) = @_;
                   9194:     my $homeserver = &homeserver($uname,$udom);
                   9195:     my ($result,$resulttype);
                   9196:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9197: 				   &escape($uname).':'.&escape($pid),
                   9198: 				   $homeserver));
1.709     albertel 9199:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9200: 	return (undef,undef);
                   9201:     }
1.706     raeburn  9202:     if ($outcome) {
                   9203:         ($result,$resulttype) = split(/:/,$outcome);
                   9204:     } 
                   9205:     return ($result,$resulttype);
                   9206: }
                   9207: 
                   9208: sub auto_photochoice {
                   9209:     my ($cnum,$cdom) = @_;
                   9210:     my $homeserver = &homeserver($cnum,$cdom);
                   9211:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9212: 						       &escape($cdom),
                   9213: 						       $homeserver)));
1.709     albertel 9214:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9215: 	return (undef,undef);
                   9216:     }
1.706     raeburn  9217:     return ($update,$comment);
                   9218: }
                   9219: 
                   9220: sub auto_photoupdate {
                   9221:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9222:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9223:     my $host=&hostname($homeserver);
1.706     raeburn  9224:     my $cmd = '';
                   9225:     my $maxtries = 1;
1.800     albertel 9226:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9227:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9228:     }
                   9229:     $cmd =~ s/%%$//;
                   9230:     $cmd = &escape($cmd);
                   9231:     my $query = 'institutionalphotos';
                   9232:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9233:     unless ($queryid=~/^\Q$host\E\_/) {
                   9234:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9235:         return 'error: '.$queryid;
                   9236:     }
                   9237:     my $reply = &get_query_reply($queryid);
                   9238:     my $tries = 1;
                   9239:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9240:         $reply = &get_query_reply($queryid);
                   9241:         $tries ++;
                   9242:     }
                   9243:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9244:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9245:     } else {
                   9246:         my @responses = split(/:/,$reply);
                   9247:         my $outcome = shift(@responses); 
                   9248:         foreach my $item (@responses) {
                   9249:             my ($key,$value) = split(/=/,$item);
                   9250:             $$photo{$key} = $value;
                   9251:         }
                   9252:         return $outcome;
                   9253:     }
                   9254:     return 'error';
                   9255: }
                   9256: 
1.521     raeburn  9257: sub auto_instcode_format {
1.793     albertel 9258:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9259: 	$cat_order) = @_;
1.521     raeburn  9260:     my $courses = '';
1.772     raeburn  9261:     my @homeservers;
1.521     raeburn  9262:     if ($caller eq 'global') {
1.841     albertel 9263: 	my %servers = &get_servers($codedom,'library');
                   9264: 	foreach my $tryserver (keys(%servers)) {
                   9265: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9266: 		push(@homeservers,$tryserver);
                   9267: 	    }
1.584     raeburn  9268:         }
1.1022    raeburn  9269:     } elsif ($caller eq 'requests') {
                   9270:         if ($codedom =~ /^$match_domain$/) {
                   9271:             my $chome = &domain($codedom,'primary');
                   9272:             unless ($chome eq 'no_host') {
                   9273:                 push(@homeservers,$chome);
                   9274:             }
                   9275:         }
1.521     raeburn  9276:     } else {
1.772     raeburn  9277:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9278:     }
1.793     albertel 9279:     foreach my $code (keys(%{$instcodes})) {
                   9280:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9281:     }
                   9282:     chop($courses);
1.772     raeburn  9283:     my $ok_response = 0;
                   9284:     my $response;
                   9285:     while (@homeservers > 0 && $ok_response == 0) {
                   9286:         my $server = shift(@homeservers); 
                   9287:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9288:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9289:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9290: 		split(/:/,$response);
1.772     raeburn  9291:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9292:             push(@{$codetitles},&str2array($codetitles_str));
                   9293:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9294:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9295:             $ok_response = 1;
                   9296:         }
                   9297:     }
                   9298:     if ($ok_response) {
1.521     raeburn  9299:         return 'ok';
1.772     raeburn  9300:     } else {
                   9301:         return $response;
1.521     raeburn  9302:     }
                   9303: }
                   9304: 
1.792     raeburn  9305: sub auto_instcode_defaults {
                   9306:     my ($domain,$returnhash,$code_order) = @_;
                   9307:     my @homeservers;
1.841     albertel 9308: 
                   9309:     my %servers = &get_servers($domain,'library');
                   9310:     foreach my $tryserver (keys(%servers)) {
                   9311: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9312: 	    push(@homeservers,$tryserver);
                   9313: 	}
1.792     raeburn  9314:     }
1.841     albertel 9315: 
1.792     raeburn  9316:     my $response;
1.841     albertel 9317:     foreach my $server (@homeservers) {
1.792     raeburn  9318:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9319:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9320: 	
                   9321: 	foreach my $pair (split(/\&/,$response)) {
                   9322: 	    my ($name,$value)=split(/\=/,$pair);
                   9323: 	    if ($name eq 'code_order') {
                   9324: 		@{$code_order} = split(/\&/,&unescape($value));
                   9325: 	    } else {
                   9326: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9327: 	    }
                   9328: 	}
                   9329: 	return 'ok';
1.792     raeburn  9330:     }
1.841     albertel 9331: 
                   9332:     return $response;
1.1003    raeburn  9333: }
                   9334: 
                   9335: sub auto_possible_instcodes {
1.1007    raeburn  9336:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9337:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9338:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9339:         return;
                   9340:     }
1.1003    raeburn  9341:     my (@homeservers,$uhome);
                   9342:     if (defined(&domain($domain,'primary'))) {
                   9343:         $uhome=&domain($domain,'primary');
                   9344:         push(@homeservers,&domain($domain,'primary'));
                   9345:     } else {
                   9346:         my %servers = &get_servers($domain,'library');
                   9347:         foreach my $tryserver (keys(%servers)) {
                   9348:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9349:                 push(@homeservers,$tryserver);
                   9350:             }
                   9351:         }
                   9352:     }
                   9353:     my $response;
                   9354:     foreach my $server (@homeservers) {
                   9355:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9356:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9357:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9358:             split(':',$response);
                   9359:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9360:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9361:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9362:             my ($name,$value)=split('=',$item);
                   9363:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9364:         }
                   9365:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9366:             my ($name,$value)=split('=',$item);
                   9367:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9368:         }
                   9369:         return 'ok';
                   9370:     }
                   9371:     return $response;
                   9372: }
1.792     raeburn  9373: 
1.1010    raeburn  9374: sub auto_courserequest_checks {
                   9375:     my ($dom) = @_;
1.1020    raeburn  9376:     my ($homeserver,%validations);
                   9377:     if ($dom =~ /^$match_domain$/) {
                   9378:         $homeserver = &domain($dom,'primary');
                   9379:     }
                   9380:     unless ($homeserver eq 'no_host') {
                   9381:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9382:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9383:             my @items = split(/&/,$response);
                   9384:             foreach my $item (@items) {
                   9385:                 my ($key,$value) = split('=',$item);
                   9386:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9387:             }
                   9388:         }
                   9389:     }
1.1010    raeburn  9390:     return %validations; 
                   9391: }
                   9392: 
1.1020    raeburn  9393: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9394:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9395:     my ($homeserver,$response);
                   9396:     if ($dom =~ /^$match_domain$/) {
                   9397:         $homeserver = &domain($dom,'primary');
                   9398:     }
1.1172.2.43  raeburn  9399:     unless ($homeserver eq 'no_host') {
                   9400:         my $customdata;
                   9401:         if (ref($custominfo) eq 'HASH') {
                   9402:             $customdata = &freeze_escape($custominfo);
                   9403:         }
1.1020    raeburn  9404:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9405:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9406:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9407:                                     $customdata,$homeserver));
1.1020    raeburn  9408:     }
                   9409:     return $response;
                   9410: }
                   9411: 
1.777     albertel 9412: sub auto_validate_class_sec {
1.918     raeburn  9413:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9414:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9415:     my $ownerlist;
                   9416:     if (ref($owners) eq 'ARRAY') {
                   9417:         $ownerlist = join(',',@{$owners});
                   9418:     } else {
                   9419:         $ownerlist = $owners;
                   9420:     }
1.773     raeburn  9421:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9422:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9423:     return $response;
                   9424: }
                   9425: 
1.1172.2.141  raeburn  9426: sub auto_instsec_reformat {
                   9427:     my ($cdom,$action,$instsecref) = @_;
                   9428:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9429:     my @homeservers;
                   9430:     if (defined(&domain($cdom,'primary'))) {
                   9431:         push(@homeservers,&domain($cdom,'primary'));
                   9432:     } else {
                   9433:         my %servers = &get_servers($cdom,'library');
                   9434:         foreach my $tryserver (keys(%servers)) {
                   9435:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9436:                 push(@homeservers,$tryserver);
                   9437:             }
                   9438:         }
                   9439:     }
                   9440:     my $response;
                   9441:     my %reformatted = %{$instsecref};
                   9442:     foreach my $server (@homeservers) {
                   9443:         if (ref($instsecref) eq 'HASH') {
                   9444:             my $info = &freeze_escape($instsecref);
                   9445:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9446:                                 $action.':'.$info,$server);
                   9447:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9448:             my @items = split(/&/,$response);
                   9449:             foreach my $item (@items) {
                   9450:                 my ($key,$value) = split(/=/,$item);
                   9451:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9452:             }
                   9453:         }
                   9454:     }
                   9455:     return %reformatted;
                   9456: }
                   9457: 
1.1172.2.94  raeburn  9458: sub auto_validate_instclasses {
                   9459:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9460:     my ($homeserver,%validations);
                   9461:     $homeserver = &homeserver($cnum,$cdom);
                   9462:     unless ($homeserver eq 'no_host') {
                   9463:         my $ownerlist;
                   9464:         if (ref($owners) eq 'ARRAY') {
                   9465:             $ownerlist = join(',',@{$owners});
                   9466:         } else {
                   9467:             $ownerlist = $owners;
                   9468:         }
                   9469:         if (ref($classesref) eq 'HASH') {
                   9470:             my $classes = &freeze_escape($classesref);
                   9471:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9472:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9473:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9474:                 my @items = split(/&/,$response);
                   9475:                 foreach my $item (@items) {
                   9476:                     my ($key,$value) = split('=',$item);
                   9477:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9478:                 }
                   9479:             }
                   9480:         }
                   9481:     }
                   9482:     return %validations;
                   9483: }
                   9484: 
1.1172.2.38  raeburn  9485: sub auto_crsreq_update {
                   9486:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9487:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9488:     my ($homeserver,%crsreqresponse);
                   9489:     if ($cdom =~ /^$match_domain$/) {
                   9490:         $homeserver = &domain($cdom,'primary');
                   9491:     }
                   9492:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9493:         my $info;
                   9494:         if (ref($inbound) eq 'HASH') {
                   9495:             $info = &freeze_escape($inbound);
                   9496:         }
                   9497:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9498:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9499:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9500:                             &escape($title).':'.&escape($code).':'.
                   9501:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9502:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9503:             my @items = split(/&/,$response);
                   9504:             foreach my $item (@items) {
                   9505:                 my ($key,$value) = split('=',$item);
                   9506:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9507:             }
                   9508:         }
                   9509:     }
                   9510:     return \%crsreqresponse;
                   9511: }
                   9512: 
1.1172.2.78  raeburn  9513: sub auto_export_grades {
                   9514:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9515:     my ($homeserver,%exportresponse);
                   9516:     if ($cdom =~ /^$match_domain$/) {
                   9517:         $homeserver = &domain($cdom,'primary');
                   9518:     }
                   9519:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9520:         my $info;
                   9521:         if (ref($inforef) eq 'HASH') {
                   9522:             $info = &freeze_escape($inforef);
                   9523:         }
                   9524:         if (ref($gradesref) eq 'HASH') {
                   9525:             my $grades = &freeze_escape($gradesref);
                   9526:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9527:                                 $info.':'.$grades,$homeserver);
                   9528:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9529:                 my @items = split(/&/,$response);
                   9530:                 foreach my $item (@items) {
                   9531:                     my ($key,$value) = split('=',$item);
                   9532:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9533:                 }
                   9534:             }
                   9535:         }
                   9536:     }
                   9537:     return \%exportresponse;
                   9538: }
                   9539: 
1.1172.2.68  raeburn  9540: sub check_instcode_cloning {
                   9541:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9542:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9543:         return;
                   9544:     }
                   9545:     my $canclone;
                   9546:     if (@{$code_order} > 0) {
                   9547:         my $instcoderegexp ='^';
                   9548:         my @clonecodes = split(/\&/,$cloner);
                   9549:         foreach my $item (@{$code_order}) {
                   9550:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9551:                 foreach my $pair (@clonecodes) {
                   9552:                     my ($key,$val) = split(/\=/,$pair,2);
                   9553:                     $val = &unescape($val);
                   9554:                     if ($key eq $item) {
                   9555:                         $instcoderegexp .= '('.$val.')';
                   9556:                         last;
                   9557:                     }
                   9558:                 }
                   9559:             } else {
                   9560:                 $instcoderegexp .= $codedefaults->{$item};
                   9561:             }
                   9562:         }
                   9563:         $instcoderegexp .= '$';
                   9564:         my (@from,@to);
                   9565:         eval {
                   9566:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9567:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9568:         };
                   9569:         if ((@from > 0) && (@to > 0)) {
                   9570:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9571:             if (!@diffs) {
                   9572:                 $canclone = 1;
                   9573:             }
                   9574:         }
                   9575:     }
                   9576:     return $canclone;
                   9577: }
                   9578: 
                   9579: sub default_instcode_cloning {
                   9580:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9581:     my (%codedefaults,@code_order,$canclone);
                   9582:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9583:         %codedefaults = %{$codedefaultsref};
                   9584:         @code_order = @{$codeorderref};
                   9585:     } elsif ($clonedom) {
                   9586:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9587:     }
                   9588:     if (($domdefclone) && (@code_order)) {
                   9589:         my @clonecodes = split(/\+/,$domdefclone);
                   9590:         my $instcoderegexp ='^';
                   9591:         foreach my $item (@code_order) {
                   9592:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9593:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9594:             } else {
                   9595:                 $instcoderegexp .= $codedefaults{$item};
                   9596:             }
                   9597:         }
                   9598:         $instcoderegexp .= '$';
                   9599:         my (@from,@to);
                   9600:         eval {
                   9601:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9602:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9603:         };
                   9604:         if ((@from > 0) && (@to > 0)) {
                   9605:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9606:             if (!@diffs) {
                   9607:                 $canclone = 1;
                   9608:             }
                   9609:         }
                   9610:     }
                   9611:     return $canclone;
                   9612: }
                   9613: 
1.679     raeburn  9614: # ------------------------------------------------------- Course Group routines
                   9615: 
                   9616: sub get_coursegroups {
1.809     raeburn  9617:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9618:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9619: }
                   9620: 
1.679     raeburn  9621: sub modify_coursegroup {
                   9622:     my ($cdom,$cnum,$groupsettings) = @_;
                   9623:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9624: }
                   9625: 
1.809     raeburn  9626: sub toggle_coursegroup_status {
                   9627:     my ($cdom,$cnum,$group,$action) = @_;
                   9628:     my ($from_namespace,$to_namespace);
                   9629:     if ($action eq 'delete') {
                   9630:         $from_namespace = 'coursegroups';
                   9631:         $to_namespace = 'deleted_groups';
                   9632:     } else {
                   9633:         $from_namespace = 'deleted_groups';
                   9634:         $to_namespace = 'coursegroups';
                   9635:     }
                   9636:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9637:     if (my $tmp = &error(%curr_group)) {
                   9638:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9639:         return ('read error',$tmp);
                   9640:     } else {
                   9641:         my %savedsettings = %curr_group; 
1.809     raeburn  9642:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9643:         my $deloutcome;
                   9644:         if ($result eq 'ok') {
1.809     raeburn  9645:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9646:         } else {
                   9647:             return ('write error',$result);
                   9648:         }
                   9649:         if ($deloutcome eq 'ok') {
                   9650:             return 'ok';
                   9651:         } else {
                   9652:             return ('delete error',$deloutcome);
                   9653:         }
                   9654:     }
                   9655: }
                   9656: 
1.679     raeburn  9657: sub modify_group_roles {
1.957     raeburn  9658:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9659:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9660:     my $role = 'gr/'.&escape($userprivs);
                   9661:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9662:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9663:     if ($result eq 'ok') {
                   9664:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9665:     }
1.679     raeburn  9666:     return $result;
                   9667: }
                   9668: 
                   9669: sub modify_coursegroup_membership {
                   9670:     my ($cdom,$cnum,$membership) = @_;
                   9671:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9672:     return $result;
                   9673: }
                   9674: 
1.682     raeburn  9675: sub get_active_groups {
                   9676:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9677:     my $now = time;
                   9678:     my %groups = ();
                   9679:     foreach my $key (keys(%env)) {
1.811     albertel 9680:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9681:             my ($start,$end) = split(/\./,$env{$key});
                   9682:             if (($end!=0) && ($end<$now)) { next; }
                   9683:             if (($start!=0) && ($start>$now)) { next; }
                   9684:             if ($1 eq $cdom && $2 eq $cnum) {
                   9685:                 $groups{$3} = $env{$key} ;
                   9686:             }
                   9687:         }
                   9688:     }
                   9689:     return %groups;
                   9690: }
                   9691: 
1.683     raeburn  9692: sub get_group_membership {
                   9693:     my ($cdom,$cnum,$group) = @_;
                   9694:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9695: }
                   9696: 
                   9697: sub get_users_groups {
                   9698:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9699:     my @usersgroups;
1.683     raeburn  9700:     my $cachetime=1800;
                   9701: 
                   9702:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9703:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9704:     if (defined($cached)) {
1.734     albertel 9705:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9706:     } else {  
                   9707:         $grouplist = '';
1.816     raeburn  9708:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9709:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9710:         my $access_end = $env{'course.'.$courseid.
                   9711:                               '.default_enrollment_end_date'};
                   9712:         my $now = time;
                   9713:         foreach my $key (keys(%roleshash)) {
                   9714:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9715:                 my $group = $1;
                   9716:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9717:                     my $start = $2;
                   9718:                     my $end = $1;
                   9719:                     if ($start == -1) { next; } # deleted from group
                   9720:                     if (($start!=0) && ($start>$now)) { next; }
                   9721:                     if (($end!=0) && ($end<$now)) {
                   9722:                         if ($access_end && $access_end < $now) {
                   9723:                             if ($access_end - $end < 86400) {
                   9724:                                 push(@usersgroups,$group);
1.733     raeburn  9725:                             }
                   9726:                         }
1.817     raeburn  9727:                         next;
1.733     raeburn  9728:                     }
1.817     raeburn  9729:                     push(@usersgroups,$group);
1.683     raeburn  9730:                 }
                   9731:             }
                   9732:         }
1.817     raeburn  9733:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9734:         $grouplist = join(':',@usersgroups);
                   9735:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9736:     }
1.733     raeburn  9737:     return @usersgroups;
1.683     raeburn  9738: }
                   9739: 
                   9740: sub devalidate_getgroups_cache {
                   9741:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9742:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9743: 
1.683     raeburn  9744:     my $hashid="$udom:$uname:$courseid";
                   9745:     &devalidate_cache_new('getgroups',$hashid);
                   9746: }
                   9747: 
1.12      www      9748: # ------------------------------------------------------------------ Plain Text
                   9749: 
                   9750: sub plaintext {
1.988     raeburn  9751:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9752:     if ($short =~ m{^cr/}) {
1.758     albertel 9753: 	return (split('/',$short))[-1];
                   9754:     }
1.742     raeburn  9755:     if (!defined($cid)) {
                   9756:         $cid = $env{'request.course.id'};
                   9757:     }
                   9758:     my %rolenames = (
1.1008    raeburn  9759:                       Course    => 'std',
                   9760:                       Community => 'alt1',
1.742     raeburn  9761:                     );
1.1037    raeburn  9762:     if ($cid ne '') {
                   9763:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9764:             unless ($forcedefault) {
                   9765:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9766:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9767:                 return &Apache::lonlocal::mt($roletext);
                   9768:             }
                   9769:         }
                   9770:     }
                   9771:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9772:         (defined($rolenames{$type})) && 
                   9773:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9774:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9775:     } elsif ($cid ne '') {
                   9776:         my $crstype = $env{'course.'.$cid.'.type'};
                   9777:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9778:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9779:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9780:         }
1.742     raeburn  9781:     }
1.1037    raeburn  9782:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9783: }
                   9784: 
                   9785: # ----------------------------------------------------------------- Assign Role
                   9786: 
                   9787: sub assignrole {
1.957     raeburn  9788:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9789:         $context)=@_;
1.21      www      9790:     my $mrole;
                   9791:     if ($role =~ /^cr\//) {
1.393     www      9792:         my $cwosec=$url;
1.811     albertel 9793:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9794: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9795:            my $refused = 1;
                   9796:            if ($context eq 'requestcourses') {
                   9797:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9798:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9799:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9800:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9801:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9802:                            if ($crsenv{'internal.courseowner'} eq
                   9803:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9804:                                $refused = '';
                   9805:                            }
                   9806:                        }
                   9807:                    }
                   9808:                }
                   9809:            }
                   9810:            if ($refused) {
                   9811:                &logthis('Refused custom assignrole: '.
                   9812:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9813:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9814:                return 'refused';
                   9815:            }
1.104     www      9816:         }
1.21      www      9817:         $mrole='cr';
1.678     raeburn  9818:     } elsif ($role =~ /^gr\//) {
                   9819:         my $cwogrp=$url;
1.811     albertel 9820:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9821:         unless (&allowed('mdg',$cwogrp)) {
                   9822:             &logthis('Refused group assignrole: '.
                   9823:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9824:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9825:             return 'refused';
                   9826:         }
                   9827:         $mrole='gr';
1.21      www      9828:     } else {
1.82      www      9829:         my $cwosec=$url;
1.811     albertel 9830:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9831:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9832:             my $refused;
                   9833:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9834:                 if (!(&allowed('c'.$role,$url))) {
                   9835:                     $refused = 1;
                   9836:                 }
                   9837:             } else {
                   9838:                 $refused = 1;
                   9839:             }
1.947     raeburn  9840:             if ($refused) {
1.1045    raeburn  9841:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9842:                 if (!$selfenroll && $context eq 'course') {
                   9843:                     my %crsenv;
                   9844:                     if ($role eq 'cc' || $role eq 'co') {
                   9845:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9846:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9847:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9848:                                 if ($crsenv{'internal.courseowner'} eq 
                   9849:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9850:                                     $refused = '';
                   9851:                                 }
                   9852:                             }
                   9853:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9854:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9855:                                 if ($crsenv{'internal.courseowner'} eq 
                   9856:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9857:                                     $refused = '';
                   9858:                                 }
                   9859:                             }
                   9860:                         }
                   9861:                     }
                   9862:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9863:                     $refused = '';
1.1017    raeburn  9864:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9865:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9866:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9867:                         my $wrongcc;
                   9868:                         if ($cnum =~ /^$match_community$/) {
                   9869:                             $wrongcc = 1 if ($role eq 'cc');
                   9870:                         } else {
                   9871:                             $wrongcc = 1 if ($role eq 'co');
                   9872:                         }
                   9873:                         unless ($wrongcc) {
                   9874:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9875:                             if ($crsenv{'internal.courseowner'} eq 
                   9876:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9877:                                 $refused = '';
                   9878:                             }
1.1017    raeburn  9879:                         }
                   9880:                     }
1.1172.2.9  raeburn  9881:                 } elsif ($context eq 'requestauthor') {
                   9882:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9883:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9884:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9885:                             $refused = '';
                   9886:                         } else {
                   9887:                             my %domdefaults = &get_domain_defaults($udom);
                   9888:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9889:                                 my $checkbystatus;
                   9890:                                 if ($env{'user.adv'}) {
                   9891:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9892:                                     if ($disposition eq 'automatic') {
                   9893:                                         $refused = '';
                   9894:                                     } elsif ($disposition eq '') {
                   9895:                                         $checkbystatus = 1;
                   9896:                                     }
                   9897:                                 } else {
                   9898:                                     $checkbystatus = 1;
                   9899:                                 }
                   9900:                                 if ($checkbystatus) {
                   9901:                                     if ($env{'environment.inststatus'}) {
                   9902:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9903:                                         foreach my $type (@inststatuses) {
                   9904:                                             if (($type ne '') &&
                   9905:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9906:                                                 $refused = '';
                   9907:                                             }
                   9908:                                         }
                   9909:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9910:                                         $refused = '';
                   9911:                                     }
                   9912:                                 }
                   9913:                             }
                   9914:                         }
                   9915:                     }
1.1017    raeburn  9916:                 }
                   9917:                 if ($refused) {
1.947     raeburn  9918:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9919:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9920: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9921:                     return 'refused';
                   9922:                 }
1.932     raeburn  9923:             }
1.1131    raeburn  9924:         } elsif ($role eq 'au') {
                   9925:             if ($url ne '/'.$udom.'/') {
                   9926:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9927:                          ' to assign author role for '.$uname.':'.$udom.
                   9928:                          ' in domain: '.$url.' refused (wrong domain).');
                   9929:                 return 'refused';
                   9930:             }
1.104     www      9931:         }
1.21      www      9932:         $mrole=$role;
                   9933:     }
1.620     albertel 9934:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9935:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9936:     if ($end) { $command.='_'.$end; }
1.21      www      9937:     if ($start) {
                   9938: 	if ($end) { 
1.81      www      9939:            $command.='_'.$start; 
1.21      www      9940:         } else {
1.81      www      9941:            $command.='_0_'.$start;
1.21      www      9942:         }
                   9943:     }
1.739     raeburn  9944:     my $origstart = $start;
                   9945:     my $origend = $end;
1.957     raeburn  9946:     my $delflag;
1.357     www      9947: # actually delete
                   9948:     if ($deleteflag) {
1.373     www      9949: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9950: # modify command to delete the role
1.620     albertel 9951:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9952:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9953: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9954: # set start and finish to negative values for userrolelog
                   9955:            $start=-1;
                   9956:            $end=-1;
1.957     raeburn  9957:            $delflag = 1;
1.357     www      9958:         }
                   9959:     }
                   9960: # send command
1.349     www      9961:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9962: # log new user role if status is ok
1.349     www      9963:     if ($answer eq 'ok') {
1.663     raeburn  9964: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9965:         if (($role eq 'cc') || ($role eq 'in') ||
                   9966:             ($role eq 'ep') || ($role eq 'ad') ||
                   9967:             ($role eq 'ta') || ($role eq 'st') ||
                   9968:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9969:             ($role eq 'co')) {
1.1172.2.13  raeburn  9970: # for course roles, perform group memberships changes triggered by role change.
                   9971:             unless ($role =~ /^gr/) {
                   9972:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9973:                                                  $origstart,$selfenroll,$context);
                   9974:             }
1.1172.2.9  raeburn  9975:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9976:                            $selfenroll,$context);
                   9977:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9978:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9979:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9980:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9981:                            $context);
                   9982:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9983:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9984:                              $context);
                   9985:         }
1.1053    raeburn  9986:         if ($role eq 'cc') {
                   9987:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9988:         }
1.349     www      9989:     }
                   9990:     return $answer;
1.169     harris41 9991: }
                   9992: 
1.1053    raeburn  9993: sub autoupdate_coowners {
                   9994:     my ($url,$end,$start,$uname,$udom) = @_;
                   9995:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9996:     if (($cdom ne '') && ($cnum ne '')) {
                   9997:         my $now = time;
                   9998:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9999:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10000:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10001:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10002:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10003:             if ($instcode ne '') {
1.1056    raeburn  10004:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10005:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10006:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10007:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10008:                         unless ($result eq 'valid') {
                   10009:                             if ($xlists ne '') {
                   10010:                                 foreach my $xlist (split(',',$xlists)) {
                   10011:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10012:                                     $result =
                   10013:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10014:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10015:                                     last if ($result eq 'valid');
                   10016:                                 }
                   10017:                             }
                   10018:                         }
1.1056    raeburn  10019:                         if ($result eq 'valid') {
                   10020:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10021:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10022:                                     push(@newcoowners,$coowner);
                   10023:                                 }
                   10024:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10025:                                     push(@newcoowners,$uname.':'.$udom);
                   10026:                                 }
                   10027:                                 @newcoowners = sort(@newcoowners);
                   10028:                             } else {
                   10029:                                 push(@newcoowners,$uname.':'.$udom);
                   10030:                             }
1.1172.2.141  raeburn  10031:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10032:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10033:                                 unless ($coowner eq $uname.':'.$udom) {
                   10034:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10035:                                 }
                   10036:                             }
1.1172.2.141  raeburn  10037:                             unless (@newcoowners > 0) {
                   10038:                                 $delcoowners = 1;
                   10039:                                 $coowners = '';
                   10040:                             }
1.1053    raeburn  10041:                         }
                   10042:                         if (@newcoowners || $delcoowners) {
                   10043:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10044:                                             $delcoowners,@newcoowners);
                   10045:                         }
                   10046:                     }
                   10047:                 }
                   10048:             }
                   10049:         }
                   10050:     }
                   10051: }
                   10052: 
                   10053: sub store_coowners {
                   10054:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10055:     my $cid = $cdom.'_'.$cnum;
                   10056:     my ($coowners,$delresult,$putresult);
                   10057:     if (@newcoowners) {
                   10058:         $coowners = join(',',@newcoowners);
                   10059:         my %coownershash = (
                   10060:                             'internal.co-owners' => $coowners,
                   10061:                            );
                   10062:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10063:         if ($putresult eq 'ok') {
                   10064:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10065:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10066:             }
                   10067:         }
                   10068:     }
                   10069:     if ($delcoowners) {
                   10070:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10071:         if ($delresult eq 'ok') {
                   10072:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10073:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10074:             }
                   10075:         }
                   10076:     }
                   10077:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10078:         my %crsinfo =
                   10079:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10080:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10081:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10082:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10083:         }
                   10084:     }
                   10085: }
                   10086: 
1.169     harris41 10087: # -------------------------------------------------- Modify user authentication
1.197     www      10088: # Overrides without validation
                   10089: 
1.169     harris41 10090: sub modifyuserauth {
                   10091:     my ($udom,$uname,$umode,$upass)=@_;
                   10092:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10093:     my $allowed;
                   10094:     if (&allowed('mau',$udom)) {
                   10095:         $allowed = 1;
                   10096:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10097:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10098:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10099:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10100:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10101:         if (($cdom ne '') && ($cnum ne '')) {
                   10102:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10103:             if ($is_owner) {
                   10104:                 $allowed = 1;
                   10105:             }
                   10106:         }
                   10107:     }
                   10108:     unless ($allowed) { return 'refused'; }
1.197     www      10109:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10110:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10111:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10112:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10113: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10114:     my $ip = &get_requestor_ip();
1.620     albertel 10115:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10116:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10117:          '(Remote '.$ip.'): '.$reply);
1.197     www      10118:     &log($udom,,$uname,$uhome,
1.620     albertel 10119:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10120:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10121:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10122:     unless ($reply eq 'ok') {
1.197     www      10123:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10124: 	return 'error: '.$reply;
                   10125:     }   
1.170     harris41 10126:     return 'ok';
1.80      www      10127: }
                   10128: 
1.81      www      10129: # --------------------------------------------------------------- Modify a user
1.80      www      10130: 
1.81      www      10131: sub modifyuser {
1.206     matthew  10132:     my ($udom,    $uname, $uid,
                   10133:         $umode,   $upass, $first,
                   10134:         $middle,  $last,  $gene,
1.1058    raeburn  10135:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10136:     $udom= &LONCAPA::clean_domain($udom);
                   10137:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10138:     my $showcandelete = 'none';
                   10139:     if (ref($candelete) eq 'ARRAY') {
                   10140:         if (@{$candelete} > 0) {
                   10141:             $showcandelete = join(', ',@{$candelete});
                   10142:         }
                   10143:     }
1.81      www      10144:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10145:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10146: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10147:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10148:                                      ' desiredhome not specified'). 
1.620     albertel 10149:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10150:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10151:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10152:     my $newuser;
                   10153:     if ($uhome eq 'no_host') {
                   10154:         $newuser = 1;
                   10155:     }
1.80      www      10156: # ----------------------------------------------------------------- Create User
1.406     albertel 10157:     if (($uhome eq 'no_host') && 
                   10158: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10159:         my $unhome='';
1.844     albertel 10160:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10161:             $unhome = $desiredhome;
1.620     albertel 10162: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10163: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10164:         } else { # load balancing routine for determining $unhome
1.81      www      10165:             my $loadm=10000000;
1.841     albertel 10166: 	    my %servers = &get_servers($udom,'library');
                   10167: 	    foreach my $tryserver (keys(%servers)) {
                   10168: 		my $answer=reply('load',$tryserver);
                   10169: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10170: 		    $loadm=$answer;
                   10171: 		    $unhome=$tryserver;
                   10172: 		}
1.80      www      10173: 	    }
                   10174:         }
                   10175:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10176: 	    return 'error: unable to find a home server for '.$uname.
                   10177:                    ' in domain '.$udom;
1.80      www      10178:         }
                   10179:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10180:                          &escape($upass),$unhome);
                   10181: 	unless ($reply eq 'ok') {
                   10182:             return 'error: '.$reply;
                   10183:         }   
1.230     stredwic 10184:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10185:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10186: 	    return 'error: unable verify users home machine.';
1.80      www      10187:         }
1.209     matthew  10188:     }   # End of creation of new user
1.80      www      10189: # ---------------------------------------------------------------------- Add ID
                   10190:     if ($uid) {
                   10191:        $uid=~tr/A-Z/a-z/;
                   10192:        my %uidhash=&idrget($udom,$uname);
1.196     www      10193:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10194:          && (!$forceid)) {
1.80      www      10195: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10196: 	      return 'error: user id "'.$uid.'" does not match '.
                   10197:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10198:           }
                   10199:        } else {
                   10200: 	  &idput($udom,($uname => $uid));
                   10201:        }
                   10202:     }
                   10203: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10204:     my @tmp=&get('environment',
1.899     raeburn  10205: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10206:                     'permanentemail','inststatus'],
1.134     albertel 10207: 		   $udom,$uname);
1.1075    raeburn  10208:     my (%names,%oldnames);
1.313     matthew  10209:     if ($tmp[0] =~ m/^error:.*/) { 
                   10210:         %names=(); 
                   10211:     } else {
                   10212:         %names = @tmp;
1.1075    raeburn  10213:         %oldnames = %names;
1.313     matthew  10214:     }
1.388     www      10215: #
1.1058    raeburn  10216: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10217: # of users did not contain them), do not overwrite existing values
                   10218: # unless field is in $candelete array ref.  
                   10219: #
                   10220: 
                   10221:     my @fields = ('firstname','middlename','lastname','generation',
                   10222:                   'permanentemail','id');
                   10223:     my %newvalues;
                   10224:     if (ref($candelete) eq 'ARRAY') {
                   10225:         foreach my $field (@fields) {
                   10226:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10227:                 if ($field eq 'firstname') {
                   10228:                     $names{$field} = $first;
                   10229:                 } elsif ($field eq 'middlename') {
                   10230:                     $names{$field} = $middle;
                   10231:                 } elsif ($field eq 'lastname') {
                   10232:                     $names{$field} = $last;
                   10233:                 } elsif ($field eq 'generation') { 
                   10234:                     $names{$field} = $gene;
                   10235:                 } elsif ($field eq 'permanentemail') {
                   10236:                     $names{$field} = $email;
                   10237:                 } elsif ($field eq 'id') {
                   10238:                     $names{$field}  = $uid;
                   10239:                 }
                   10240:             }
                   10241:         }
                   10242:     }
1.388     www      10243:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10244:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10245:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10246:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10247:     if ($email) {
                   10248:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10249:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10250:     }
1.899     raeburn  10251:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10252:     if (defined($inststatus)) {
                   10253:         $names{'inststatus'} = '';
                   10254:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10255:         if (ref($usertypes) eq 'HASH') {
                   10256:             my @okstatuses; 
                   10257:             foreach my $item (split(/:/,$inststatus)) {
                   10258:                 if (defined($usertypes->{$item})) {
                   10259:                     push(@okstatuses,$item);  
                   10260:                 }
                   10261:             }
                   10262:             if (@okstatuses) {
                   10263:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10264:             }
                   10265:         }
                   10266:     }
1.1075    raeburn  10267:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10268:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10269:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10270:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10271:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10272:     } else {
                   10273:         $logmsg .= ' during self creation';
                   10274:     }
1.1075    raeburn  10275:     my $changed;
                   10276:     if ($newuser) {
                   10277:         $changed = 1;
                   10278:     } else {
                   10279:         foreach my $field (@fields) {
                   10280:             if ($names{$field} ne $oldnames{$field}) {
                   10281:                 $changed = 1;
                   10282:                 last;
                   10283:             }
                   10284:         }
                   10285:     }
                   10286:     unless ($changed) {
                   10287:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10288:         &logthis($logmsg);
                   10289:         return 'ok';
                   10290:     }
                   10291:     my $reply = &put('environment', \%names, $udom,$uname);
                   10292:     if ($reply ne 'ok') { 
                   10293:         return 'error: '.$reply;
                   10294:     }
1.1087    raeburn  10295:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10296:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10297:     }
1.1075    raeburn  10298:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10299:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10300:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10301:     &logthis($logmsg);
1.134     albertel 10302:     return 'ok';
1.80      www      10303: }
                   10304: 
1.81      www      10305: # -------------------------------------------------------------- Modify student
1.80      www      10306: 
1.81      www      10307: sub modifystudent {
                   10308:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10309:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10310:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10311:     if (!$cid) {
1.620     albertel 10312: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10313: 	    return 'not_in_class';
                   10314: 	}
1.80      www      10315:     }
                   10316: # --------------------------------------------------------------- Make the user
1.81      www      10317:     my $reply=&modifyuser
1.209     matthew  10318: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10319:          $desiredhome,$email,$inststatus);
1.80      www      10320:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10321:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10322:     # student's environment
1.297     matthew  10323:     $uid = undef if (!$forceid);
1.455     albertel 10324:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10325: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10326:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10327:     return $reply;
                   10328: }
                   10329: 
                   10330: sub modify_student_enrollment {
1.1172.2.23  raeburn  10331:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10332:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10333:     my ($cdom,$cnum,$chome);
                   10334:     if (!$cid) {
1.620     albertel 10335: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10336: 	    return 'not_in_class';
                   10337: 	}
1.620     albertel 10338: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10339: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10340:     } else {
                   10341: 	($cdom,$cnum)=split(/_/,$cid);
                   10342:     }
1.620     albertel 10343:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10344:     if (!$chome) {
1.457     raeburn  10345: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10346:     }
1.455     albertel 10347:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10348:     # Make sure the user exists
1.81      www      10349:     my $uhome=&homeserver($uname,$udom);
                   10350:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10351: 	return 'error: no such user';
                   10352:     }
1.297     matthew  10353:     # Get student data if we were not given enough information
                   10354:     if (!defined($first)  || $first  eq '' || 
                   10355:         !defined($last)   || $last   eq '' || 
                   10356:         !defined($uid)    || $uid    eq '' || 
                   10357:         !defined($middle) || $middle eq '' || 
                   10358:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10359:         # They did not supply us with enough data to enroll the student, so
                   10360:         # we need to pick up more information.
1.297     matthew  10361:         my %tmp = &get('environment',
1.294     matthew  10362:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10363:                        ,$udom,$uname);
                   10364: 
1.800     albertel 10365:         #foreach my $key (keys(%tmp)) {
                   10366:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10367:         #}
1.294     matthew  10368:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10369:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10370:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10371:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10372:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10373:     }
1.556     albertel 10374:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10375:     my $user = "$uname:$udom";
                   10376:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10377:     my $reply=cput('classlist',
1.1148    raeburn  10378: 		   {$user => 
1.1172.2.76  raeburn  10379: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10380: 		   $cdom,$cnum);
1.1148    raeburn  10381:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10382:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10383:     } else { 
1.81      www      10384: 	return 'error: '.$reply;
                   10385:     }
1.297     matthew  10386:     # Add student role to user
1.83      www      10387:     my $uurl='/'.$cid;
1.81      www      10388:     $uurl=~s/\_/\//g;
                   10389:     if ($usec) {
                   10390: 	$uurl.='/'.$usec;
                   10391:     }
1.1148    raeburn  10392:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10393:                              $selfenroll,$context);
                   10394:     if ($result ne 'ok') {
                   10395:         if ($old_entry{$user} ne '') {
                   10396:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10397:         } else {
                   10398:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10399:         }
                   10400:     }
                   10401:     return $result; 
1.21      www      10402: }
                   10403: 
1.556     albertel 10404: sub format_name {
                   10405:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10406:     my $name;
                   10407:     if ($first ne 'lastname') {
                   10408: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10409:     } else {
                   10410: 	if ($lastname=~/\S/) {
                   10411: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10412: 	    $name=~s/\s+,/,/;
                   10413: 	} else {
                   10414: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10415: 	}
                   10416:     }
                   10417:     $name=~s/^\s+//;
                   10418:     $name=~s/\s+$//;
                   10419:     $name=~s/\s+/ /g;
                   10420:     return $name;
                   10421: }
                   10422: 
1.84      www      10423: # ------------------------------------------------- Write to course preferences
                   10424: 
                   10425: sub writecoursepref {
                   10426:     my ($courseid,%prefs)=@_;
                   10427:     $courseid=~s/^\///;
                   10428:     $courseid=~s/\_/\//g;
                   10429:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10430:     my $chome=homeserver($cnum,$cdomain);
                   10431:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10432: 	return 'error: no such course';
                   10433:     }
                   10434:     my $cstring='';
1.800     albertel 10435:     foreach my $pref (keys(%prefs)) {
                   10436: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10437:     }
1.84      www      10438:     $cstring=~s/\&$//;
                   10439:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10440: }
                   10441: 
                   10442: # ---------------------------------------------------------- Make/modify course
                   10443: 
                   10444: sub createcourse {
1.741     raeburn  10445:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10446:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10447:     $url=&declutter($url);
                   10448:     my $cid='';
1.1028    raeburn  10449:     if ($context eq 'requestcourses') {
                   10450:         my $can_create = 0;
                   10451:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10452:         if ($udom eq $ownerdom) {
                   10453:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10454:                                   $context)) {
                   10455:                 $can_create = 1;
                   10456:             }
                   10457:         } else {
                   10458:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10459:                                            $category);
                   10460:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10461:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10462:                 if (@curr > 0) {
                   10463:                     my @options = qw(approval validate autolimit);
                   10464:                     my $optregex = join('|',@options);
                   10465:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10466:                         $can_create = 1;
                   10467:                     }
                   10468:                 }
                   10469:             }
                   10470:         }
                   10471:         if ($can_create) {
                   10472:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10473:                 unless (&allowed('ccc',$udom)) {
                   10474:                     return 'refused'; 
                   10475:                 }
1.1017    raeburn  10476:             }
                   10477:         } else {
                   10478:             return 'refused';
                   10479:         }
1.1028    raeburn  10480:     } elsif (!&allowed('ccc',$udom)) {
                   10481:         return 'refused';
1.84      www      10482:     }
1.1011    raeburn  10483: # --------------------------------------------------------------- Get Unique ID
                   10484:     my $uname;
                   10485:     if ($cnum =~ /^$match_courseid$/) {
                   10486:         my $chome=&homeserver($cnum,$udom,'true');
                   10487:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10488:             $uname = $cnum;
                   10489:         } else {
1.1038    raeburn  10490:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10491:         }
                   10492:     } else {
1.1038    raeburn  10493:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10494:     }
                   10495:     return $uname if ($uname =~ /^error/);
                   10496: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10497:     if (!defined($course_server)) {
                   10498:         if (defined(&domain($udom,'primary'))) {
                   10499:             $course_server = &domain($udom,'primary');
                   10500:         } else {
                   10501:             $course_server = $env{'user.home'}; 
                   10502:         }
                   10503:     }
                   10504:     my %host_servers =
                   10505:         &Apache::lonnet::get_servers($udom,'library');
                   10506:     unless ($host_servers{$course_server}) {
                   10507:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10508:     }
1.84      www      10509: # ------------------------------------------------------------- Make the course
                   10510:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10511:                       $course_server);
1.84      www      10512:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10513:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10514:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10515: 	return 'error: no such course';
                   10516:     }
1.271     www      10517: # ----------------------------------------------------------------- Course made
1.516     raeburn  10518: # log existence
1.1029    raeburn  10519:     my $now = time;
1.918     raeburn  10520:     my $newcourse = {
                   10521:                     $udom.'_'.$uname => {
1.921     raeburn  10522:                                      description => $description,
                   10523:                                      inst_code   => $inst_code,
                   10524:                                      owner       => $course_owner,
                   10525:                                      type        => $crstype,
1.1029    raeburn  10526:                                      creator     => $env{'user.name'}.':'.
                   10527:                                                     $env{'user.domain'},
                   10528:                                      created     => $now,
                   10529:                                      context     => $context,
1.918     raeburn  10530:                                                 },
                   10531:                     };
1.921     raeburn  10532:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10533: # set toplevel url
1.271     www      10534:     my $topurl=$url;
                   10535:     unless ($nonstandard) {
                   10536: # ------------------------------------------ For standard courses, make top url
                   10537:         my $mapurl=&clutter($url);
1.278     www      10538:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10539:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10540: <map>
                   10541: <resource id="1" type="start"></resource>
                   10542: <resource id="2" src="$mapurl"></resource>
                   10543: <resource id="3" type="finish"></resource>
                   10544: <link index="1" from="1" to="2"></link>
                   10545: <link index="2" from="2" to="3"></link>
                   10546: </map>
                   10547: ENDINITMAP
                   10548:         $topurl=&declutter(
1.638     albertel 10549:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10550:                           );
                   10551:     }
                   10552: # ----------------------------------------------------------- Write preferences
1.84      www      10553:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10554:                      ('description'              => $description,
                   10555:                       'url'                      => $topurl,
                   10556:                       'internal.creator'         => $env{'user.name'}.':'.
                   10557:                                                     $env{'user.domain'},
                   10558:                       'internal.created'         => $now,
                   10559:                       'internal.creationcontext' => $context)
                   10560:                     );
1.84      www      10561:     return '/'.$udom.'/'.$uname;
                   10562: }
                   10563: 
1.1011    raeburn  10564: # ------------------------------------------------------------------- Create ID
                   10565: sub generate_coursenum {
1.1038    raeburn  10566:     my ($udom,$crstype) = @_;
1.1011    raeburn  10567:     my $domdesc = &domain($udom);
                   10568:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10569:     my $first;
                   10570:     if ($crstype eq 'Community') {
                   10571:         $first = '0';
                   10572:     } else {
                   10573:         $first = int(1+rand(9)); 
                   10574:     } 
                   10575:     my $uname=$first.
1.1011    raeburn  10576:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10577:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10578:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10579: # ----------------------------------------------- Make sure that does not exist
                   10580:     my $uhome=&homeserver($uname,$udom,'true');
                   10581:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10582:         if ($crstype eq 'Community') {
                   10583:             $first = '0';
                   10584:         } else {
                   10585:             $first = int(1+rand(9));
                   10586:         }
                   10587:         $uname=$first.
1.1011    raeburn  10588:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10589:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10590:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10591:         $uhome=&homeserver($uname,$udom,'true');
                   10592:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10593:             return 'error: unable to generate unique course-ID';
                   10594:         }
                   10595:     }
                   10596:     return $uname;
                   10597: }
                   10598: 
1.813     albertel 10599: sub is_course {
1.1167    droeschl 10600:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10601:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10602:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10603:     my $uhome=&homeserver($cnum,$cdom);
                   10604:     my $iscourse;
                   10605:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10606:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10607:     } else {
                   10608:         my $hashid = $cdom.':'.$cnum;
                   10609:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10610:         unless (defined($cached)) {
                   10611:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10612:                                         $cnum,undef,undef,'.');
                   10613:             $iscourse = 0;
                   10614:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10615:                 $iscourse = 1;
                   10616:             }
                   10617:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10618:         }
                   10619:     }
                   10620:     return unless($iscourse);
1.1167    droeschl 10621:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10622: }
                   10623: 
1.1015    raeburn  10624: sub store_userdata {
                   10625:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10626:     my $result;
1.1016    raeburn  10627:     if ($datakey ne '') {
1.1013    raeburn  10628:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10629:             if ($udom eq '' || $uname eq '') {
                   10630:                 $udom = $env{'user.domain'};
                   10631:                 $uname = $env{'user.name'};
                   10632:             }
                   10633:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10634:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10635:                 $result = 'error: no_host';
                   10636:             } else {
1.1172.2.138  raeburn  10637:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10638:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10639: 
                   10640:                 my $namevalue='';
                   10641:                 foreach my $key (keys(%{$storehash})) {
                   10642:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10643:                 }
                   10644:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10645:                 unless ($namespace eq 'courserequests') {
                   10646:                     $datakey = &escape($datakey);
                   10647:                 }
1.1105    raeburn  10648:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10649:                                   $namevalue,$uhome);
1.1013    raeburn  10650:             }
                   10651:         } else {
                   10652:             $result = 'error: data to store was not a hash reference'; 
                   10653:         }
                   10654:     } else {
                   10655:         $result= 'error: invalid requestkey'; 
                   10656:     }
                   10657:     return $result;
                   10658: }
                   10659: 
1.21      www      10660: # ---------------------------------------------------------- Assign Custom Role
                   10661: 
                   10662: sub assigncustomrole {
1.957     raeburn  10663:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10664:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10665:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10666: }
                   10667: 
                   10668: # ----------------------------------------------------------------- Revoke Role
                   10669: 
                   10670: sub revokerole {
1.957     raeburn  10671:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10672:     my $now=time;
1.965     raeburn  10673:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10674: }
                   10675: 
                   10676: # ---------------------------------------------------------- Revoke Custom Role
                   10677: 
                   10678: sub revokecustomrole {
1.957     raeburn  10679:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10680:     my $now=time;
1.357     www      10681:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10682:            $deleteflag,$selfenroll,$context);
1.17      www      10683: }
                   10684: 
1.533     banghart 10685: # ------------------------------------------------------------ Disk usage
1.535     albertel 10686: sub diskusage {
1.955     raeburn  10687:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10688:     $directorypath =~ s/\/$//;
                   10689:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10690:                        .&escape($getpropath).':'.&escape($uname).':'
                   10691:                        .&escape($udom),homeserver($uname,$udom));
                   10692:     if ($listing eq 'unknown_cmd') {
                   10693:         if ($getpropath) {
                   10694:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10695:         }
                   10696:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10697:     }
1.514     albertel 10698:     return $listing;
1.512     banghart 10699: }
                   10700: 
1.566     banghart 10701: sub is_locked {
1.1096    raeburn  10702:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10703:     my @check;
                   10704:     my $is_locked;
1.1093    raeburn  10705:     push (@check,$file_name);
1.613     albertel 10706:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10707: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10708:     my ($tmp)=keys(%locked);
                   10709:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10710:     
1.566     banghart 10711:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10712:         $is_locked = 'false';
                   10713:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10714:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10715:                $is_locked = 'true';
1.1096    raeburn  10716:                if (ref($which) eq 'ARRAY') {
                   10717:                    push(@{$which},$entry);
                   10718:                } else {
                   10719:                    last;
                   10720:                }
1.745     raeburn  10721:            }
                   10722:        }
1.566     banghart 10723:     } else {
                   10724:         $is_locked = 'false';
                   10725:     }
1.1093    raeburn  10726:     return $is_locked;
1.566     banghart 10727: }
                   10728: 
1.759     albertel 10729: sub declutter_portfile {
                   10730:     my ($file) = @_;
1.833     albertel 10731:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10732:     return $file;
                   10733: }
                   10734: 
1.559     banghart 10735: # ------------------------------------------------------------- Mark as Read Only
                   10736: 
                   10737: sub mark_as_readonly {
                   10738:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10739:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10740:     my ($tmp)=keys(%current_permissions);
                   10741:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10742:     foreach my $file (@{$files}) {
1.759     albertel 10743: 	$file = &declutter_portfile($file);
1.561     banghart 10744:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10745:     }
1.613     albertel 10746:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10747:     return;
                   10748: }
                   10749: 
1.572     banghart 10750: # ------------------------------------------------------------Save Selected Files
                   10751: 
                   10752: sub save_selected_files {
                   10753:     my ($user, $path, @files) = @_;
                   10754:     my $filename = $user."savedfiles";
1.573     banghart 10755:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10756:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10757:     foreach my $file (@files) {
1.620     albertel 10758:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10759:     }
                   10760:     foreach my $file (@other_files) {
1.574     banghart 10761:         print (OUT $file."\n");
1.572     banghart 10762:     }
1.574     banghart 10763:     close (OUT);
1.572     banghart 10764:     return 'ok';
                   10765: }
                   10766: 
1.574     banghart 10767: sub clear_selected_files {
                   10768:     my ($user) = @_;
                   10769:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10770:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10771:     print (OUT undef);
                   10772:     close (OUT);
                   10773:     return ("ok");    
                   10774: }
                   10775: 
1.572     banghart 10776: sub files_in_path {
                   10777:     my ($user, $path) = @_;
                   10778:     my $filename = $user."savedfiles";
                   10779:     my %return_files;
1.1172.2.96  raeburn  10780:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10781:     while (my $line_in = <IN>) {
1.574     banghart 10782:         chomp ($line_in);
                   10783:         my @paths_and_file = split (m!/!, $line_in);
                   10784:         my $file_part = pop (@paths_and_file);
                   10785:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10786:         $path_part.='/';
                   10787:         my $path_and_file = $path_part.$file_part;
                   10788:         if ($path_part eq $path) {
                   10789:             $return_files{$file_part}= 'selected';
                   10790:         }
                   10791:     }
1.574     banghart 10792:     close (IN);
                   10793:     return (\%return_files);
1.572     banghart 10794: }
                   10795: 
                   10796: # called in portfolio select mode, to show files selected NOT in current directory
                   10797: sub files_not_in_path {
                   10798:     my ($user, $path) = @_;
                   10799:     my $filename = $user."savedfiles";
                   10800:     my @return_files;
                   10801:     my $path_part;
1.1172.2.96  raeburn  10802:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10803:     while (my $line = <IN>) {
1.572     banghart 10804:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10805:         my @paths_and_file = split(m|/|, $line);
                   10806:         my $file_part = pop(@paths_and_file);
                   10807:         chomp($file_part);
                   10808:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10809:         $path_part .= '/';
                   10810:         my $path_and_file = $path_part.$file_part;
                   10811:         if ($path_part ne $path) {
1.800     albertel 10812:             push(@return_files, ($path_and_file));
1.572     banghart 10813:         }
                   10814:     }
1.800     albertel 10815:     close(OUT);
1.574     banghart 10816:     return (@return_files);
1.572     banghart 10817: }
                   10818: 
1.745     raeburn  10819: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10820: 
1.745     raeburn  10821: sub get_portfile_permissions {
                   10822:     my ($domain,$user) = @_;
1.613     albertel 10823:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10824:     my ($tmp)=keys(%current_permissions);
                   10825:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10826:     return \%current_permissions;
                   10827: }
                   10828: 
                   10829: #---------------------------------------------Get portfolio file access controls
                   10830: 
1.749     raeburn  10831: sub get_access_controls {
1.745     raeburn  10832:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10833:     my %access;
                   10834:     my $real_file = $file;
                   10835:     $file =~ s/\.meta$//;
1.745     raeburn  10836:     if (defined($file)) {
1.749     raeburn  10837:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10838:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10839:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10840:             }
                   10841:         }
1.745     raeburn  10842:     } else {
1.749     raeburn  10843:         foreach my $key (keys(%{$current_permissions})) {
                   10844:             if ($key =~ /\0accesscontrol$/) {
                   10845:                 if (defined($group)) {
                   10846:                     if ($key !~ m-^\Q$group\E/-) {
                   10847:                         next;
                   10848:                     }
                   10849:                 }
                   10850:                 my ($fullpath) = split(/\0/,$key);
                   10851:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10852:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10853:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10854:                     }
                   10855:                 }
                   10856:             }
                   10857:         }
                   10858:     }
                   10859:     return %access;
                   10860: }
                   10861: 
                   10862: sub modify_access_controls {
                   10863:     my ($file_name,$changes,$domain,$user)=@_;
                   10864:     my ($outcome,$deloutcome);
                   10865:     my %store_permissions;
                   10866:     my %new_values;
                   10867:     my %new_control;
                   10868:     my %translation;
                   10869:     my @deletions = ();
                   10870:     my $now = time;
                   10871:     if (exists($$changes{'activate'})) {
                   10872:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10873:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10874:             my $numnew = scalar(@newitems);
                   10875:             for (my $i=0; $i<$numnew; $i++) {
                   10876:                 my $newkey = $newitems[$i];
                   10877:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10878:                 if ($newkey =~ /^\d+:/) { 
                   10879:                     $newkey =~ s/^(\d+)/$newid/;
                   10880:                     $translation{$1} = $newid;
                   10881:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10882:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10883:                     $translation{$1} = $newid;
                   10884:                 }
1.749     raeburn  10885:                 $new_values{$file_name."\0".$newkey} = 
                   10886:                                           $$changes{'activate'}{$newitems[$i]};
                   10887:                 $new_control{$newkey} = $now;
                   10888:             }
                   10889:         }
                   10890:     }
                   10891:     my %todelete;
                   10892:     my %changed_items;
                   10893:     foreach my $action ('delete','update') {
                   10894:         if (exists($$changes{$action})) {
                   10895:             if (ref($$changes{$action}) eq 'HASH') {
                   10896:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10897:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10898:                     if ($action eq 'delete') { 
                   10899:                         $todelete{$itemnum} = 1;
                   10900:                     } else {
                   10901:                         $changed_items{$itemnum} = $key;
                   10902:                     }
                   10903:                 }
1.745     raeburn  10904:             }
                   10905:         }
1.749     raeburn  10906:     }
                   10907:     # get lock on access controls for file.
                   10908:     my $lockhash = {
                   10909:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10910:                                                        ':'.$env{'user.domain'},
                   10911:                    }; 
                   10912:     my $tries = 0;
                   10913:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10914:    
1.1172.2.79  raeburn  10915:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10916:         $tries ++;
1.1172.2.79  raeburn  10917:         sleep(0.1);
1.749     raeburn  10918:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10919:     }
                   10920:     if ($gotlock eq 'ok') {
                   10921:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10922:         my ($tmp)=keys(%curr_permissions);
                   10923:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10924:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10925:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10926:             if (ref($curr_controls) eq 'HASH') {
                   10927:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10928:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10929:                     if (defined($todelete{$itemnum})) {
                   10930:                         push(@deletions,$file_name."\0".$control_item);
                   10931:                     } else {
                   10932:                         if (defined($changed_items{$itemnum})) {
                   10933:                             $new_control{$changed_items{$itemnum}} = $now;
                   10934:                             push(@deletions,$file_name."\0".$control_item);
                   10935:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10936:                         } else {
                   10937:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10938:                         }
                   10939:                     }
1.745     raeburn  10940:                 }
                   10941:             }
                   10942:         }
1.970     raeburn  10943:         my ($group);
                   10944:         if (&is_course($domain,$user)) {
                   10945:             ($group,my $file) = split(/\//,$file_name,2);
                   10946:         }
1.749     raeburn  10947:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10948:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10949:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10950:         #  remove lock
                   10951:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10952:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10953:         my $sqlresult =
1.970     raeburn  10954:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10955:                                     $group);
1.749     raeburn  10956:     } else {
                   10957:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10958:     }
1.749     raeburn  10959:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10960: }
                   10961: 
1.827     raeburn  10962: sub make_public_indefinitely {
                   10963:     my ($requrl) = @_;
                   10964:     my $now = time;
                   10965:     my $action = 'activate';
                   10966:     my $aclnum = 0;
                   10967:     if (&is_portfolio_url($requrl)) {
                   10968:         my (undef,$udom,$unum,$file_name,$group) =
                   10969:             &parse_portfolio_url($requrl);
                   10970:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10971:         my %access_controls = &get_access_controls($current_perms,
                   10972:                                                    $group,$file_name);
                   10973:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10974:             my ($num,$scope,$end,$start) = 
                   10975:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10976:             if ($scope eq 'public') {
                   10977:                 if ($start <= $now && $end == 0) {
                   10978:                     $action = 'none';
                   10979:                 } else {
                   10980:                     $action = 'update';
                   10981:                     $aclnum = $num;
                   10982:                 }
                   10983:                 last;
                   10984:             }
                   10985:         }
                   10986:         if ($action eq 'none') {
                   10987:              return 'ok';
                   10988:         } else {
                   10989:             my %changes;
                   10990:             my $newend = 0;
                   10991:             my $newstart = $now;
                   10992:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10993:             $changes{$action}{$newkey} = {
                   10994:                 type => 'public',
                   10995:                 time => {
                   10996:                     start => $newstart,
                   10997:                     end   => $newend,
                   10998:                 },
                   10999:             };
                   11000:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11001:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11002:             return $outcome;
                   11003:         }
                   11004:     } else {
                   11005:         return 'invalid';
                   11006:     }
                   11007: }
                   11008: 
1.745     raeburn  11009: #------------------------------------------------------Get Marked as Read Only
                   11010: 
                   11011: sub get_marked_as_readonly {
                   11012:     my ($domain,$user,$what,$group) = @_;
                   11013:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11014:     my @readonly_files;
1.629     banghart 11015:     my $cmp1=$what;
                   11016:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11017:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11018:         if (defined($group)) {
                   11019:             if ($file_name !~ m-^\Q$group\E/-) {
                   11020:                 next;
                   11021:             }
                   11022:         }
1.561     banghart 11023:         if (ref($value) eq "ARRAY"){
                   11024:             foreach my $stored_what (@{$value}) {
1.629     banghart 11025:                 my $cmp2=$stored_what;
1.759     albertel 11026:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11027:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11028:                 }
1.629     banghart 11029:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11030:                     push(@readonly_files, $file_name);
1.745     raeburn  11031:                     last;
1.563     banghart 11032:                 } elsif (!defined($what)) {
                   11033:                     push(@readonly_files, $file_name);
1.745     raeburn  11034:                     last;
1.561     banghart 11035:                 }
                   11036:             }
1.745     raeburn  11037:         }
1.561     banghart 11038:     }
                   11039:     return @readonly_files;
                   11040: }
1.577     banghart 11041: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11042: 
1.577     banghart 11043: sub get_marked_as_readonly_hash {
1.745     raeburn  11044:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11045:     my %readonly_files;
1.745     raeburn  11046:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11047:         if (defined($group)) {
                   11048:             if ($file_name !~ m-^\Q$group\E/-) {
                   11049:                 next;
                   11050:             }
                   11051:         }
1.577     banghart 11052:         if (ref($value) eq "ARRAY"){
                   11053:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11054:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11055:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11056:                         if ($lock_descriptor eq 'graded') {
                   11057:                             $readonly_files{$file_name} = 'graded';
                   11058:                         } elsif ($lock_descriptor eq 'handback') {
                   11059:                             $readonly_files{$file_name} = 'handback';
                   11060:                         } else {
                   11061:                             if (!exists($readonly_files{$file_name})) {
                   11062:                                 $readonly_files{$file_name} = 'locked';
                   11063:                             }
                   11064:                         }
1.745     raeburn  11065:                     }
1.750     banghart 11066:                 } 
1.577     banghart 11067:             }
                   11068:         } 
                   11069:     }
                   11070:     return %readonly_files;
                   11071: }
1.559     banghart 11072: # ------------------------------------------------------------ Unmark as Read Only
                   11073: 
                   11074: sub unmark_as_readonly {
1.629     banghart 11075:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11076:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11077:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11078:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11079:     my $symb_crs = $what;
                   11080:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11081:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11082:     my ($tmp)=keys(%current_permissions);
                   11083:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11084:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11085:     foreach my $file (@readonly_files) {
1.759     albertel 11086: 	my $clean_file = &declutter_portfile($file);
                   11087: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11088: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11089:         my @new_locks;
                   11090:         my @del_keys;
                   11091:         if (ref($current_locks) eq "ARRAY"){
                   11092:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11093:                 my $compare=$locker;
1.749     raeburn  11094:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11095:                     $compare=join('',@{$locker});
1.746     raeburn  11096:                     if ($compare ne $symb_crs) {
                   11097:                         push(@new_locks, $locker);
                   11098:                     }
1.563     banghart 11099:                 }
                   11100:             }
1.650     albertel 11101:             if (scalar(@new_locks) > 0) {
1.563     banghart 11102:                 $current_permissions{$file} = \@new_locks;
                   11103:             } else {
                   11104:                 push(@del_keys, $file);
1.613     albertel 11105:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11106:                 delete($current_permissions{$file});
1.563     banghart 11107:             }
                   11108:         }
1.561     banghart 11109:     }
1.613     albertel 11110:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11111:     return;
                   11112: }
1.512     banghart 11113: 
1.17      www      11114: # ------------------------------------------------------------ Directory lister
                   11115: 
                   11116: sub dirlist {
1.955     raeburn  11117:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11118:     $uri=~s/^\///;
                   11119:     $uri=~s/\/$//;
1.253     stredwic 11120:     my ($udom, $uname);
1.955     raeburn  11121:     if ($getuserdir) {
1.253     stredwic 11122:         $udom = $userdomain;
                   11123:         $uname = $username;
1.955     raeburn  11124:     } else {
                   11125:         (undef,$udom,$uname)=split(/\//,$uri);
                   11126:         if(defined($userdomain)) {
                   11127:             $udom = $userdomain;
                   11128:         }
                   11129:         if(defined($username)) {
                   11130:             $uname = $username;
                   11131:         }
1.253     stredwic 11132:     }
1.955     raeburn  11133:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11134: 
1.955     raeburn  11135:     $dirRoot = $perlvar{'lonDocRoot'};
                   11136:     if (defined($getpropath)) {
                   11137:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11138:         $dirRoot =~ s/\/$//;
1.955     raeburn  11139:     } elsif (defined($getuserdir)) {
                   11140:         my $subdir=$uname.'__';
                   11141:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11142:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11143:                    ."/$udom/$subdir/$uname";
                   11144:     } elsif (defined($alternateRoot)) {
                   11145:         $dirRoot = $alternateRoot;
1.751     banghart 11146:     }
1.253     stredwic 11147: 
                   11148:     if($udom) {
                   11149:         if($uname) {
1.1135    raeburn  11150:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11151:             if ($uhome eq 'no_host') {
                   11152:                 return ([],'no_host');
                   11153:             }
1.955     raeburn  11154:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11155:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11156:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11157:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11158:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11159:             } else {
                   11160:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11161:             }
1.605     matthew  11162:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11163:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11164:                 @listing_results = split(/:/,$listing);
                   11165:             } else {
                   11166:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11167:             }
1.1135    raeburn  11168:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11169:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11170:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11171:                 return ([],$listing);
                   11172:             } else {
                   11173:                 return (\@listing_results);
1.1135    raeburn  11174:             }
1.955     raeburn  11175:         } elsif(!$alternateRoot) {
1.1136    raeburn  11176:             my (%allusers,%listerror);
1.841     albertel 11177: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11178:  	    foreach my $tryserver (keys(%servers)) {
                   11179:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11180:                                   &escape($udom),$tryserver);
                   11181:                 if ($listing eq 'unknown_cmd') {
                   11182: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11183: 				      $udom, $tryserver);
                   11184:                 } else {
                   11185:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11186:                 }
1.841     albertel 11187: 		if ($listing eq 'unknown_cmd') {
                   11188: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11189: 				      $udom, $tryserver);
                   11190: 		    @listing_results = split(/:/,$listing);
                   11191: 		} else {
                   11192: 		    @listing_results =
                   11193: 			map { &unescape($_); } split(/:/,$listing);
                   11194: 		}
1.1136    raeburn  11195:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11196:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11197:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11198:                     $listerror{$tryserver} = $listing;
                   11199:                 } else {
1.841     albertel 11200: 		    foreach my $line (@listing_results) {
                   11201: 			my ($entry) = split(/&/,$line,2);
                   11202: 			$allusers{$entry} = 1;
                   11203: 		    }
                   11204: 		}
1.253     stredwic 11205:             }
1.1136    raeburn  11206:             my @alluserslist=();
1.800     albertel 11207:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11208:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11209:             }
1.1172.2.80  raeburn  11210:             if (!%listerror) {
                   11211:                 # no errors
                   11212:                 return (\@alluserslist);
                   11213:             } elsif (scalar(keys(%servers)) == 1) {
                   11214:                 # one library server, one error
                   11215:                 my ($key) = keys(%listerror);
                   11216:                 return (\@alluserslist, $listerror{$key});
                   11217:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11218:                 # con_lost indicates that we might miss data from at least one
                   11219:                 # library server
                   11220:                 return (\@alluserslist, 'con_lost');
                   11221:             } else {
                   11222:                 # multiple library servers and no con_lost -> data should be
                   11223:                 # complete.
                   11224:                 return (\@alluserslist);
                   11225:             }
                   11226: 
1.253     stredwic 11227:         } else {
1.1136    raeburn  11228:             return ([],'missing username');
1.253     stredwic 11229:         }
1.955     raeburn  11230:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11231:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11232:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11233:         return (\@all_domains);
1.955     raeburn  11234:     } else {
1.1136    raeburn  11235:         return ([],'missing domain');
1.275     stredwic 11236:     }
                   11237: }
                   11238: 
                   11239: # --------------------------------------------- GetFileTimestamp
                   11240: # This function utilizes dirlist and returns the date stamp for
                   11241: # when it was last modified.  It will also return an error of -1
                   11242: # if an error occurs
                   11243: 
                   11244: sub GetFileTimestamp {
1.955     raeburn  11245:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11246:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11247:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11248:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11249:                                     undef,$getuserdir);
                   11250:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11251:         return -1;
                   11252:     }
                   11253:     if (ref($fileref) eq 'ARRAY') {
                   11254:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11255:         # @stats contains first the filename, then the stat output
                   11256:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11257:     } else {
                   11258:         return -1;
1.253     stredwic 11259:     }
1.26      www      11260: }
                   11261: 
1.712     albertel 11262: sub stat_file {
                   11263:     my ($uri) = @_;
1.787     albertel 11264:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11265: 
1.955     raeburn  11266:     my ($udom,$uname,$file);
1.712     albertel 11267:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11268: 	($udom,$uname,$file) =
1.811     albertel 11269: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11270: 	$file = 'userfiles/'.$file;
                   11271:     }
                   11272:     if ($uri =~ m-^/res/-) {
                   11273: 	($udom,$uname) = 
1.807     albertel 11274: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11275: 	$file = $uri;
                   11276:     }
                   11277: 
                   11278:     if (!$udom || !$uname || !$file) {
                   11279: 	# unable to handle the uri
                   11280: 	return ();
                   11281:     }
1.956     raeburn  11282:     my $getpropath;
                   11283:     if ($file =~ /^userfiles\//) {
                   11284:         $getpropath = 1;
                   11285:     }
1.1136    raeburn  11286:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11287:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11288:         return ();
                   11289:     } else {
                   11290:         if (ref($listref) eq 'ARRAY') {
                   11291:             my @stats = split('&',$listref->[0]);
                   11292: 	    shift(@stats); #filename is first
                   11293: 	    return @stats;
                   11294:         }
1.712     albertel 11295:     }
                   11296:     return ();
                   11297: }
                   11298: 
1.26      www      11299: # -------------------------------------------------------- Value of a Condition
                   11300: 
1.713     albertel 11301: # gets the value of a specific preevaluated condition
                   11302: #    stored in the string  $env{user.state.<cid>}
                   11303: # or looks up a condition reference in the bighash and if if hasn't
                   11304: # already been evaluated recurses into docondval to get the value of
                   11305: # the condition, then memoizing it to 
                   11306: #   $env{user.state.<cid>.<condition>}
1.40      www      11307: sub directcondval {
                   11308:     my $number=shift;
1.620     albertel 11309:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11310: 	&Apache::lonuserstate::evalstate();
                   11311:     }
1.713     albertel 11312:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11313: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11314:     } elsif ($number =~ /^_/) {
                   11315: 	my $sub_condition;
                   11316: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11317: 		&GDBM_READER(),0640)) {
                   11318: 	    $sub_condition=$bighash{'conditions'.$number};
                   11319: 	    untie(%bighash);
                   11320: 	}
                   11321: 	my $value = &docondval($sub_condition);
1.949     raeburn  11322: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11323: 	return $value;
                   11324:     }
1.620     albertel 11325:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11326:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11327:     } else {
                   11328:        return 2;
                   11329:     }
                   11330: }
                   11331: 
1.713     albertel 11332: # get the collection of conditions for this resource
1.26      www      11333: sub condval {
                   11334:     my $condidx=shift;
1.54      www      11335:     my $allpathcond='';
1.713     albertel 11336:     foreach my $cond (split(/\|/,$condidx)) {
                   11337: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11338: 	    $allpathcond.=
                   11339: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11340: 	}
1.191     harris41 11341:     }
1.54      www      11342:     $allpathcond=~s/\|$//;
1.713     albertel 11343:     return &docondval($allpathcond);
                   11344: }
                   11345: 
                   11346: #evaluates an expression of conditions
                   11347: sub docondval {
                   11348:     my ($allpathcond) = @_;
                   11349:     my $result=0;
                   11350:     if ($env{'request.course.id'}
                   11351: 	&& defined($allpathcond)) {
                   11352: 	my $operand='|';
                   11353: 	my @stack;
                   11354: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11355: 	    if ($chunk eq '(') {
                   11356: 		push @stack,($operand,$result);
                   11357: 	    } elsif ($chunk eq ')') {
                   11358: 		my $before=pop @stack;
                   11359: 		if (pop @stack eq '&') {
                   11360: 		    $result=$result>$before?$before:$result;
                   11361: 		} else {
                   11362: 		    $result=$result>$before?$result:$before;
                   11363: 		}
                   11364: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11365: 		$operand=$chunk;
                   11366: 	    } else {
                   11367: 		my $new=directcondval($chunk);
                   11368: 		if ($operand eq '&') {
                   11369: 		    $result=$result>$new?$new:$result;
                   11370: 		} else {
                   11371: 		    $result=$result>$new?$result:$new;
                   11372: 		}
                   11373: 	    }
                   11374: 	}
1.26      www      11375:     }
                   11376:     return $result;
1.421     albertel 11377: }
                   11378: 
                   11379: # ---------------------------------------------------- Devalidate courseresdata
                   11380: 
                   11381: sub devalidatecourseresdata {
                   11382:     my ($coursenum,$coursedomain)=@_;
                   11383:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11384:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11385: }
                   11386: 
1.763     www      11387: 
1.200     www      11388: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11389: #
                   11390: #  Parameters:
                   11391: #      $coursenum    - Number of the course.
                   11392: #      $coursedomain - Domain at which the course was created.
                   11393: #  Returns:
                   11394: #     A hash of the course parameters along (I think) with timestamps
                   11395: #     and version info.
1.877     foxr     11396: 
1.624     albertel 11397: sub get_courseresdata {
                   11398:     my ($coursenum,$coursedomain)=@_;
1.200     www      11399:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11400:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11401:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11402:     my %dumpreply;
1.417     albertel 11403:     unless (defined($cached)) {
1.624     albertel 11404: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11405: 	$result=\%dumpreply;
1.251     albertel 11406: 	my ($tmp) = keys(%dumpreply);
                   11407: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11408: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11409: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11410: 	    return $tmp;
1.416     albertel 11411: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11412: 	    $result=undef;
1.599     albertel 11413: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11414: 	}
                   11415:     }
1.624     albertel 11416:     return $result;
                   11417: }
                   11418: 
1.633     albertel 11419: sub devalidateuserresdata {
                   11420:     my ($uname,$udom)=@_;
                   11421:     my $hashid="$udom:$uname";
                   11422:     &devalidate_cache_new('userres',$hashid);
                   11423: }
                   11424: 
1.624     albertel 11425: sub get_userresdata {
                   11426:     my ($uname,$udom)=@_;
                   11427:     #most student don\'t have any data set, check if there is some data
                   11428:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11429: 
                   11430:     my $hashid="$udom:$uname";
                   11431:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11432:     if (!defined($cached)) {
                   11433: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11434: 	$result=\%resourcedata;
                   11435: 	&do_cache_new('userres',$hashid,$result,600);
                   11436:     }
                   11437:     my ($tmp)=keys(%$result);
                   11438:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11439: 	return $result;
                   11440:     }
                   11441:     #error 2 occurs when the .db doesn't exist
                   11442:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11443:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11444: 	    &logthis("<font color=\"blue\">WARNING:".
                   11445: 		     " Trying to get resource data for ".
                   11446: 		     $uname." at ".$udom.": ".
                   11447: 		     $tmp."</font>");
                   11448:         }
1.624     albertel 11449:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11450: 	#&EXT_cache_set($udom,$uname);
                   11451: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11452: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11453:     }
                   11454:     return $tmp;
                   11455: }
1.879     foxr     11456: #----------------------------------------------- resdata - return resource data
                   11457: #  Purpose:
                   11458: #    Return resource data for either users or for a course.
                   11459: #  Parameters:
                   11460: #     $name      - Course/user name.
                   11461: #     $domain    - Name of the domain the user/course is registered on.
                   11462: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11463: #     @which     - Array of names of resources desired.
                   11464: #  Returns:
                   11465: #     The value of the first reasource in @which that is found in the
                   11466: #     resource hash.
                   11467: #  Exceptional Conditions:
                   11468: #     If the $type passed in is not valid (not the string 'course' or 
                   11469: #     'user', an undefined  reference is returned.
                   11470: #     If none of the resources are found, an undef is returned
1.624     albertel 11471: sub resdata {
                   11472:     my ($name,$domain,$type,@which)=@_;
                   11473:     my $result;
                   11474:     if ($type eq 'course') {
                   11475: 	$result=&get_courseresdata($name,$domain);
                   11476:     } elsif ($type eq 'user') {
                   11477: 	$result=&get_userresdata($name,$domain);
                   11478:     }
                   11479:     if (!ref($result)) { return $result; }    
1.251     albertel 11480:     foreach my $item (@which) {
1.927     albertel 11481: 	if (defined($result->{$item->[0]})) {
                   11482: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11483: 	}
1.250     albertel 11484:     }
1.291     albertel 11485:     return undef;
1.200     www      11486: }
                   11487: 
1.1172.2.31  raeburn  11488: sub get_numsuppfiles {
                   11489:     my ($cnum,$cdom,$ignorecache)=@_;
                   11490:     my $hashid=$cnum.':'.$cdom;
                   11491:     my ($suppcount,$cached);
                   11492:     unless ($ignorecache) {
                   11493:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11494:     }
                   11495:     unless (defined($cached)) {
                   11496:         my $chome=&homeserver($cnum,$cdom);
                   11497:         unless ($chome eq 'no_host') {
                   11498:             ($suppcount,my $errors) = (0,0);
                   11499:             my $suppmap = 'supplemental.sequence';
                   11500:             ($suppcount,$errors) =
                   11501:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11502:         }
                   11503:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11504:     }
                   11505:     return $suppcount;
                   11506: }
                   11507: 
1.379     matthew  11508: #
                   11509: # EXT resource caching routines
                   11510: #
                   11511: 
                   11512: sub clear_EXT_cache_status {
1.383     albertel 11513:     &delenv('cache.EXT.');
1.379     matthew  11514: }
                   11515: 
                   11516: sub EXT_cache_status {
                   11517:     my ($target_domain,$target_user) = @_;
1.383     albertel 11518:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11519:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11520:         # We know already the user has no data
                   11521:         return 1;
                   11522:     } else {
                   11523:         return 0;
                   11524:     }
                   11525: }
                   11526: 
                   11527: sub EXT_cache_set {
                   11528:     my ($target_domain,$target_user) = @_;
1.383     albertel 11529:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11530:     #&appenv({$cachename => time});
1.379     matthew  11531: }
                   11532: 
1.28      www      11533: # --------------------------------------------------------- Value of a Variable
1.58      www      11534: sub EXT {
1.715     albertel 11535: 
1.1172.2.28  raeburn  11536:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11537:     unless ($varname) { return ''; }
1.218     albertel 11538:     #get real user name/domain, courseid and symb
                   11539:     my $courseid;
1.359     albertel 11540:     my $publicuser;
1.427     www      11541:     if ($symbparm) {
                   11542: 	$symbparm=&get_symb_from_alias($symbparm);
                   11543:     }
1.218     albertel 11544:     if (!($uname && $udom)) {
1.790     albertel 11545:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11546:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11547:     } else {
1.620     albertel 11548: 	$courseid=$env{'request.course.id'};
1.218     albertel 11549:     }
1.48      www      11550:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11551:     my $rest;
1.320     albertel 11552:     if (defined($therest[0])) {
1.48      www      11553:        $rest=join('.',@therest);
                   11554:     } else {
                   11555:        $rest='';
                   11556:     }
1.320     albertel 11557: 
1.57      www      11558:     my $qualifierrest=$qualifier;
                   11559:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11560:     my $spacequalifierrest=$space;
                   11561:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11562:     if ($realm eq 'user') {
1.48      www      11563: # --------------------------------------------------------------- user.resource
                   11564: 	if ($space eq 'resource') {
1.651     albertel 11565: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11566: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11567: 		 &&
1.1172.2.142  raeburn  11568: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11569: 		# if we are in the middle of processing the resource the
                   11570: 		# get the value we are planning on committing
                   11571:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11572:                     return $Apache::lonhomework::results{$qualifierrest};
                   11573:                 } else {
                   11574:                     return $Apache::lonhomework::history{$qualifierrest};
                   11575:                 }
1.335     albertel 11576: 	    } else {
1.359     albertel 11577: 		my %restored;
1.620     albertel 11578: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11579: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11580: 		} else {
                   11581: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11582: 		}
1.335     albertel 11583: 		return $restored{$qualifierrest};
                   11584: 	    }
1.48      www      11585: # ----------------------------------------------------------------- user.access
                   11586:         } elsif ($space eq 'access') {
1.218     albertel 11587: 	    # FIXME - not supporting calls for a specific user
1.48      www      11588:             return &allowed($qualifier,$rest);
                   11589: # ------------------------------------------ user.preferences, user.environment
                   11590:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11591: 	    if (($uname eq $env{'user.name'}) &&
                   11592: 		($udom eq $env{'user.domain'})) {
                   11593: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11594: 	    } else {
1.359     albertel 11595: 		my %returnhash;
                   11596: 		if (!$publicuser) {
                   11597: 		    %returnhash=&userenvironment($udom,$uname,
                   11598: 						 $qualifierrest);
                   11599: 		}
1.218     albertel 11600: 		return $returnhash{$qualifierrest};
                   11601: 	    }
1.48      www      11602: # ----------------------------------------------------------------- user.course
                   11603:         } elsif ($space eq 'course') {
1.218     albertel 11604: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11605:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11606: # ------------------------------------------------------------------- user.role
                   11607:         } elsif ($space eq 'role') {
1.218     albertel 11608: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11609:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11610:             if ($qualifier eq 'value') {
                   11611: 		return $role;
                   11612:             } elsif ($qualifier eq 'extent') {
                   11613:                 return $where;
                   11614:             }
                   11615: # ----------------------------------------------------------------- user.domain
                   11616:         } elsif ($space eq 'domain') {
1.218     albertel 11617:             return $udom;
1.48      www      11618: # ------------------------------------------------------------------- user.name
                   11619:         } elsif ($space eq 'name') {
1.218     albertel 11620:             return $uname;
1.48      www      11621: # ---------------------------------------------------- Any other user namespace
1.29      www      11622:         } else {
1.359     albertel 11623: 	    my %reply;
                   11624: 	    if (!$publicuser) {
                   11625: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11626: 	    }
                   11627: 	    return $reply{$qualifierrest};
1.48      www      11628:         }
1.236     www      11629:     } elsif ($realm eq 'query') {
                   11630: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11631:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11632: 						[$spacequalifierrest]);
1.620     albertel 11633: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11634:    } elsif ($realm eq 'request') {
1.48      www      11635: # ------------------------------------------------------------- request.browser
                   11636:         if ($space eq 'browser') {
1.1145    bisitz   11637:             return $env{'browser.'.$qualifier};
1.57      www      11638: # ------------------------------------------------------------ request.filename
                   11639:         } else {
1.620     albertel 11640:             return $env{'request.'.$spacequalifierrest};
1.29      www      11641:         }
1.28      www      11642:     } elsif ($realm eq 'course') {
1.48      www      11643: # ---------------------------------------------------------- course.description
1.620     albertel 11644:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11645:     } elsif ($realm eq 'resource') {
1.165     www      11646: 
1.620     albertel 11647: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11648: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11649: 	}
1.693     albertel 11650: 
1.1172.2.30  raeburn  11651:         if ($qualifier eq '') {
                   11652: 	    if ($space eq 'title') {
                   11653: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11654: 	        return &gettitle($symbparm);
                   11655: 	    }
1.693     albertel 11656: 	
1.1172.2.30  raeburn  11657: 	    if ($space eq 'map') {
                   11658: 	        my ($map) = &decode_symb($symbparm);
                   11659: 	        return &symbread($map);
                   11660: 	    }
                   11661:             if ($space eq 'maptitle') {
                   11662:                 my ($map) = &decode_symb($symbparm);
                   11663:                 return &gettitle($map);
                   11664:             }
                   11665: 	    if ($space eq 'filename') {
                   11666: 	        if ($symbparm) {
                   11667: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11668: 	        }
                   11669: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11670: 	    }
1.1172.2.30  raeburn  11671: 
                   11672:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11673:                 if ($space eq 'visibleparts') {
                   11674:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11675:                     my $item;
                   11676:                     if (ref($navmap)) {
                   11677:                         my $res = $navmap->getBySymb($symbparm);
                   11678:                         my $parts = $res->parts();
                   11679:                         if (ref($parts) eq 'ARRAY') {
                   11680:                             $item = join(',',@{$parts});
                   11681:                         }
                   11682:                         undef($navmap);
                   11683:                     }
                   11684:                     return $item;
                   11685:                 }
                   11686:             }
                   11687:         }
1.693     albertel 11688: 
                   11689: 	my ($section, $group, @groups);
1.593     albertel 11690: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11691:         if (($courseid eq '') && ($cid)) {
                   11692:             $courseid = $cid;
                   11693:         }
                   11694: 	if (($symbparm && $courseid) && 
                   11695: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11696: 
1.218     albertel 11697: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11698: 
1.60      www      11699: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11700: 	    my $symbp=$symbparm;
1.735     albertel 11701: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11702: 
                   11703: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11704: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11705: 
1.620     albertel 11706: 	    if (($env{'user.name'} eq $uname) &&
                   11707: 		($env{'user.domain'} eq $udom)) {
                   11708: 		$section=$env{'request.course.sec'};
1.733     raeburn  11709:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11710:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11711: 	    } else {
1.539     albertel 11712: 		if (! defined($usection)) {
1.551     albertel 11713: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11714: 		} else {
                   11715: 		    $section = $usection;
                   11716: 		}
1.733     raeburn  11717:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11718: 	    }
                   11719: 
                   11720: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11721: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11722: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11723: 
1.593     albertel 11724: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11725: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11726: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11727: 
1.60      www      11728: # ----------------------------------------------------------- first, check user
1.624     albertel 11729: 
                   11730: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11731: 				       ([$courselevelr,'resource'],
                   11732: 					[$courselevelm,'map'     ],
                   11733: 					[$courselevel, 'course'  ]));
1.931     albertel 11734: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11735: 
1.594     albertel 11736: # ------------------------------------------------ second, check some of course
1.684     raeburn  11737:             my $coursereply;
1.691     raeburn  11738:             if (@groups > 0) {
                   11739:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11740:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11741:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11742:             }
1.96      www      11743: 
1.684     raeburn  11744: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11745: 				  $env{'course.'.$courseid.'.domain'},
                   11746: 				  'course',
                   11747: 				  ([$seclevelr,   'resource'],
                   11748: 				   [$seclevelm,   'map'     ],
                   11749: 				   [$seclevel,    'course'  ],
                   11750: 				   [$courselevelr,'resource']));
                   11751: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11752: 
1.60      www      11753: # ------------------------------------------------------ third, check map parms
1.218     albertel 11754: 	    my %parmhash=();
                   11755: 	    my $thisparm='';
                   11756: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11757: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11758: 		    &GDBM_READER(),0640)) {
1.218     albertel 11759: 		$thisparm=$parmhash{$symbparm};
                   11760: 		untie(%parmhash);
                   11761: 	    }
1.927     albertel 11762: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11763: 	}
1.594     albertel 11764: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11765: 
1.218     albertel 11766: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11767: 	my $filename;
                   11768: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11769: 	if ($symbparm) {
1.409     www      11770: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11771: 	} else {
1.620     albertel 11772: 	    $filename=$env{'request.filename'};
1.282     albertel 11773: 	}
                   11774: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11775: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11776: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11777: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11778: 
1.927     albertel 11779: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11780: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11781: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11782: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11783: 				     $env{'course.'.$courseid.'.domain'},
                   11784: 				     'course',
1.927     albertel 11785: 				     ([$courselevelm,'map'   ],
                   11786: 				      [$courselevel, 'course']));
                   11787: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11788: 	}
1.145     www      11789: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11790: 	unless ($space eq '0') {
1.336     albertel 11791: 	    my @parts=split(/_/,$space);
                   11792: 	    my $id=pop(@parts);
                   11793: 	    my $part=join('_',@parts);
                   11794: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11795: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11796: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11797: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11798: 	}
1.395     albertel 11799: 	if ($recurse) { return undef; }
                   11800: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11801: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11802: # ---------------------------------------------------- Any other user namespace
                   11803:     } elsif ($realm eq 'environment') {
                   11804: # ----------------------------------------------------------------- environment
1.620     albertel 11805: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11806: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11807: 	} else {
1.770     albertel 11808: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11809: 		return '';
                   11810: 	    }
1.219     albertel 11811: 	    my %returnhash=&userenvironment($udom,$uname,
                   11812: 					    $spacequalifierrest);
                   11813: 	    return $returnhash{$spacequalifierrest};
                   11814: 	}
1.28      www      11815:     } elsif ($realm eq 'system') {
1.48      www      11816: # ----------------------------------------------------------------- system.time
                   11817: 	if ($space eq 'time') {
                   11818: 	    return time;
                   11819:         }
1.696     albertel 11820:     } elsif ($realm eq 'server') {
                   11821: # ----------------------------------------------------------------- system.time
                   11822: 	if ($space eq 'name') {
                   11823: 	    return $ENV{'SERVER_NAME'};
                   11824:         }
1.28      www      11825:     }
1.48      www      11826:     return '';
1.61      www      11827: }
                   11828: 
1.927     albertel 11829: sub get_reply {
                   11830:     my ($reply_value) = @_;
1.940     raeburn  11831:     if (ref($reply_value) eq 'ARRAY') {
                   11832:         if (wantarray) {
                   11833: 	    return @$reply_value;
                   11834:         }
                   11835:         return $reply_value->[0];
                   11836:     } else {
                   11837:         return $reply_value;
1.927     albertel 11838:     }
                   11839: }
                   11840: 
1.691     raeburn  11841: sub check_group_parms {
                   11842:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11843:     my @groupitems = ();
                   11844:     my $resultitem;
1.927     albertel 11845:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11846:     foreach my $group (@{$groups}) {
                   11847:         foreach my $level (@levels) {
1.927     albertel 11848:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11849:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11850:         }
                   11851:     }
                   11852:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11853:                             $env{'course.'.$courseid.'.domain'},
                   11854:                                      'course',@groupitems);
                   11855:     return $coursereply;
                   11856: }
                   11857: 
                   11858: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11859:     my ($courseid,@groups) = @_;
                   11860:     @groups = sort(@groups);
1.691     raeburn  11861:     return @groups;
                   11862: }
                   11863: 
1.395     albertel 11864: sub packages_tab_default {
                   11865:     my ($uri,$varname)=@_;
                   11866:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11867: 
                   11868:     my (@extension,@specifics,$do_default);
                   11869:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11870: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11871: 	if ($pack_type eq 'default') {
                   11872: 	    $do_default=1;
                   11873: 	} elsif ($pack_type eq 'extension') {
                   11874: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11875: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11876: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11877: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11878: 	}
                   11879:     }
                   11880:     # first look for a package that matches the requested part id
                   11881:     foreach my $package (@specifics) {
                   11882: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11883: 	next if ($pack_part ne $part);
                   11884: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11885: 	    return $packagetab{"$pack_type&$name&default"};
                   11886: 	}
                   11887:     }
                   11888:     # look for any possible matching non extension_ package
                   11889:     foreach my $package (@specifics) {
                   11890: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11891: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11892: 	    return $packagetab{"$pack_type&$name&default"};
                   11893: 	}
1.585     albertel 11894: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11895: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11896: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11897: 	}
                   11898:     }
1.738     albertel 11899:     # look for any posible extension_ match
                   11900:     foreach my $package (@extension) {
                   11901: 	my ($package,$pack_type)=@{$package};
                   11902: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11903: 	    return $packagetab{"$pack_type&$name&default"};
                   11904: 	}
                   11905: 	if (defined($packagetab{$package."&$name&default"})) {
                   11906: 	    return $packagetab{$package."&$name&default"};
                   11907: 	}
                   11908:     }
                   11909:     # look for a global default setting
                   11910:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11911: 	return $packagetab{"default&$name&default"};
                   11912:     }
1.395     albertel 11913:     return undef;
                   11914: }
                   11915: 
1.334     albertel 11916: sub add_prefix_and_part {
                   11917:     my ($prefix,$part)=@_;
                   11918:     my $keyroot;
                   11919:     if (defined($prefix) && $prefix !~ /^__/) {
                   11920: 	# prefix that has a part already
                   11921: 	$keyroot=$prefix;
                   11922:     } elsif (defined($prefix)) {
                   11923: 	# prefix that is missing a part
                   11924: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11925:     } else {
                   11926: 	# no prefix at all
                   11927: 	if (defined($part)) { $keyroot='_'.$part; }
                   11928:     }
                   11929:     return $keyroot;
                   11930: }
                   11931: 
1.71      www      11932: # ---------------------------------------------------------------- Get metadata
                   11933: 
1.599     albertel 11934: my %metaentry;
1.1070    www      11935: my %importedpartids;
1.1172.2.99  raeburn  11936: my %importedrespids;
1.71      www      11937: sub metadata {
1.176     www      11938:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11939:     $uri=&declutter($uri);
1.288     albertel 11940:     # if it is a non metadata possible uri return quickly
1.529     albertel 11941:     if (($uri eq '') || 
                   11942: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11943: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11944:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11945: 	return undef;
                   11946:     }
1.1172.2.49  raeburn  11947:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11948: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11949: 	return undef;
1.288     albertel 11950:     }
1.73      www      11951:     my $filename=$uri;
                   11952:     $uri=~s/\.meta$//;
1.172     www      11953: #
                   11954: # Is the metadata already cached?
1.177     www      11955: # Look at timestamp of caching
1.172     www      11956: # Everything is cached by the main uri, libraries are never directly cached
                   11957: #
1.428     albertel 11958:     if (!defined($liburi)) {
1.599     albertel 11959: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11960: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11961:     }
                   11962:     {
1.1069    www      11963: # Imported parts would go here
1.1172.2.99  raeburn  11964:         my @origfiletagids=();
1.1069    www      11965:         my $importedparts=0;
1.1172.2.99  raeburn  11966: 
                   11967: # Imported responseids would go here
                   11968:         my $importedresponses=0;
1.172     www      11969: #
                   11970: # Is this a recursive call for a library?
                   11971: #
1.599     albertel 11972: #	if (! exists($metacache{$uri})) {
                   11973: #	    $metacache{$uri}={};
                   11974: #	}
1.924     albertel 11975: 	my $cachetime = 60*60;
1.171     www      11976:         if ($liburi) {
                   11977: 	    $liburi=&declutter($liburi);
                   11978:             $filename=$liburi;
1.401     bowersj2 11979:         } else {
1.599     albertel 11980: 	    &devalidate_cache_new('meta',$uri);
                   11981: 	    undef(%metaentry);
1.401     bowersj2 11982: 	}
1.140     www      11983:         my %metathesekeys=();
1.73      www      11984:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11985: 	my $metastring;
1.1140    www      11986: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11987: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11988: 	    $metastring = 
1.929     albertel 11989: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11990: 					  ('grade_target' => 'meta'));
                   11991: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11992: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11993:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11994: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11995: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11996: 	    $metastring=&getfile($file);
1.489     albertel 11997: 	}
1.208     albertel 11998:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11999:         my $token;
1.140     www      12000:         undef %metathesekeys;
1.71      www      12001:         while ($token=$parser->get_token) {
1.339     albertel 12002: 	    if ($token->[0] eq 'S') {
                   12003: 		if (defined($token->[2]->{'package'})) {
1.172     www      12004: #
                   12005: # This is a package - get package info
                   12006: #
1.339     albertel 12007: 		    my $package=$token->[2]->{'package'};
                   12008: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12009: 		    if (defined($token->[2]->{'id'})) { 
                   12010: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12011: 		    }
1.599     albertel 12012: 		    if ($metaentry{':packages'}) {
                   12013: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12014: 		    } else {
1.599     albertel 12015: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12016: 		    }
1.736     albertel 12017: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12018: 			my $part=$keyroot;
                   12019: 			$part=~s/^\_//;
1.736     albertel 12020: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12021: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12022: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12023: 			    # ignore package.tab specified default values
                   12024:                             # here &package_tab_default() will fetch those
                   12025: 			    if ($subp eq 'default') { next; }
1.736     albertel 12026: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12027: 			    my $unikey;
                   12028: 			    if ($pack =~ /_0$/) {
                   12029: 				$unikey='parameter_0_'.$name;
                   12030: 				$part=0;
                   12031: 			    } else {
                   12032: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12033: 			    }
1.339     albertel 12034: 			    if ($subp eq 'display') {
                   12035: 				$value.=' [Part: '.$part.']';
                   12036: 			    }
1.599     albertel 12037: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12038: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12039: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12040: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12041: 			    }
1.599     albertel 12042: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12043: 				$metaentry{':'.$unikey}=
                   12044: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12045: 			    }
1.339     albertel 12046: 			}
                   12047: 		    }
                   12048: 		} else {
1.172     www      12049: #
                   12050: # This is not a package - some other kind of start tag
1.339     albertel 12051: #
                   12052: 		    my $entry=$token->[1];
1.1068    www      12053: 		    my $unikey='';
1.175     www      12054: 
1.339     albertel 12055: 		    if ($entry eq 'import') {
1.175     www      12056: #
                   12057: # Importing a library here
1.339     albertel 12058: #
1.1067    www      12059:                         my $location=$parser->get_text('/import');
                   12060:                         my $dir=$filename;
                   12061:                         $dir=~s|[^/]*$||;
                   12062:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12063: 
                   12064:                         my $importid=$token->[2]->{'id'};
1.1068    www      12065:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12066: #
                   12067: # Check metadata for imported file to
                   12068: # see if it contained response items
                   12069: #
                   12070:                         my %currmetaentry = %metaentry;
                   12071:                         my $libresponseorder = &metadata($location,'responseorder');
                   12072:                         my $origfile;
                   12073:                         if ($libresponseorder ne '') {
                   12074:                             if ($#origfiletagids<0) {
                   12075:                                 undef(%importedrespids);
                   12076:                                 undef(%importedpartids);
                   12077:                             }
                   12078:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12079:                             if (@{$importedrespids{$importid}} > 0) {
                   12080:                                 $importedresponses = 1;
                   12081: # We need to get the original file and the imported file to get the response order correct
                   12082: # Load and inspect original file
                   12083:                                 if ($#origfiletagids<0) {
                   12084:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12085:                                     $origfile=&getfile($origfilelocation);
                   12086:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12087:                                 }
                   12088:                             }
                   12089:                         }
                   12090: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12091: # hash populated for imported library file
                   12092:                         %metaentry = %currmetaentry;
                   12093:                         undef(%currmetaentry);
1.1068    www      12094:                         if ($importmode eq 'problem') {
1.1069    www      12095: # Import as problem/response
1.1068    www      12096:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12097:                         } elsif ($importmode eq 'part') {
                   12098: # Import as part(s)
1.1069    www      12099:                            $importedparts=1;
                   12100: # We need to get the original file and the imported file to get the part order correct
                   12101: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12102: # Load and inspect original file if we didn't do that already
                   12103:                            if ($#origfiletagids<0) {
                   12104:                                undef(%importedrespids);
                   12105:                                undef(%importedpartids);
                   12106:                                if ($origfile eq '') {
                   12107:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12108:                                    $origfile=&getfile($origfilelocation);
                   12109:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12110:                                }
1.1070    www      12111:                            }
                   12112: 
1.1069    www      12113: # Load and inspect imported file
                   12114:                            my $impfile=&getfile($location);
                   12115:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12116:                            if ($#impfilepartids>=0) {
                   12117: # This problem had parts
1.1070    www      12118:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12119:                            } else {
                   12120: # Importing by turning a single problem into a problem part
                   12121: # It gets the import-tags ID as part-ID
                   12122:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12123:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12124:                            }
1.1068    www      12125:                         } else {
                   12126: # Normal import
                   12127:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12128:                            if (defined($token->[2]->{'id'})) {
                   12129:                               $unikey.='_'.$token->[2]->{'id'};
                   12130:                            }
1.1067    www      12131:                         }
                   12132: 
1.339     albertel 12133: 			if ($depthcount<20) {
1.736     albertel 12134: 			    my $metadata = 
                   12135: 				&metadata($uri,'keys', $location,$unikey,
                   12136: 					  $depthcount+1);
                   12137: 			    foreach my $meta (split(',',$metadata)) {
                   12138: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12139: 				$metathesekeys{$meta}=1;
1.339     albertel 12140: 			    }
1.1068    www      12141: 			
                   12142:                         }
1.1067    www      12143: 		    } else {
                   12144: #
                   12145: # Not importing, some other kind of non-package, non-library start tag
                   12146: # 
                   12147:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12148:                         if (defined($token->[2]->{'id'})) {
                   12149:                             $unikey.='_'.$token->[2]->{'id'};
                   12150:                         }
1.339     albertel 12151: 			if (defined($token->[2]->{'name'})) { 
                   12152: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12153: 			}
                   12154: 			$metathesekeys{$unikey}=1;
1.736     albertel 12155: 			foreach my $param (@{$token->[3]}) {
                   12156: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12157: 				$token->[2]->{$param};
1.339     albertel 12158: 			}
                   12159: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12160: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12161: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12162: 		 # only ws inside the tag, and not in default, so use default
                   12163: 		 # as value
1.599     albertel 12164: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12165: 			} elsif ( $internaltext =~ /\S/ ) {
                   12166: 		  # something interesting inside the tag
                   12167: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12168: 			} else {
1.908     albertel 12169: 		  # no interesting values, don't set a default
1.339     albertel 12170: 			}
1.172     www      12171: # end of not-a-package not-a-library import
1.339     albertel 12172: 		    }
1.172     www      12173: # end of not-a-package start tag
1.339     albertel 12174: 		}
1.172     www      12175: # the next is the end of "start tag"
1.339     albertel 12176: 	    }
                   12177: 	}
1.483     albertel 12178: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12179: 	$extension = lc($extension);
                   12180: 	if ($extension eq 'htm') { $extension='html'; }
                   12181: 
1.737     albertel 12182: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12183: 	    #no specific packages #how's our extension
                   12184: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12185: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12186: 					 \%metathesekeys);
                   12187: 	}
1.883     albertel 12188: 
                   12189: 	if (!exists($metaentry{':packages'})
                   12190: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12191: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12192: 		#no specific packages well let's get default then
                   12193: 		if ($key!~/^default&/) { next; }
1.488     albertel 12194: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12195: 					     \%metathesekeys);
                   12196: 	    }
                   12197: 	}
1.338     www      12198: # are there custom rights to evaluate
1.599     albertel 12199: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12200: 
1.338     www      12201:     #
                   12202:     # Importing a rights file here
1.339     albertel 12203:     #
                   12204: 	    unless ($depthcount) {
1.599     albertel 12205: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12206: 		my $dir=$filename;
                   12207: 		$dir=~s|[^/]*$||;
                   12208: 		$location=&filelocation($dir,$location);
1.736     albertel 12209: 		my $rights_metadata =
                   12210: 		    &metadata($uri,'keys',$location,'_rights',
                   12211: 			      $depthcount+1);
                   12212: 		foreach my $rights (split(',',$rights_metadata)) {
                   12213: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12214: 		    $metathesekeys{$rights}=1;
1.339     albertel 12215: 		}
                   12216: 	    }
                   12217: 	}
1.737     albertel 12218: 	# uniqifiy package listing
                   12219: 	my %seen;
                   12220: 	my @uniq_packages =
                   12221: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12222: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12223: 
1.1172.2.99  raeburn  12224:         if (($importedresponses) || ($importedparts)) {
                   12225:             if ($importedparts) {
1.1070    www      12226: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12227:                 $metaentry{':partorder'}='';
                   12228:                 $metathesekeys{'partorder'}=1;
                   12229:             }
                   12230:             if ($importedresponses) {
                   12231: # We had imported responses and need to rebuild responseorder
                   12232:                 $metaentry{':responseorder'}='';
                   12233:                 $metathesekeys{'responseorder'}=1;
                   12234:             }
                   12235:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12236:                 my $origid = $origfiletagids[$index+1];
                   12237:                 if ($origfiletagids[$index] eq 'part') {
                   12238: # Original part, part of the problem
                   12239:                     if ($importedparts) {
                   12240:                         $metaentry{':partorder'}.=','.$origid;
                   12241:                     }
                   12242:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12243:                     if ($importedparts) {
                   12244: # We have imported parts at this position
                   12245:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12246:                     }
                   12247:                     if ($importedresponses) {
                   12248: # We have imported responses at this position
                   12249:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12250:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12251:                         }
                   12252:                     }
                   12253:                 } else {
                   12254: # Original response item, part of the problem
                   12255:                     if ($importedresponses) {
                   12256:                         $metaentry{':responseorder'}.=','.$origid;
                   12257:                     }
                   12258:                 }
                   12259:             }
                   12260:             if ($importedparts) {
                   12261:                 $metaentry{':partorder'}=~s/^\,//;
                   12262:             }
                   12263:             if ($importedresponses) {
                   12264:                 $metaentry{':responseorder'}=~s/^\,//;
                   12265:             }
1.1070    www      12266:         }
                   12267: 
1.737     albertel 12268: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12269: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12270: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12271: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12272: # this is the end of "was not already recently cached
1.71      www      12273:     }
1.599     albertel 12274:     return $metaentry{':'.$what};
1.261     albertel 12275: }
                   12276: 
1.488     albertel 12277: sub metadata_create_package_def {
1.483     albertel 12278:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12279:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12280:     if ($subp eq 'default') { next; }
                   12281:     
1.599     albertel 12282:     if (defined($metaentry{':packages'})) {
                   12283: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12284:     } else {
1.599     albertel 12285: 	$metaentry{':packages'}=$package;
1.483     albertel 12286:     }
                   12287:     my $value=$packagetab{$key};
                   12288:     my $unikey;
                   12289:     $unikey='parameter_0_'.$name;
1.599     albertel 12290:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12291:     $$metathesekeys{$unikey}=1;
1.599     albertel 12292:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12293: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12294:     }
1.599     albertel 12295:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12296: 	$metaentry{':'.$unikey}=
                   12297: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12298:     }
                   12299: }
                   12300: 
1.261     albertel 12301: sub metadata_generate_part0 {
                   12302:     my ($metadata,$metacache,$uri) = @_;
                   12303:     my %allnames;
1.737     albertel 12304:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12305: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12306: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12307: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12308: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12309: 	    $allnames{$name}=$part;
                   12310: 	  }
                   12311: 	}
                   12312:     }
                   12313:     foreach my $name (keys(%allnames)) {
                   12314:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12315:       my $key=":parameter_0_$name";
1.261     albertel 12316:       $$metacache{"$key.part"}='0';
                   12317:       $$metacache{"$key.name"}=$name;
1.428     albertel 12318:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12319: 					   $allnames{$name}.'_'.$name.
                   12320: 					   '.type'};
1.428     albertel 12321:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12322: 			     '.display'};
1.644     www      12323:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12324:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12325:       $$metacache{"$key.display"}=$olddis;
                   12326:     }
1.71      www      12327: }
                   12328: 
1.764     albertel 12329: # ------------------------------------------------------ Devalidate title cache
                   12330: 
                   12331: sub devalidate_title_cache {
                   12332:     my ($url)=@_;
                   12333:     if (!$env{'request.course.id'}) { return; }
                   12334:     my $symb=&symbread($url);
                   12335:     if (!$symb) { return; }
                   12336:     my $key=$env{'request.course.id'}."\0".$symb;
                   12337:     &devalidate_cache_new('title',$key);
                   12338: }
                   12339: 
1.1014    droeschl 12340: # ------------------------------------------------- Get the title of a course
                   12341: 
                   12342: sub current_course_title {
                   12343:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12344: }
1.301     www      12345: # ------------------------------------------------- Get the title of a resource
                   12346: 
                   12347: sub gettitle {
                   12348:     my $urlsymb=shift;
                   12349:     my $symb=&symbread($urlsymb);
1.534     albertel 12350:     if ($symb) {
1.620     albertel 12351: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12352: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12353: 	if (defined($cached)) { 
                   12354: 	    return $result;
                   12355: 	}
1.534     albertel 12356: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12357: 	my $title='';
1.907     albertel 12358: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12359: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12360: 	} else {
                   12361: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12362: 		    &GDBM_READER(),0640)) {
                   12363: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12364: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12365: 		untie(%bighash);
                   12366: 	    }
1.534     albertel 12367: 	}
                   12368: 	$title=~s/\&colon\;/\:/gs;
                   12369: 	if ($title) {
1.1159    www      12370: # Remember both $symb and $title for dynamic metadata
                   12371:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12372:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12373: # Cache this title and then return it
1.599     albertel 12374: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12375: 	}
                   12376: 	$urlsymb=$url;
                   12377:     }
                   12378:     my $title=&metadata($urlsymb,'title');
                   12379:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12380:     return $title;
1.301     www      12381: }
1.613     albertel 12382: 
1.614     albertel 12383: sub get_slot {
                   12384:     my ($which,$cnum,$cdom)=@_;
                   12385:     if (!$cnum || !$cdom) {
1.790     albertel 12386: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12387: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12388: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12389:     }
1.703     albertel 12390:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12391:     my %slotinfo;
                   12392:     if (exists($remembered{$key})) {
                   12393: 	$slotinfo{$which} = $remembered{$key};
                   12394:     } else {
                   12395: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12396: 	&Apache::lonhomework::showhash(%slotinfo);
                   12397: 	my ($tmp)=keys(%slotinfo);
                   12398: 	if ($tmp=~/^error:/) { return (); }
                   12399: 	$remembered{$key} = $slotinfo{$which};
                   12400:     }
1.616     albertel 12401:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12402: 	return %{$slotinfo{$which}};
                   12403:     }
                   12404:     return $slotinfo{$which};
1.614     albertel 12405: }
1.1150    raeburn  12406: 
                   12407: sub get_reservable_slots {
                   12408:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12409:     my $now = time;
                   12410:     my $reservable_info;
                   12411:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12412:     if (exists($remembered{$key})) {
                   12413:         $reservable_info = $remembered{$key};
                   12414:     } else {
                   12415:         my %resv;
                   12416:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12417:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12418:         $reservable_info = \%resv;
                   12419:         $remembered{$key} = $reservable_info;
                   12420:     }
                   12421:     return $reservable_info;
                   12422: }
                   12423: 
                   12424: sub get_course_slots {
                   12425:     my ($cnum,$cdom) = @_;
                   12426:     my $hashid=$cnum.':'.$cdom;
                   12427:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12428:     if (defined($cached)) {
                   12429:         if (ref($result) eq 'HASH') {
                   12430:             return %{$result};
                   12431:         }
                   12432:     } else {
                   12433:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12434:         my ($tmp) = keys(%slots);
                   12435:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12436:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12437:             return %slots;
                   12438:         }
                   12439:     }
                   12440:     return;
                   12441: }
                   12442: 
                   12443: sub devalidate_slots_cache {
                   12444:     my ($cnum,$cdom)=@_;
                   12445:     my $hashid=$cnum.':'.$cdom;
                   12446:     &devalidate_cache_new('allslots',$hashid);
                   12447: }
                   12448: 
1.1172.2.8  raeburn  12449: sub get_coursechange {
                   12450:     my ($cdom,$cnum) = @_;
                   12451:     if ($cdom eq '' || $cnum eq '') {
                   12452:         return unless ($env{'request.course.id'});
                   12453:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12454:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12455:     }
                   12456:     my $hashid=$cdom.'_'.$cnum;
                   12457:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12458:     if ((defined($cached)) && ($change ne '')) {
                   12459:         return $change;
                   12460:     } else {
                   12461:         my %crshash;
                   12462:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12463:         if ($crshash{'internal.contentchange'} eq '') {
                   12464:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12465:             if ($change eq '') {
                   12466:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12467:                 $change = $crshash{'internal.created'};
                   12468:             }
                   12469:         } else {
                   12470:             $change = $crshash{'internal.contentchange'};
                   12471:         }
                   12472:         my $cachetime = 600;
                   12473:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12474:     }
                   12475:     return $change;
                   12476: }
                   12477: 
                   12478: sub devalidate_coursechange_cache {
                   12479:     my ($cnum,$cdom)=@_;
                   12480:     my $hashid=$cnum.':'.$cdom;
                   12481:     &devalidate_cache_new('crschange',$hashid);
                   12482: }
                   12483: 
1.31      www      12484: # ------------------------------------------------- Update symbolic store links
                   12485: 
                   12486: sub symblist {
                   12487:     my ($mapname,%newhash)=@_;
1.438     www      12488:     $mapname=&deversion(&declutter($mapname));
1.31      www      12489:     my %hash;
1.620     albertel 12490:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12491:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12492:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12493: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12494: 		next if ($url eq 'last_known'
                   12495: 			 && $env{'form.no_update_last_known'});
                   12496: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12497: 						    $newhash{$url}->[1],
                   12498: 						    $newhash{$url}->[0]);
1.191     harris41 12499:             }
1.31      www      12500:             if (untie(%hash)) {
                   12501: 		return 'ok';
                   12502:             }
                   12503:         }
                   12504:     }
                   12505:     return 'error';
1.212     www      12506: }
                   12507: 
                   12508: # --------------------------------------------------------------- Verify a symb
                   12509: 
                   12510: sub symbverify {
1.1172.2.11  raeburn  12511:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12512:     my $thisfn=$thisurl;
1.439     www      12513:     $thisfn=&declutter($thisfn);
1.215     www      12514: # direct jump to resource in page or to a sequence - will construct own symbs
                   12515:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12516: # check URL part
1.409     www      12517:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12518: 
1.431     www      12519:     unless ($url eq $thisfn) { return 0; }
1.213     www      12520: 
1.216     www      12521:     $symb=&symbclean($symb);
1.510     www      12522:     $thisurl=&deversion($thisurl);
1.439     www      12523:     $thisfn=&deversion($thisfn);
1.213     www      12524: 
                   12525:     my %bighash;
                   12526:     my $okay=0;
1.431     www      12527: 
1.620     albertel 12528:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12529:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12530:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12531:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12532:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12533:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12534:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12535:             }
                   12536:         }
                   12537:         my $ids;
1.1172.2.122  raeburn  12538:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12539:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12540:         } else {
                   12541:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12542:         }
1.1102    raeburn  12543:         unless ($ids) {
1.1172.2.13  raeburn  12544:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12545:             $ids=$bighash{$idkey};
1.216     www      12546:         }
                   12547:         if ($ids) {
                   12548: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12549:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12550:                 $symb =~ s/\?.+$//;
                   12551:             }
1.800     albertel 12552: 	    foreach my $id (split(/\,/,$ids)) {
                   12553: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12554:                if (
                   12555:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12556:    eq $symb) {
1.1172.2.11  raeburn  12557:                    if (ref($encstate)) {
                   12558:                        $$encstate = $bighash{'encrypted_'.$id};
                   12559:                    }
1.1172.2.13  raeburn  12560:                    if (($env{'request.role.adv'}) ||
                   12561:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12562:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12563:                        $okay=1;
                   12564:                        last;
                   12565:                    }
                   12566:                }
                   12567:            }
1.216     www      12568:         }
1.213     www      12569: 	untie(%bighash);
                   12570:     }
                   12571:     return $okay;
1.31      www      12572: }
                   12573: 
1.210     www      12574: # --------------------------------------------------------------- Clean-up symb
                   12575: 
                   12576: sub symbclean {
                   12577:     my $symb=shift;
1.568     albertel 12578:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12579: # remove version from map
                   12580:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12581: 
1.210     www      12582: # remove version from URL
                   12583:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12584: 
1.507     www      12585: # remove wrapper
                   12586: 
1.510     www      12587:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12588:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12589:     return $symb;
1.409     www      12590: }
                   12591: 
                   12592: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12593: 
                   12594: sub encode_symb {
                   12595:     my ($map,$resid,$url)=@_;
                   12596:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12597: }
1.409     www      12598: 
                   12599: sub decode_symb {
1.568     albertel 12600:     my $symb=shift;
                   12601:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12602:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12603:     return (&fixversion($map),$resid,&fixversion($url));
                   12604: }
                   12605: 
                   12606: sub fixversion {
                   12607:     my $fn=shift;
1.609     banghart 12608:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12609:     my %bighash;
                   12610:     my $uri=&clutter($fn);
1.620     albertel 12611:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12612: # is this cached?
1.599     albertel 12613:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12614:     if (defined($cached)) { return $result; }
                   12615: # unfortunately not cached, or expired
1.620     albertel 12616:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12617: 	    &GDBM_READER(),0640)) {
                   12618:  	if ($bighash{'version_'.$uri}) {
                   12619:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12620:  	    unless (($version eq 'mostrecent') || 
                   12621: 		    ($version==&getversion($uri))) {
1.440     www      12622:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12623:  	    }
                   12624:  	}
                   12625:  	untie %bighash;
1.413     www      12626:     }
1.599     albertel 12627:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12628: }
                   12629: 
                   12630: sub deversion {
                   12631:     my $url=shift;
                   12632:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12633:     return $url;
1.210     www      12634: }
                   12635: 
1.31      www      12636: # ------------------------------------------------------ Return symb list entry
                   12637: 
                   12638: sub symbread {
1.1172.2.126  raeburn  12639:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12640:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12641:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12642:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12643:         unless (ref($possibles) eq 'HASH') {
                   12644:             if ($ignorecachednull) {
                   12645:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12646:             } else {
                   12647:                 return $env{$cache_str};
                   12648:             }
1.1172.2.66  raeburn  12649:         }
                   12650:     }
1.242     www      12651: # no filename provided? try from environment
1.1172.2.54  raeburn  12652:     unless ($thisfn) {
1.620     albertel 12653:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12654:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12655:         }
                   12656:         $thisfn=$env{'request.filename'};
1.44      www      12657:     }
1.569     albertel 12658:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12659: # is that filename actually a symb? Verify, clean, and return
                   12660:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12661: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12662: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12663: 	}
1.242     www      12664:     }
1.44      www      12665:     $thisfn=declutter($thisfn);
1.31      www      12666:     my %hash;
1.37      www      12667:     my %bighash;
                   12668:     my $syval='';
1.620     albertel 12669:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12670:         my $targetfn = $thisfn;
1.609     banghart 12671:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12672:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12673:         }
1.687     albertel 12674: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12675: 	    $targetfn=$1;
                   12676: 	}
1.1172.2.128  raeburn  12677:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12678:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12679:                           &GDBM_READER(),0640)) {
                   12680: 	        $syval=$hash{$targetfn};
                   12681:                 untie(%hash);
                   12682:             }
1.1172.2.128  raeburn  12683:             if ($syval && $checkforblock) {
                   12684:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12685:                 if (@blockers) {
                   12686:                     $syval='';
                   12687:                 }
                   12688:             }
1.37      www      12689:         }
                   12690: # ---------------------------------------------------------- There was an entry
                   12691:         if ($syval) {
1.601     albertel 12692: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12693: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12694: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12695: 		    #return $env{$cache_str}='';
1.601     albertel 12696: 		#}    
                   12697: 		#$syval.=$1;
                   12698: 	    #}
1.37      www      12699:         } else {
                   12700: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12701:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12702:                             &GDBM_READER(),0640)) {
1.37      www      12703: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12704:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12705:               unless ($ids) { 
                   12706:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12707:               }
                   12708:               unless ($ids) {
                   12709: # alias?
                   12710: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12711:               }
1.37      www      12712:               if ($ids) {
                   12713: # ------------------------------------------------------------------- Has ID(s)
                   12714:                  my @possibilities=split(/\,/,$ids);
1.39      www      12715:                  if ($#possibilities==0) {
                   12716: # ----------------------------------------------- There is only one possibility
1.37      www      12717: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12718: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12719: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12720:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12721:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12722:                              $possibles->{$syval} = 1;
                   12723:                          }
1.1172.2.66  raeburn  12724:                      }
                   12725:                      if ($checkforblock) {
1.1172.2.126  raeburn  12726:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12727:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12728:                              if (@blockers) {
                   12729:                                  $syval = '';
                   12730:                                  untie(%bighash);
                   12731:                                  return $env{$cache_str}='';
                   12732:                              }
1.1172.2.66  raeburn  12733:                          }
                   12734:                      }
                   12735:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12736: # ------------------------------------------ There is more than one possibility
                   12737:                      my $realpossible=0;
1.800     albertel 12738:                      foreach my $id (@possibilities) {
                   12739: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12740:                          my $canaccess;
                   12741:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12742:                              $canaccess = 1;
                   12743:                          } else {
                   12744:                              $canaccess = &allowed('bre',$file);
                   12745:                          }
                   12746:                          if ($canaccess) {
                   12747:          		     my ($mapid,$resid)=split(/\./,$id);
                   12748:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12749:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12750:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12751:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12752:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12753:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12754:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12755:                                      if (@blockers > 0) {
                   12756:                                          $syval = '';
                   12757:                                      } else {
1.1172.2.66  raeburn  12758:                                          $syval = $poss_syval;
                   12759:                                          $realpossible++;
                   12760:                                      }
                   12761:                                  } else {
                   12762:                                      $syval = $poss_syval;
                   12763:                                      $realpossible++;
                   12764:                                  }
1.1172.2.126  raeburn  12765:                                  if ($syval) {
                   12766:                                      if (ref($possibles) eq 'HASH') {
                   12767:                                          $possibles->{$syval} = 1;
                   12768:                                      }
                   12769:                                  }
1.1172.2.66  raeburn  12770:                              }
1.39      www      12771: 			 }
1.191     harris41 12772:                      }
1.39      www      12773: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12774:                  } else {
                   12775:                      $syval='';
1.37      www      12776:                  }
                   12777: 	      }
1.1172.2.66  raeburn  12778:               untie(%bighash);
1.481     raeburn  12779:            }
1.31      www      12780:         }
1.62      www      12781:         if ($syval) {
1.1172.2.128  raeburn  12782: 	    return $env{$cache_str}=$syval;
1.62      www      12783:         }
1.31      www      12784:     }
1.949     raeburn  12785:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12786:     return $env{$cache_str}='';
1.31      www      12787: }
                   12788: 
                   12789: # ---------------------------------------------------------- Return random seed
                   12790: 
1.32      www      12791: sub numval {
                   12792:     my $txt=shift;
                   12793:     $txt=~tr/A-J/0-9/;
                   12794:     $txt=~tr/a-j/0-9/;
                   12795:     $txt=~tr/K-T/0-9/;
                   12796:     $txt=~tr/k-t/0-9/;
                   12797:     $txt=~tr/U-Z/0-5/;
                   12798:     $txt=~tr/u-z/0-5/;
                   12799:     $txt=~s/\D//g;
1.564     albertel 12800:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12801:     return int($txt);
1.368     albertel 12802: }
                   12803: 
1.484     albertel 12804: sub numval2 {
                   12805:     my $txt=shift;
                   12806:     $txt=~tr/A-J/0-9/;
                   12807:     $txt=~tr/a-j/0-9/;
                   12808:     $txt=~tr/K-T/0-9/;
                   12809:     $txt=~tr/k-t/0-9/;
                   12810:     $txt=~tr/U-Z/0-5/;
                   12811:     $txt=~tr/u-z/0-5/;
                   12812:     $txt=~s/\D//g;
                   12813:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12814:     my $total;
                   12815:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12816:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12817:     return int($total);
                   12818: }
                   12819: 
1.575     albertel 12820: sub numval3 {
                   12821:     use integer;
                   12822:     my $txt=shift;
                   12823:     $txt=~tr/A-J/0-9/;
                   12824:     $txt=~tr/a-j/0-9/;
                   12825:     $txt=~tr/K-T/0-9/;
                   12826:     $txt=~tr/k-t/0-9/;
                   12827:     $txt=~tr/U-Z/0-5/;
                   12828:     $txt=~tr/u-z/0-5/;
                   12829:     $txt=~s/\D//g;
                   12830:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12831:     my $total;
                   12832:     foreach my $val (@txts) { $total+=$val; }
                   12833:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12834:     return $total;
                   12835: }
                   12836: 
1.675     albertel 12837: sub digest {
                   12838:     my ($data)=@_;
                   12839:     my $digest=&Digest::MD5::md5($data);
                   12840:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12841:     my ($e,$f);
                   12842:     {
                   12843:         use integer;
                   12844:         $e=($a+$b);
                   12845:         $f=($c+$d);
                   12846:         if ($_64bit) {
                   12847:             $e=(($e<<32)>>32);
                   12848:             $f=(($f<<32)>>32);
                   12849:         }
                   12850:     }
                   12851:     if (wantarray) {
                   12852: 	return ($e,$f);
                   12853:     } else {
                   12854: 	my $g;
                   12855: 	{
                   12856: 	    use integer;
                   12857: 	    $g=($e+$f);
                   12858: 	    if ($_64bit) {
                   12859: 		$g=(($g<<32)>>32);
                   12860: 	    }
                   12861: 	}
                   12862: 	return $g;
                   12863:     }
                   12864: }
                   12865: 
1.368     albertel 12866: sub latest_rnd_algorithm_id {
1.675     albertel 12867:     return '64bit5';
1.366     albertel 12868: }
1.32      www      12869: 
1.503     albertel 12870: sub get_rand_alg {
                   12871:     my ($courseid)=@_;
1.790     albertel 12872:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12873:     if ($courseid) {
1.620     albertel 12874: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12875:     }
                   12876:     return &latest_rnd_algorithm_id();
                   12877: }
                   12878: 
1.562     albertel 12879: sub validCODE {
                   12880:     my ($CODE)=@_;
                   12881:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12882:     return 0;
                   12883: }
                   12884: 
1.491     albertel 12885: sub getCODE {
1.620     albertel 12886:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12887:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12888: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12889: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12890: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12891:     }
                   12892:     return undef;
                   12893: }
1.1133    foxr     12894: #
                   12895: #  Determines the random seed for a specific context:
                   12896: #
                   12897: # parameters:
                   12898: #   symb      - in course context the symb for the seed.
                   12899: #   course_id - The course id of the form domain_coursenum.
                   12900: #   domain    - Domain for the user.
                   12901: #   course    - Course for the user.
                   12902: #   cenv      - environment of the course.
                   12903: #
                   12904: # NOTE:
                   12905: #   All parameters are picked out of the environment if missing
                   12906: #   or not defined.
                   12907: #   If a symb cannot be determined the current time is used instead.
                   12908: #
                   12909: #  For a given well defined symb, courside, domain, username,
                   12910: #  and course environment, the seed is reproducible.
                   12911: #
1.31      www      12912: sub rndseed {
1.1133    foxr     12913:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12914:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12915:     if (!defined($symb)) {
1.366     albertel 12916: 	unless ($symb=$wsymb) { return time; }
                   12917:     }
1.1146    foxr     12918:     if (!defined $courseid) { 
                   12919: 	$courseid=$wcourseid; 
                   12920:     }
                   12921:     if (!defined $domain) { $domain=$wdomain; }
                   12922:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12923: 
                   12924:     my $which;
                   12925:     if (defined($cenv->{'rndseed'})) {
                   12926: 	$which = $cenv->{'rndseed'};
                   12927:     } else {
                   12928: 	$which =&get_rand_alg($courseid);
                   12929:     }
1.491     albertel 12930:     if (defined(&getCODE())) {
1.675     albertel 12931: 	if ($which eq '64bit5') {
                   12932: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12933: 	} elsif ($which eq '64bit4') {
1.575     albertel 12934: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12935: 	} else {
                   12936: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12937: 	}
1.675     albertel 12938:     } elsif ($which eq '64bit5') {
                   12939: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12940:     } elsif ($which eq '64bit4') {
                   12941: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12942:     } elsif ($which eq '64bit3') {
                   12943: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12944:     } elsif ($which eq '64bit2') {
                   12945: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12946:     } elsif ($which eq '64bit') {
                   12947: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12948:     }
                   12949:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12950: }
                   12951: 
                   12952: sub rndseed_32bit {
                   12953:     my ($symb,$courseid,$domain,$username)=@_;
                   12954:     {
                   12955: 	use integer;
                   12956: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12957: 	my $symbseed=numval($symb) << 22;
                   12958: 	my $namechck=unpack("%32C*",$username) << 17;
                   12959: 	my $nameseed=numval($username) << 12;
                   12960: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12961: 	my $courseseed=unpack("%32C*",$courseid);
                   12962: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12963: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12964: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12965: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12966: 	return $num;
                   12967:     }
                   12968: }
                   12969: 
                   12970: sub rndseed_64bit {
                   12971:     my ($symb,$courseid,$domain,$username)=@_;
                   12972:     {
                   12973: 	use integer;
                   12974: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12975: 	my $symbseed=numval($symb) << 10;
                   12976: 	my $namechck=unpack("%32S*",$username);
                   12977: 	
                   12978: 	my $nameseed=numval($username) << 21;
                   12979: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12980: 	my $courseseed=unpack("%32S*",$courseid);
                   12981: 	
                   12982: 	my $num1=$symbchck+$symbseed+$namechck;
                   12983: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12984: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12985: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12986: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12987: 	return "$num1,$num2";
1.155     albertel 12988:     }
1.366     albertel 12989: }
                   12990: 
1.443     albertel 12991: sub rndseed_64bit2 {
                   12992:     my ($symb,$courseid,$domain,$username)=@_;
                   12993:     {
                   12994: 	use integer;
                   12995: 	# strings need to be an even # of cahracters long, it it is odd the
                   12996:         # last characters gets thrown away
                   12997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12998: 	my $symbseed=numval($symb) << 10;
                   12999: 	my $namechck=unpack("%32S*",$username.' ');
                   13000: 	
                   13001: 	my $nameseed=numval($username) << 21;
1.501     albertel 13002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13003: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13004: 	
                   13005: 	my $num1=$symbchck+$symbseed+$namechck;
                   13006: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13008: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13010: 	return "$num1,$num2";
                   13011:     }
                   13012: }
                   13013: 
                   13014: sub rndseed_64bit3 {
                   13015:     my ($symb,$courseid,$domain,$username)=@_;
                   13016:     {
                   13017: 	use integer;
                   13018: 	# strings need to be an even # of cahracters long, it it is odd the
                   13019:         # last characters gets thrown away
                   13020: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13021: 	my $symbseed=numval2($symb) << 10;
                   13022: 	my $namechck=unpack("%32S*",$username.' ');
                   13023: 	
                   13024: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13025: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13026: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13027: 	
                   13028: 	my $num1=$symbchck+$symbseed+$namechck;
                   13029: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13031: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13033: 	
1.503     albertel 13034: 	return "$num1:$num2";
1.443     albertel 13035:     }
                   13036: }
                   13037: 
1.575     albertel 13038: sub rndseed_64bit4 {
                   13039:     my ($symb,$courseid,$domain,$username)=@_;
                   13040:     {
                   13041: 	use integer;
                   13042: 	# strings need to be an even # of cahracters long, it it is odd the
                   13043:         # last characters gets thrown away
                   13044: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13045: 	my $symbseed=numval3($symb) << 10;
                   13046: 	my $namechck=unpack("%32S*",$username.' ');
                   13047: 	
                   13048: 	my $nameseed=numval3($username) << 21;
                   13049: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13050: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13051: 	
                   13052: 	my $num1=$symbchck+$symbseed+$namechck;
                   13053: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13055: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13057: 	
1.575     albertel 13058: 	return "$num1:$num2";
                   13059:     }
                   13060: }
                   13061: 
1.675     albertel 13062: sub rndseed_64bit5 {
                   13063:     my ($symb,$courseid,$domain,$username)=@_;
                   13064:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13065:     return "$num1:$num2";
                   13066: }
                   13067: 
1.366     albertel 13068: sub rndseed_CODE_64bit {
                   13069:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13070:     {
1.366     albertel 13071: 	use integer;
1.443     albertel 13072: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13073: 	my $symbseed=numval2($symb);
1.491     albertel 13074: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13075: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13076: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13077: 	my $num1=$symbseed+$CODEchck;
                   13078: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13079: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13080: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13081: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13082: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13083: 	return "$num1:$num2";
1.366     albertel 13084:     }
                   13085: }
                   13086: 
1.575     albertel 13087: sub rndseed_CODE_64bit4 {
                   13088:     my ($symb,$courseid,$domain,$username)=@_;
                   13089:     {
                   13090: 	use integer;
                   13091: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13092: 	my $symbseed=numval3($symb);
                   13093: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13094: 	my $CODEseed=numval3(&getCODE());
                   13095: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13096: 	my $num1=$symbseed+$CODEchck;
                   13097: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13098: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13099: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13100: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13101: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13102: 	return "$num1:$num2";
                   13103:     }
                   13104: }
                   13105: 
1.675     albertel 13106: sub rndseed_CODE_64bit5 {
                   13107:     my ($symb,$courseid,$domain,$username)=@_;
                   13108:     my $code = &getCODE();
                   13109:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13110:     return "$num1:$num2";
                   13111: }
                   13112: 
1.366     albertel 13113: sub setup_random_from_rndseed {
                   13114:     my ($rndseed)=@_;
1.503     albertel 13115:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13116: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13117:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13118:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13119:         } else {
                   13120:             &Math::Random::random_set_seed($num1,$num2);
                   13121:         }
1.366     albertel 13122:     } else {
                   13123: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13124:     }
1.36      albertel 13125: }
                   13126: 
1.474     albertel 13127: sub latest_receipt_algorithm_id {
1.835     albertel 13128:     return 'receipt3';
1.474     albertel 13129: }
                   13130: 
1.480     www      13131: sub recunique {
                   13132:     my $fucourseid=shift;
                   13133:     my $unique;
1.835     albertel 13134:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13135: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13136: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13137:     } else {
                   13138: 	$unique=$perlvar{'lonReceipt'};
                   13139:     }
                   13140:     return unpack("%32C*",$unique);
                   13141: }
                   13142: 
                   13143: sub recprefix {
                   13144:     my $fucourseid=shift;
                   13145:     my $prefix;
1.835     albertel 13146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13147: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13148: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13149:     } else {
                   13150: 	$prefix=$perlvar{'lonHostID'};
                   13151:     }
                   13152:     return unpack("%32C*",$prefix);
                   13153: }
                   13154: 
1.76      www      13155: sub ireceipt {
1.474     albertel 13156:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13157: 
                   13158:     my $return =&recprefix($fucourseid).'-';
                   13159: 
                   13160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13161: 	$env{'request.state'} eq 'construct') {
                   13162: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13163: 	return $return;
                   13164:     }
                   13165: 
1.76      www      13166:     my $cuname=unpack("%32C*",$funame);
                   13167:     my $cudom=unpack("%32C*",$fudom);
                   13168:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13169:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13170:     my $cunique=&recunique($fucourseid);
1.474     albertel 13171:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13172:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13173: 
1.790     albertel 13174: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13175: 			       
                   13176: 	$return.= ($cunique%$cuname+
                   13177: 		   $cunique%$cudom+
                   13178: 		   $cusymb%$cuname+
                   13179: 		   $cusymb%$cudom+
                   13180: 		   $cucourseid%$cuname+
                   13181: 		   $cucourseid%$cudom+
                   13182: 		   $cpart%$cuname+
                   13183: 		   $cpart%$cudom);
                   13184:     } else {
                   13185: 	$return.= ($cunique%$cuname+
                   13186: 		   $cunique%$cudom+
                   13187: 		   $cusymb%$cuname+
                   13188: 		   $cusymb%$cudom+
                   13189: 		   $cucourseid%$cuname+
                   13190: 		   $cucourseid%$cudom);
                   13191:     }
                   13192:     return $return;
1.76      www      13193: }
                   13194: 
                   13195: sub receipt {
1.474     albertel 13196:     my ($part)=@_;
1.790     albertel 13197:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13198:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13199: }
1.260     ng       13200: 
1.790     albertel 13201: sub whichuser {
                   13202:     my ($passedsymb)=@_;
                   13203:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13204:     if (defined($env{'form.grade_symb'})) {
                   13205: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13206: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13207: 	if (!$allowed &&
                   13208: 	    exists($env{'request.course.sec'}) &&
                   13209: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13210: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13211: 			      '/'.$env{'request.course.sec'});
                   13212: 	}
                   13213: 	if ($allowed) {
                   13214: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13215: 	    $courseid=$tmp_courseid;
                   13216: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13217: 	    ($name)=&get_env_multiple('form.grade_username');
                   13218: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13219: 	}
                   13220:     }
                   13221:     if (!$passedsymb) {
                   13222: 	$symb=&symbread();
                   13223:     } else {
                   13224: 	$symb=$passedsymb;
                   13225:     }
                   13226:     $courseid=$env{'request.course.id'};
                   13227:     $domain=$env{'user.domain'};
                   13228:     $name=$env{'user.name'};
                   13229:     if ($name eq 'public' && $domain eq 'public') {
                   13230: 	if (!defined($env{'form.username'})) {
                   13231: 	    $env{'form.username'}.=time.rand(10000000);
                   13232: 	}
                   13233: 	$name.=$env{'form.username'};
                   13234:     }
                   13235:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13236: 
                   13237: }
                   13238: 
1.36      albertel 13239: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13240: # returns either the contents of the file or 
                   13241: # -1 if the file doesn't exist
1.481     raeburn  13242: #
                   13243: # if the target is a file that was uploaded via DOCS, 
                   13244: # a check will be made to see if a current copy exists on the local server,
                   13245: # if it does this will be served, otherwise a copy will be retrieved from
                   13246: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13247: # the local server.   
1.472     albertel 13248: 
1.36      albertel 13249: sub getfile {
1.538     albertel 13250:     my ($file) = @_;
1.609     banghart 13251:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13252:     &repcopy($file);
                   13253:     return &readfile($file);
                   13254: }
                   13255: 
                   13256: sub repcopy_userfile {
                   13257:     my ($file)=@_;
1.1142    raeburn  13258:     my $londocroot = $perlvar{'lonDocRoot'};
                   13259:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13260:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13261:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13262: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13263:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13264:     if (-e "$file") {
1.828     www      13265: # we already have a local copy, check it out
1.538     albertel 13266: 	my @fileinfo = stat($file);
1.828     www      13267: 	my $rtncode;
                   13268: 	my $info;
1.538     albertel 13269: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13270: 	if ($lwpresp ne 'ok') {
1.828     www      13271: # there is no such file anymore, even though we had a local copy
1.482     albertel 13272: 	    if ($rtncode eq '404') {
1.538     albertel 13273: 		unlink($file);
1.482     albertel 13274: 	    }
                   13275: 	    return -1;
                   13276: 	}
                   13277: 	if ($info < $fileinfo[9]) {
1.828     www      13278: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13279: 	    return 'ok';
1.828     www      13280: 	} else {
                   13281: # the file is outdated, get rid of it
                   13282: 	    unlink($file);
1.482     albertel 13283: 	}
1.828     www      13284:     }
                   13285: # one way or the other, at this point, we don't have the file
                   13286: # construct the correct path for the file
                   13287:     my @parts = ($cdom,$cnum); 
                   13288:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13289: 	push @parts, split(/\//,$1);
                   13290:     }
                   13291:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13292:     foreach my $part (@parts) {
                   13293: 	$path .= '/'.$part;
                   13294: 	if (!-e $path) {
                   13295: 	    mkdir($path,0770);
1.482     albertel 13296: 	}
                   13297:     }
1.828     www      13298: # now the path exists for sure
                   13299: # get a user agent
                   13300:     my $ua=new LWP::UserAgent;
                   13301:     my $transferfile=$file.'.in.transfer';
                   13302: # FIXME: this should flock
                   13303:     if (-e $transferfile) { return 'ok'; }
                   13304:     my $request;
                   13305:     $uri=~s/^\///;
1.980     raeburn  13306:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13307:     my $hostname = &hostname($homeserver);
1.980     raeburn  13308:     my $protocol = $protocol{$homeserver};
                   13309:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13310:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13311:     my $response=$ua->request($request,$transferfile);
                   13312: # did it work?
                   13313:     if ($response->is_error()) {
                   13314: 	unlink($transferfile);
                   13315: 	&logthis("Userfile repcopy failed for $uri");
                   13316: 	return -1;
                   13317:     }
                   13318: # worked, rename the transfer file
                   13319:     rename($transferfile,$file);
1.607     raeburn  13320:     return 'ok';
1.481     raeburn  13321: }
                   13322: 
1.517     albertel 13323: sub tokenwrapper {
                   13324:     my $uri=shift;
1.980     raeburn  13325:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13326:     $uri=~s|^/||;
1.620     albertel 13327:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13328:     my $token=$1;
1.552     albertel 13329:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13330:     if ($udom && $uname && $file) {
                   13331: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13332:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13333:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13334:         my $hostname = &hostname($homeserver);
1.980     raeburn  13335:         my $protocol = $protocol{$homeserver};
                   13336:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13337:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13338:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13339:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13340:     } else {
                   13341:         return '/adm/notfound.html';
                   13342:     }
                   13343: }
                   13344: 
1.828     www      13345: # call with reqtype HEAD: get last modification time
                   13346: # call with reqtype GET: get the file contents
                   13347: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13348: #
1.481     raeburn  13349: sub getuploaded {
                   13350:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13351:     $uri=~s/^\///;
1.980     raeburn  13352:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13353:     my $hostname = &hostname($homeserver);
1.980     raeburn  13354:     my $protocol = $protocol{$homeserver};
                   13355:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13356:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13357:     my $ua=new LWP::UserAgent;
                   13358:     my $request=new HTTP::Request($reqtype,$uri);
                   13359:     my $response=$ua->request($request);
                   13360:     $$rtncode = $response->code;
1.482     albertel 13361:     if (! $response->is_success()) {
                   13362: 	return 'failed';
                   13363:     }      
                   13364:     if ($reqtype eq 'HEAD') {
1.486     www      13365: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13366:     } elsif ($reqtype eq 'GET') {
                   13367: 	$$info = $response->content;
1.472     albertel 13368:     }
1.482     albertel 13369:     return 'ok';
1.36      albertel 13370: }
                   13371: 
1.481     raeburn  13372: sub readfile {
                   13373:     my $file = shift;
                   13374:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13375:     my $fh;
1.1172.2.96  raeburn  13376:     open($fh,"<",$file);
1.481     raeburn  13377:     my $a='';
1.800     albertel 13378:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13379:     return $a;
                   13380: }
                   13381: 
1.36      albertel 13382: sub filelocation {
1.590     banghart 13383:     my ($dir,$file) = @_;
                   13384:     my $location;
                   13385:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13386: 
                   13387:     if ($file =~ m-^/adm/-) {
                   13388: 	$file=~s-^/adm/wrapper/-/-;
                   13389: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13390:     }
1.882     albertel 13391: 
1.1139    www      13392:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13393:         $location = $file;
1.609     banghart 13394:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13395:         my ($udom,$uname,$filename)=
1.811     albertel 13396:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13397:         my $home=&homeserver($uname,$udom);
                   13398:         my $is_me=0;
                   13399:         my @ids=&current_machine_ids();
                   13400:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13401:         if ($is_me) {
1.1117    foxr     13402:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13403:         } else {
                   13404:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13405:   	      $udom.'/'.$uname.'/'.$filename;
                   13406:         }
1.882     albertel 13407:     } elsif ($file =~ m-^/adm/-) {
                   13408: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13409:     } else {
                   13410:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13411:         $file=~s:^/(res|priv)/:/:;
                   13412:         my $space=$1;
1.590     banghart 13413:         if ( !( $file =~ m:^/:) ) {
                   13414:             $location = $dir. '/'.$file;
                   13415:         } else {
1.1142    raeburn  13416:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13417:         }
1.59      albertel 13418:     }
1.590     banghart 13419:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13420:     while ($location=~m{/\.\./}) {
                   13421: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13422: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13423: 	} else {
                   13424: 	    $location=~ s{/\.\./}{/}g;
                   13425: 	}
                   13426:     } #remove dir/..
1.590     banghart 13427:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13428:     return $location;
1.46      www      13429: }
1.36      albertel 13430: 
1.46      www      13431: sub hreflocation {
                   13432:     my ($dir,$file)=@_;
1.980     raeburn  13433:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13434: 	$file=filelocation($dir,$file);
1.700     albertel 13435:     } elsif ($file=~m-^/adm/-) {
                   13436: 	$file=~s-^/adm/wrapper/-/-;
                   13437: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13438:     }
                   13439:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13440: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13441:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13442: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13443: 	        {/uploaded/$1/$2/}x;
1.46      www      13444:     }
1.913     albertel 13445:     if ($file=~ m{^/userfiles/}) {
                   13446: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13447:     }
1.462     albertel 13448:     return $file;
1.465     albertel 13449: }
                   13450: 
1.1139    www      13451: 
                   13452: 
                   13453: 
                   13454: 
1.465     albertel 13455: sub current_machine_domains {
1.853     albertel 13456:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13457: }
                   13458: 
                   13459: sub machine_domains {
                   13460:     my ($hostname) = @_;
1.465     albertel 13461:     my @domains;
1.838     albertel 13462:     my %hostname = &all_hostnames();
1.465     albertel 13463:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13464: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13465: 	if ($hostname eq $name) {
1.844     albertel 13466: 	    push(@domains,&host_domain($id));
1.465     albertel 13467: 	}
                   13468:     }
                   13469:     return @domains;
                   13470: }
                   13471: 
                   13472: sub current_machine_ids {
1.853     albertel 13473:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13474: }
                   13475: 
                   13476: sub machine_ids {
                   13477:     my ($hostname) = @_;
                   13478:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13479:     my @ids;
1.888     albertel 13480:     my %name_to_host = &all_names();
1.889     albertel 13481:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13482: 	return @{ $name_to_host{$hostname} };
                   13483:     }
                   13484:     return;
1.31      www      13485: }
                   13486: 
1.824     raeburn  13487: sub additional_machine_domains {
                   13488:     my @domains;
1.1172.2.142  raeburn  13489:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13490:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13491:             while( my $line = <$fh>) {
                   13492:                 chomp($line);
                   13493:                 $line =~ s/\s//g;
                   13494:                 push(@domains,$line);
                   13495:             }
                   13496:             close($fh);
                   13497:         }
1.824     raeburn  13498:     }
                   13499:     return @domains;
                   13500: }
                   13501: 
                   13502: sub default_login_domain {
                   13503:     my $domain = $perlvar{'lonDefDomain'};
                   13504:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13505:     foreach my $posdom (&current_machine_domains(),
                   13506:                         &additional_machine_domains()) {
                   13507:         if (lc($posdom) eq lc($testdomain)) {
                   13508:             $domain=$posdom;
                   13509:             last;
                   13510:         }
                   13511:     }
                   13512:     return $domain;
                   13513: }
                   13514: 
1.1172.2.106  raeburn  13515: sub shared_institution {
1.1172.2.136  raeburn  13516:     my ($dom,$lonhost) = @_;
                   13517:     if ($lonhost eq '') {
                   13518:         $lonhost = $perlvar{'lonHostID'};
                   13519:     }
1.1172.2.106  raeburn  13520:     my $same_intdom;
1.1172.2.136  raeburn  13521:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13522:     if ($hostintdom ne '') {
                   13523:         my %iphost = &get_iphost();
                   13524:         my $primary_id = &domain($dom,'primary');
                   13525:         my $primary_ip = &get_host_ip($primary_id);
                   13526:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13527:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13528:                 my $intdom = &internet_dom($id);
                   13529:                 if ($intdom eq $hostintdom) {
                   13530:                     $same_intdom = 1;
                   13531:                     last;
                   13532:                 }
                   13533:             }
                   13534:         }
                   13535:     }
                   13536:     return $same_intdom;
                   13537: }
                   13538: 
1.1172.2.120  raeburn  13539: sub uses_sts {
                   13540:     my ($ignore_cache) = @_;
                   13541:     my $lonhost = $perlvar{'lonHostID'};
                   13542:     my $hostname = &hostname($lonhost);
                   13543:     my $sts_on;
                   13544:     if ($protocol{$lonhost} eq 'https') {
                   13545:         my $cachetime = 12*3600;
                   13546:         if (!$ignore_cache) {
                   13547:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13548:             if (defined($cached)) {
                   13549:                 return $sts_on;
                   13550:             }
                   13551:         }
1.1172.2.121  raeburn  13552:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13553:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13554:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13555:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13556:         if ($response->is_success) {
                   13557:             my $has_sts = $response->header('Strict-Transport-Security');
                   13558:             if ($has_sts eq '') {
                   13559:                 $sts_on = 0;
                   13560:             } else {
                   13561:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13562:                     my $maxage = $1;
                   13563:                     if ($maxage) {
                   13564:                         $sts_on = 1;
                   13565:                     } else {
                   13566:                         $sts_on = 0;
                   13567:                     }
                   13568:                 } else {
                   13569:                     $sts_on = 0;
                   13570:                 }
                   13571:             }
                   13572:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13573:         }
                   13574:     }
                   13575:     return;
                   13576: }
                   13577: 
1.1172.2.142  raeburn  13578: sub waf_allssl {
                   13579:     my ($host_name) = @_;
                   13580:     my $alias = &get_proxy_alias();
                   13581:     if ($host_name eq '') {
                   13582:         $host_name = $ENV{'SERVER_NAME'};
                   13583:     }
                   13584:     if (($host_name ne '') && ($alias eq $host_name)) {
                   13585:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   13586:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   13587:         if ($defdomdefaults{'waf_sslopt'}) {
                   13588:             return $defdomdefaults{'waf_sslopt'};
                   13589:         }
                   13590:     }
                   13591:     return;
                   13592: }
                   13593: 
1.1172.2.134  raeburn  13594: sub get_requestor_ip {
                   13595:     my ($r,$nolookup,$noproxy) = @_;
                   13596:     my $from_ip;
                   13597:     if (ref($r)) {
1.1172.2.142  raeburn  13598:         if ($r->can('useragent_ip')) {
                   13599:             if ($noproxy && $r->can('client_ip')) {
                   13600:                 $from_ip = $r->client_ip();
                   13601:             } else {
                   13602:                 $from_ip = $r->useragent_ip();
                   13603:             }
                   13604:         } elsif ($r->connection->can('remote_ip')) {
                   13605:             $from_ip = $r->connection->remote_ip();
                   13606:         } else {
                   13607:             $from_ip = $r->get_remote_host($nolookup);
                   13608:         }
1.1172.2.134  raeburn  13609:     } else {
                   13610:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13611:     }
1.1172.2.142  raeburn  13612:     return $from_ip if ($noproxy);
                   13613:    # Who controls proxy settings for server
                   13614:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   13615:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   13616:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   13617:         if ($proxyinfo->{'vpnint'}) {
                   13618:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   13619:                 return $from_ip;
                   13620:             }
                   13621:         }
                   13622:         if ($proxyinfo->{'trusted'}) {
                   13623:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   13624:                 my $ipheader = $proxyinfo->{'ipheader'};
                   13625:                 my ($ip,$xfor);
                   13626:                 if (ref($r)) {
                   13627:                     if ($ipheader) {
                   13628:                         $ip = $r->headers_in->{$ipheader};
                   13629:                     }
                   13630:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   13631:                 } else {
                   13632:                     if ($ipheader) {
                   13633:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   13634:                     }
                   13635:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   13636:                 }
                   13637:                 if (($ip eq '') && ($xfor ne '')) {
                   13638:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   13639:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   13640:                             $ip = $poss_ip;
                   13641:                             last;
                   13642:                         }
                   13643:                     }
                   13644:                 }
                   13645:                 if ($ip ne '') {
                   13646:                     return $ip;
                   13647:                 }
                   13648:             }
                   13649:         }
                   13650:     }
1.1172.2.134  raeburn  13651:     return $from_ip;
                   13652: }
                   13653: 
1.1172.2.142  raeburn  13654: sub get_proxy_settings {
                   13655:     my ($dom_in_use) = @_;
                   13656:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   13657:     my $proxyinfo = {
                   13658:                        ipheader => $domdefaults{'waf_ipheader'},
                   13659:                        trusted  => $domdefaults{'waf_trusted'},
                   13660:                        vpnint   => $domdefaults{'waf_vpnint'},
                   13661:                        vpnext   => $domdefaults{'waf_vpnext'},
                   13662:                        sslopt   => $domdefaults{'waf_sslopt'},
                   13663:                     };
                   13664:     return $proxyinfo;
                   13665: }
                   13666: 
                   13667: sub ip_match {
                   13668:     my ($ip,$pattern_str) = @_;
                   13669:     $ip=Net::CIDR::cidrvalidate($ip);
                   13670:     if ($ip) {
                   13671:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   13672:     }
                   13673:     return;
                   13674: }
                   13675: 
                   13676: sub get_proxy_alias {
                   13677:     my ($lonid) = @_;
                   13678:     if ($lonid eq '') {
                   13679:         $lonid = $perlvar{'lonHostID'};
                   13680:     }
                   13681:     if (!defined(&hostname($lonid))) {
                   13682:         return;
                   13683:     }
                   13684:     if ($lonid ne '') {
                   13685:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   13686:         if ($cached) {
                   13687:             return $alias;
                   13688:         }
                   13689:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13690:         if ($dom ne '') {
                   13691:             my $cachetime = 60*60*24;
                   13692:             my %domconfig =
                   13693:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13694:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13695:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   13696:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   13697:                 }
                   13698:             }
                   13699:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   13700:         }
                   13701:     }
                   13702:     return;
                   13703: }
                   13704: 
                   13705: sub use_proxy_alias {
                   13706:     my ($r,$lonid) = @_;
                   13707:     my $alias = &get_proxy_alias($lonid);
                   13708:     if ($alias) {
                   13709:         my $dom = &host_domain($lonid);
                   13710:         if ($dom ne '') {
                   13711:             my $proxyinfo = &get_proxy_settings($dom);
                   13712:             my ($vpnint,$remote_ip);
                   13713:             if (ref($proxyinfo) eq 'HASH') {
                   13714:                 $vpnint = $proxyinfo->{'vpnint'};
                   13715:                 if ($vpnint) {
                   13716:                     $remote_ip = &get_requestor_ip($r,1,1);
                   13717:                 }
                   13718:             }
                   13719:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   13720:                 return $alias;
                   13721:             }
                   13722:         }
                   13723:     }
                   13724:     return;
                   13725: }
                   13726: 
                   13727: sub alias_sso {
                   13728:     my ($lonid) = @_;
                   13729:     if ($lonid eq '') {
                   13730:         $lonid = $perlvar{'lonHostID'};
                   13731:     }
                   13732:     if (!defined(&hostname($lonid))) {
                   13733:         return;
                   13734:     }
                   13735:     if ($lonid ne '') {
                   13736:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   13737:         if ($cached) {
                   13738:             return $use_alias;
                   13739:         }
                   13740:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13741:         if ($dom ne '') {
                   13742:             my $cachetime = 60*60*24;
                   13743:             my %domconfig =
                   13744:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13745:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13746:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   13747:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   13748:                 }
                   13749:             }
                   13750:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   13751:         }
                   13752:     }
                   13753:     return;
                   13754: }
                   13755: 
                   13756: sub get_saml_landing {
                   13757:     my ($lonid) = @_;
                   13758:     if ($lonid eq '') {
                   13759:         my $defdom = &default_login_domain();
                   13760:         my @hosts = &current_machine_ids();
                   13761:         if (@hosts > 1) {
                   13762:             foreach my $hostid (@hosts) {
                   13763:                 if (&host_domain($hostid) eq $defdom) {
                   13764:                     $lonid = $hostid;
                   13765:                     last;
                   13766:                 }
                   13767:             }
                   13768:         } else {
                   13769:             $lonid = $perlvar{'lonHostID'};
                   13770:         }
                   13771:         if ($lonid) {
                   13772:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   13773:                 return;
                   13774:             }
                   13775:         } else {
                   13776:             return;
                   13777:         }
                   13778:     } elsif (!defined(&hostname($lonid))) {
                   13779:         return;
                   13780:     }
                   13781:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   13782:     if ($cached) {
                   13783:         return $landing;
                   13784:     }
                   13785:     my $dom = &Apache::lonnet::host_domain($lonid);
                   13786:     if ($dom ne '') {
                   13787:         my $cachetime = 60*60*24;
                   13788:         my %domconfig =
                   13789:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   13790:         if (ref($domconfig{'login'}) eq 'HASH') {
                   13791:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   13792:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   13793:                     $landing = 1;
                   13794:                 }
                   13795:             }
                   13796:         }
                   13797:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   13798:     }
                   13799:     return;
                   13800: }
                   13801: 
1.31      www      13802: # ------------------------------------------------------------- Declutters URLs
                   13803: 
                   13804: sub declutter {
                   13805:     my $thisfn=shift;
1.569     albertel 13806:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13807:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13808:         $thisfn=~s{^/home/httpd/html}{};
                   13809:     }
1.31      www      13810:     $thisfn=~s/^\///;
1.697     albertel 13811:     $thisfn=~s|^adm/wrapper/||;
                   13812:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13813:     $thisfn=~s/^res\///;
1.1172    bisitz   13814:     $thisfn=~s/^priv\///;
1.1032    raeburn  13815:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13816:         $thisfn=~s/\?.+$//;
                   13817:     }
1.268     www      13818:     return $thisfn;
                   13819: }
                   13820: 
                   13821: # ------------------------------------------------------------- Clutter up URLs
                   13822: 
                   13823: sub clutter {
                   13824:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13825:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13826: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13827:        $thisfn='/res'.$thisfn; 
                   13828:     }
1.1031    raeburn  13829:     if ($thisfn !~m|^/adm|) {
                   13830: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13831: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13832: 	} else {
                   13833: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13834: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13835: 	    if ($embstyle eq 'ssi'
                   13836: 		|| ($embstyle eq 'hdn')
                   13837: 		|| ($embstyle eq 'rat')
                   13838: 		|| ($embstyle eq 'prv')
                   13839: 		|| ($embstyle eq 'ign')) {
                   13840: 		#do nothing with these
                   13841: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13842: 		|| ($embstyle eq 'emb')
                   13843: 		|| ($embstyle eq 'wrp')) {
                   13844: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13845: 	    } elsif ($embstyle eq 'unk'
                   13846: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13847: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13848: 	    } else {
1.718     www      13849: #		&logthis("Got a blank emb style");
1.695     albertel 13850: 	    }
1.694     albertel 13851: 	}
                   13852:     }
1.31      www      13853:     return $thisfn;
1.12      www      13854: }
                   13855: 
1.787     albertel 13856: sub clutter_with_no_wrapper {
                   13857:     my $uri = &clutter(shift);
                   13858:     if ($uri =~ m-^/adm/-) {
                   13859: 	$uri =~ s-^/adm/wrapper/-/-;
                   13860: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13861:     }
                   13862:     return $uri;
                   13863: }
                   13864: 
1.557     albertel 13865: sub freeze_escape {
                   13866:     my ($value)=@_;
                   13867:     if (ref($value)) {
                   13868: 	$value=&nfreeze($value);
                   13869: 	return '__FROZEN__'.&escape($value);
                   13870:     }
                   13871:     return &escape($value);
                   13872: }
                   13873: 
1.11      www      13874: 
1.557     albertel 13875: sub thaw_unescape {
                   13876:     my ($value)=@_;
                   13877:     if ($value =~ /^__FROZEN__/) {
                   13878: 	substr($value,0,10,undef);
                   13879: 	$value=&unescape($value);
                   13880: 	return &thaw($value);
                   13881:     }
                   13882:     return &unescape($value);
                   13883: }
                   13884: 
1.436     albertel 13885: sub correct_line_ends {
                   13886:     my ($result)=@_;
                   13887:     $$result =~s/\r\n/\n/mg;
                   13888:     $$result =~s/\r/\n/mg;
1.415     albertel 13889: }
1.1       albertel 13890: # ================================================================ Main Program
                   13891: 
1.184     www      13892: sub goodbye {
1.204     albertel 13893:    &logthis("Starting Shut down");
1.443     albertel 13894: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13895:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13896: #converted
1.599     albertel 13897: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13898:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13899: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13900: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13901: #1.1 only
1.870     albertel 13902: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13903: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13904: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13905: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13906:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13907:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13908:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13909:    &flushcourselogs();
                   13910:    &logthis("Shutting down");
                   13911: }
                   13912: 
1.852     albertel 13913: sub get_dns {
1.1172.2.17  raeburn  13914:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13915:     if (!$ignore_cache) {
                   13916: 	my ($content,$cached)=
                   13917: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13918: 	if ($cached) {
1.1172.2.17  raeburn  13919: 	    &$func($content,$hashref);
1.869     albertel 13920: 	    return;
                   13921: 	}
                   13922:     }
                   13923: 
                   13924:     my %alldns;
1.1172.2.96  raeburn  13925:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13926:         foreach my $dns (<$config>) {
                   13927: 	    next if ($dns !~ /^\^(\S*)/x);
                   13928:             my $line = $1;
                   13929:             my ($host,$protocol) = split(/:/,$line);
                   13930:             if ($protocol ne 'https') {
                   13931:                 $protocol = 'http';
                   13932:             }
                   13933: 	    $alldns{$host} = $protocol;
1.979     raeburn  13934:         }
1.1172.2.96  raeburn  13935:         close($config);
1.869     albertel 13936:     }
                   13937:     while (%alldns) {
1.1172.2.52  raeburn  13938: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  13939:         my @content;
                   13940:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   13941:             my $command = (split('/',$url))[3];
                   13942:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   13943:             delete($alldns{$dns});
                   13944:             next if (($dir eq '') || ($file eq ''));
                   13945:             if (open(my $config,'<',"$dir/$file")) {
                   13946:                 @content = <$config>;
                   13947:                 close($config);
                   13948:             }
                   13949:         } else {
                   13950: 	    my $ua=new LWP::UserAgent;
                   13951:             $ua->timeout(30);
                   13952: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   13953: 	    my $response=$ua->request($request);
                   13954:             delete($alldns{$dns});
                   13955: 	    next if ($response->is_error());
                   13956: 	    @content = split("\n",$response->content);
                   13957:         }
1.1172.2.17  raeburn  13958:         unless ($nocache) {
1.1172.2.23  raeburn  13959: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13960:         }
                   13961: 	&$func(\@content,$hashref);
1.869     albertel 13962: 	return;
1.852     albertel 13963:     }
1.871     albertel 13964:     my $which = (split('/',$url))[3];
                   13965:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13966:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13967:         my @content = <$config>;
                   13968:         &$func(\@content,$hashref);
                   13969:     }
1.1172.2.17  raeburn  13970:     return;
                   13971: }
                   13972: 
                   13973: # ------------------------------------------------------Get DNS checksums file
                   13974: sub parse_dns_checksums_tab {
                   13975:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13976:     my $lonhost = $perlvar{'lonHostID'};
                   13977:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13978:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13979:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13980:     my $webconfdir = '/etc/httpd/conf';
                   13981:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13982:         $webconfdir = '/etc/apache2';
                   13983:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13984:         if ($1 >= 10) {
                   13985:             $webconfdir = '/etc/apache2';
                   13986:         }
                   13987:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13988:         if ($1 >= 10.0) {
                   13989:             $webconfdir = '/etc/apache2';
                   13990:         }
                   13991:     }
1.1172.2.17  raeburn  13992:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13993:     my (%chksum,%revnum);
                   13994:     if (ref($lines) eq 'ARRAY') {
                   13995:         chomp(@{$lines});
1.1172.2.34  raeburn  13996:         my $version = shift(@{$lines});
                   13997:         if ($version eq $release) {
1.1172.2.17  raeburn  13998:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13999:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14000:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14001:                     if ($webconfdir eq '/etc/apache2') {
                   14002:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14003:                     }
                   14004:                 }
1.1172.2.34  raeburn  14005:                 $chksum{$file} = $shasum;
                   14006:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14007:             }
                   14008:             if (ref($hashref) eq 'HASH') {
                   14009:                 %{$hashref} = (
                   14010:                                 sums     => \%chksum,
                   14011:                                 versions => \%revnum,
                   14012:                               );
                   14013:             }
                   14014:         }
                   14015:     }
1.869     albertel 14016:     return;
1.852     albertel 14017: }
1.1172.2.17  raeburn  14018: 
                   14019: sub fetch_dns_checksums {
                   14020:     my %checksums;
1.1172.2.34  raeburn  14021:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14022:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14023:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14024:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14025:              \%checksums);
                   14026:     return \%checksums;
                   14027: }
                   14028: 
1.1172.2.142  raeburn  14029: sub parse_getdns_url {
                   14030:     my ($command,$url) = @_;
                   14031:     my $dir = $perlvar{'lonTabDir'};
                   14032:     my $file;
                   14033:     if ($command eq 'hosts') {
                   14034:         $file = 'dns_hosts.tab';
                   14035:     } elsif ($command eq 'domain') {
                   14036:         $file = 'dns_domain.tab';
                   14037:     } elsif ($command eq 'checksums') {
                   14038:         my $version = (split('/',$url))[4];
                   14039:         $file = "dns_checksums/$version.tab",
                   14040:     }
                   14041:     return ($dir,$file);
                   14042: }
                   14043: 
1.327     albertel 14044: # ------------------------------------------------------------ Read domain file
                   14045: {
1.852     albertel 14046:     my $loaded;
1.846     albertel 14047:     my %domain;
                   14048: 
1.852     albertel 14049:     sub parse_domain_tab {
                   14050: 	my ($lines) = @_;
                   14051: 	foreach my $line (@$lines) {
                   14052: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14053: 
1.846     albertel 14054: 	    chomp($line);
1.852     albertel 14055: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14056: 	    my %this_domain;
                   14057: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14058: 			       'lang_def', 'city', 'longi', 'lati',
                   14059: 			       'primary') {
                   14060: 		$this_domain{$field} = shift(@elements);
                   14061: 	    }
                   14062: 	    $domain{$name} = \%this_domain;
1.852     albertel 14063: 	}
                   14064:     }
1.864     albertel 14065: 
                   14066:     sub reset_domain_info {
                   14067: 	undef($loaded);
                   14068: 	undef(%domain);
                   14069:     }
                   14070: 
1.852     albertel 14071:     sub load_domain_tab {
1.1172.2.70  raeburn  14072: 	my ($ignore_cache,$nocache) = @_;
                   14073: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14074: 	my $fh;
1.1172.2.96  raeburn  14075: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14076: 	    my @lines = <$fh>;
                   14077: 	    &parse_domain_tab(\@lines);
1.448     albertel 14078: 	}
1.852     albertel 14079: 	close($fh);
                   14080: 	$loaded = 1;
1.327     albertel 14081:     }
1.846     albertel 14082: 
                   14083:     sub domain {
1.852     albertel 14084: 	&load_domain_tab() if (!$loaded);
                   14085: 
1.846     albertel 14086: 	my ($name,$what) = @_;
                   14087: 	return if ( !exists($domain{$name}) );
                   14088: 
                   14089: 	if (!$what) {
                   14090: 	    return $domain{$name}{'description'};
                   14091: 	}
                   14092: 	return $domain{$name}{$what};
                   14093:     }
1.974     raeburn  14094: 
                   14095:     sub domain_info {
                   14096:         &load_domain_tab() if (!$loaded);
                   14097:         return %domain;
                   14098:     }
                   14099: 
1.327     albertel 14100: }
                   14101: 
                   14102: 
1.1       albertel 14103: # ------------------------------------------------------------- Read hosts file
                   14104: {
1.838     albertel 14105:     my %hostname;
1.844     albertel 14106:     my %hostdom;
1.845     albertel 14107:     my %libserv;
1.852     albertel 14108:     my $loaded;
1.888     albertel 14109:     my %name_to_host;
1.1074    raeburn  14110:     my %internetdom;
1.1107    raeburn  14111:     my %LC_dns_serv;
1.852     albertel 14112: 
                   14113:     sub parse_hosts_tab {
                   14114: 	my ($file) = @_;
                   14115: 	foreach my $configline (@$file) {
                   14116: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14117:             chomp($configline);
                   14118: 	    if ($configline =~ /^\^/) {
                   14119:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14120:                     $LC_dns_serv{$1} = 1;
                   14121:                 }
                   14122:                 next;
                   14123:             }
1.1074    raeburn  14124: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14125: 	    $name=~s/\s//g;
                   14126: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14127:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14128:                     my $curr = $hostname{$id};
                   14129:                     my $skip;
                   14130:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14131:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14132:                             $skip = 1;
                   14133:                         } else {
                   14134:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14135:                         }
                   14136:                     }
                   14137:                     unless ($skip) {
                   14138:                         push(@{$name_to_host{$name}},$id);
                   14139:                     }
                   14140:                 } else {
                   14141:                     push(@{$name_to_host{$name}},$id);
                   14142:                 }
1.852     albertel 14143: 		$hostname{$id}=$name;
                   14144: 		$hostdom{$id}=$domain;
                   14145: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14146:                 if (defined($protocol)) {
                   14147:                     if ($protocol eq 'https') {
                   14148:                         $protocol{$id} = $protocol;
                   14149:                     } else {
                   14150:                         $protocol{$id} = 'http'; 
                   14151:                     }
1.968     raeburn  14152:                 } else {
1.969     raeburn  14153:                     $protocol{$id} = 'http';
1.968     raeburn  14154:                 }
1.1074    raeburn  14155:                 if (defined($intdom)) {
                   14156:                     $internetdom{$id} = $intdom;
                   14157:                 }
1.852     albertel 14158: 	    }
                   14159: 	}
                   14160:     }
1.864     albertel 14161:     
                   14162:     sub reset_hosts_info {
1.897     albertel 14163: 	&purge_remembered();
1.864     albertel 14164: 	&reset_domain_info();
                   14165: 	&reset_hosts_ip_info();
1.892     albertel 14166: 	undef(%name_to_host);
1.864     albertel 14167: 	undef(%hostname);
                   14168: 	undef(%hostdom);
                   14169: 	undef(%libserv);
                   14170: 	undef($loaded);
                   14171:     }
1.1       albertel 14172: 
1.852     albertel 14173:     sub load_hosts_tab {
1.1172.2.70  raeburn  14174: 	my ($ignore_cache,$nocache) = @_;
                   14175: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14176: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14177: 	my @config = <$config>;
                   14178: 	&parse_hosts_tab(\@config);
                   14179: 	close($config);
                   14180: 	$loaded=1;
1.1       albertel 14181:     }
1.852     albertel 14182: 
1.838     albertel 14183:     sub hostname {
1.852     albertel 14184: 	&load_hosts_tab() if (!$loaded);
                   14185: 
1.838     albertel 14186: 	my ($lonid) = @_;
                   14187: 	return $hostname{$lonid};
                   14188:     }
1.845     albertel 14189: 
1.838     albertel 14190:     sub all_hostnames {
1.852     albertel 14191: 	&load_hosts_tab() if (!$loaded);
                   14192: 
1.838     albertel 14193: 	return %hostname;
                   14194:     }
1.845     albertel 14195: 
1.888     albertel 14196:     sub all_names {
1.1172.2.70  raeburn  14197:         my ($ignore_cache,$nocache) = @_;
                   14198: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14199: 
                   14200: 	return %name_to_host;
                   14201:     }
                   14202: 
1.974     raeburn  14203:     sub all_host_domain {
                   14204:         &load_hosts_tab() if (!$loaded);
                   14205:         return %hostdom;
                   14206:     }
                   14207: 
1.845     albertel 14208:     sub is_library {
1.852     albertel 14209: 	&load_hosts_tab() if (!$loaded);
                   14210: 
1.845     albertel 14211: 	return exists($libserv{$_[0]});
                   14212:     }
                   14213: 
                   14214:     sub all_library {
1.852     albertel 14215: 	&load_hosts_tab() if (!$loaded);
                   14216: 
1.845     albertel 14217: 	return %libserv;
                   14218:     }
                   14219: 
1.1062    droeschl 14220:     sub unique_library {
                   14221: 	#2x reverse removes all hostnames that appear more than once
                   14222:         my %unique = reverse &all_library();
                   14223:         return reverse %unique;
                   14224:     }
                   14225: 
1.841     albertel 14226:     sub get_servers {
1.852     albertel 14227: 	&load_hosts_tab() if (!$loaded);
                   14228: 
1.841     albertel 14229: 	my ($domain,$type) = @_;
                   14230: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14231: 	                                          : %hostname;
                   14232: 	my %result;
1.842     albertel 14233: 	if (ref($domain) eq 'ARRAY') {
                   14234: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14235: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14236: 		    $result{$host} = $hostname;
                   14237: 		}
                   14238: 	    }
                   14239: 	} else {
                   14240: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14241: 		if ($hostdom{$host} eq $domain) {
                   14242: 		    $result{$host} = $hostname;
                   14243: 		}
1.841     albertel 14244: 	    }
                   14245: 	}
                   14246: 	return %result;
                   14247:     }
1.845     albertel 14248: 
1.1062    droeschl 14249:     sub get_unique_servers {
                   14250:         my %unique = reverse &get_servers(@_);
                   14251: 	return reverse %unique;
                   14252:     }
                   14253: 
1.844     albertel 14254:     sub host_domain {
1.852     albertel 14255: 	&load_hosts_tab() if (!$loaded);
                   14256: 
1.844     albertel 14257: 	my ($lonid) = @_;
                   14258: 	return $hostdom{$lonid};
                   14259:     }
                   14260: 
1.841     albertel 14261:     sub all_domains {
1.852     albertel 14262: 	&load_hosts_tab() if (!$loaded);
                   14263: 
1.841     albertel 14264: 	my %seen;
                   14265: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14266: 	return @uniq;
                   14267:     }
1.1074    raeburn  14268: 
                   14269:     sub internet_dom {
                   14270:         &load_hosts_tab() if (!$loaded);
                   14271: 
                   14272:         my ($lonid) = @_;
                   14273:         return $internetdom{$lonid};
                   14274:     }
1.1107    raeburn  14275: 
                   14276:     sub is_LC_dns {
                   14277:         &load_hosts_tab() if (!$loaded);
                   14278: 
                   14279:         my ($hostname) = @_;
                   14280:         return exists($LC_dns_serv{$hostname});
                   14281:     }
                   14282: 
1.1       albertel 14283: }
                   14284: 
1.847     albertel 14285: { 
                   14286:     my %iphost;
1.856     albertel 14287:     my %name_to_ip;
                   14288:     my %lonid_to_ip;
1.869     albertel 14289: 
1.847     albertel 14290:     sub get_hosts_from_ip {
                   14291: 	my ($ip) = @_;
                   14292: 	my %iphosts = &get_iphost();
                   14293: 	if (ref($iphosts{$ip})) {
                   14294: 	    return @{$iphosts{$ip}};
                   14295: 	}
                   14296: 	return;
1.839     albertel 14297:     }
1.864     albertel 14298:     
                   14299:     sub reset_hosts_ip_info {
                   14300: 	undef(%iphost);
                   14301: 	undef(%name_to_ip);
                   14302: 	undef(%lonid_to_ip);
                   14303:     }
1.856     albertel 14304: 
                   14305:     sub get_host_ip {
                   14306: 	my ($lonid) = @_;
                   14307: 	if (exists($lonid_to_ip{$lonid})) {
                   14308: 	    return $lonid_to_ip{$lonid};
                   14309: 	}
                   14310: 	my $name=&hostname($lonid);
                   14311:    	my $ip = gethostbyname($name);
                   14312: 	return if (!$ip || length($ip) ne 4);
                   14313: 	$ip=inet_ntoa($ip);
                   14314: 	$name_to_ip{$name}   = $ip;
                   14315: 	$lonid_to_ip{$lonid} = $ip;
                   14316: 	return $ip;
                   14317:     }
1.847     albertel 14318:     
                   14319:     sub get_iphost {
1.1172.2.70  raeburn  14320: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14321: 
1.869     albertel 14322: 	if (!$ignore_cache) {
                   14323: 	    if (%iphost) {
                   14324: 		return %iphost;
                   14325: 	    }
                   14326: 	    my ($ip_info,$cached)=
                   14327: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14328: 	    if ($cached) {
                   14329: 		%iphost      = %{$ip_info->[0]};
                   14330: 		%name_to_ip  = %{$ip_info->[1]};
                   14331: 		%lonid_to_ip = %{$ip_info->[2]};
                   14332: 		return %iphost;
                   14333: 	    }
                   14334: 	}
1.894     albertel 14335: 
                   14336: 	# get yesterday's info for fallback
                   14337: 	my %old_name_to_ip;
                   14338: 	my ($ip_info,$cached)=
                   14339: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14340: 	if ($cached) {
                   14341: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14342: 	}
                   14343: 
1.1172.2.70  raeburn  14344: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14345: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14346: 	    my $ip;
                   14347: 	    if (!exists($name_to_ip{$name})) {
                   14348: 		$ip = gethostbyname($name);
                   14349: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14350: 		    if (defined($old_name_to_ip{$name})) {
                   14351: 			$ip = $old_name_to_ip{$name};
                   14352: 			&logthis("Can't find $name defaulting to old $ip");
                   14353: 		    } else {
                   14354: 			&logthis("Name $name no IP found");
                   14355: 			next;
                   14356: 		    }
                   14357: 		} else {
                   14358: 		    $ip=inet_ntoa($ip);
1.847     albertel 14359: 		}
                   14360: 		$name_to_ip{$name} = $ip;
                   14361: 	    } else {
                   14362: 		$ip = $name_to_ip{$name};
1.653     albertel 14363: 	    }
1.888     albertel 14364: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14365: 		$lonid_to_ip{$id} = $ip;
                   14366: 	    }
                   14367: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14368: 	}
1.1172.2.70  raeburn  14369:         unless ($nocache) {
                   14370: 	    &do_cache_new('iphost','iphost',
                   14371: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14372: 		          48*60*60);
                   14373:         }
1.869     albertel 14374: 
1.847     albertel 14375: 	return %iphost;
1.598     albertel 14376:     }
                   14377: 
1.992     raeburn  14378:     #
                   14379:     #  Given a DNS returns the loncapa host name for that DNS 
                   14380:     # 
                   14381:     sub host_from_dns {
                   14382:         my ($dns) = @_;
                   14383:         my @hosts;
                   14384:         my $ip;
                   14385: 
1.993     raeburn  14386:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14387:             $ip = $name_to_ip{$dns};
                   14388:         }
                   14389:         if (!$ip) {
                   14390:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14391:             if (length($ip) == 4) { 
                   14392: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14393:             }
                   14394:         }
                   14395:         if ($ip) {
                   14396: 	    @hosts = get_hosts_from_ip($ip);
                   14397: 	    return $hosts[0];
                   14398:         }
                   14399:         return undef;
1.986     foxr     14400:     }
1.992     raeburn  14401: 
1.1074    raeburn  14402:     sub get_internet_names {
                   14403:         my ($lonid) = @_;
                   14404:         return if ($lonid eq '');
                   14405:         my ($idnref,$cached)=
                   14406:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14407:         if ($cached) {
                   14408:             return $idnref;
                   14409:         }
                   14410:         my $ip = &get_host_ip($lonid);
                   14411:         my @hosts = &get_hosts_from_ip($ip);
                   14412:         my %iphost = &get_iphost();
                   14413:         my (@idns,%seen);
                   14414:         foreach my $id (@hosts) {
                   14415:             my $dom = &host_domain($id);
                   14416:             my $prim_id = &domain($dom,'primary');
                   14417:             my $prim_ip = &get_host_ip($prim_id);
                   14418:             next if ($seen{$prim_ip});
                   14419:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14420:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14421:                     my $intdom = &internet_dom($id);
                   14422:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14423:                         push(@idns,$intdom);
                   14424:                     }
                   14425:                 }
                   14426:             }
                   14427:             $seen{$prim_ip} = 1;
                   14428:         }
1.1172.2.23  raeburn  14429:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14430:     }
                   14431: 
1.986     foxr     14432: }
                   14433: 
1.1079    raeburn  14434: sub all_loncaparevs {
1.1172.2.39  raeburn  14435:     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 2.11);
1.1079    raeburn  14436: }
                   14437: 
1.1172.2.27  raeburn  14438: # ------------------------------------------------------- Read loncaparev table
                   14439: {
                   14440:     sub load_loncaparevs {
                   14441:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14442:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14443:                 while (my $configline=<$config>) {
                   14444:                     chomp($configline);
                   14445:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14446:                     $loncaparevs{$hostid}=$loncaparev;
                   14447:                 }
                   14448:                 close($config);
                   14449:             }
                   14450:         }
                   14451:     }
                   14452: }
                   14453: 
                   14454: # ----------------------------------------------------- Read serverhostID table
                   14455: {
                   14456:     sub load_serverhomeIDs {
                   14457:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14458:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14459:                 while (my $configline=<$config>) {
                   14460:                     chomp($configline);
                   14461:                     my ($name,$id)=split(/:/,$configline);
                   14462:                     $serverhomeIDs{$name}=$id;
                   14463:                 }
                   14464:                 close($config);
                   14465:             }
                   14466:         }
                   14467:     }
                   14468: }
                   14469: 
                   14470: 
1.862     albertel 14471: BEGIN {
                   14472: 
                   14473: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14474:     unless ($readit) {
                   14475: {
                   14476:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14477:     %perlvar = (%perlvar,%{$configvars});
                   14478: }
                   14479: 
                   14480: 
1.1       albertel 14481: # ------------------------------------------------------ Read spare server file
                   14482: {
1.1172.2.96  raeburn  14483:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14484: 
                   14485:     while (my $configline=<$config>) {
                   14486:        chomp($configline);
1.284     matthew  14487:        if ($configline) {
1.784     albertel 14488: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14489: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14490: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14491:        }
                   14492:     }
1.448     albertel 14493:     close($config);
1.1       albertel 14494: }
1.11      www      14495: # ------------------------------------------------------------ Read permissions
                   14496: {
1.1172.2.96  raeburn  14497:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14498: 
                   14499:     while (my $configline=<$config>) {
1.448     albertel 14500: 	chomp($configline);
                   14501: 	if ($configline) {
                   14502: 	    my ($role,$perm)=split(/ /,$configline);
                   14503: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14504: 	}
1.11      www      14505:     }
1.448     albertel 14506:     close($config);
1.11      www      14507: }
                   14508: 
                   14509: # -------------------------------------------- Read plain texts for permissions
                   14510: {
1.1172.2.96  raeburn  14511:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14512: 
                   14513:     while (my $configline=<$config>) {
1.448     albertel 14514: 	chomp($configline);
                   14515: 	if ($configline) {
1.742     raeburn  14516: 	    my ($short,@plain)=split(/:/,$configline);
                   14517:             %{$prp{$short}} = ();
                   14518: 	    if (@plain > 0) {
                   14519:                 $prp{$short}{'std'} = $plain[0];
                   14520:                 for (my $i=1; $i<@plain; $i++) {
                   14521:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14522:                 }
                   14523:             }
1.448     albertel 14524: 	}
1.135     www      14525:     }
1.448     albertel 14526:     close($config);
1.135     www      14527: }
                   14528: 
                   14529: # ---------------------------------------------------------- Read package table
                   14530: {
1.1172.2.96  raeburn  14531:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14532: 
                   14533:     while (my $configline=<$config>) {
1.483     albertel 14534: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14535: 	chomp($configline);
                   14536: 	my ($short,$plain)=split(/:/,$configline);
                   14537: 	my ($pack,$name)=split(/\&/,$short);
                   14538: 	if ($plain ne '') {
                   14539: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14540: 	    $packagetab{$short}=$plain; 
                   14541: 	}
1.11      www      14542:     }
1.448     albertel 14543:     close($config);
1.329     matthew  14544: }
                   14545: 
1.1172.2.27  raeburn  14546: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14547: 
1.1172.2.27  raeburn  14548: &load_loncaparevs();
                   14549: 
                   14550: # ------------------------------------------------------- Read serverhostID table
                   14551: 
                   14552: &load_serverhomeIDs();
1.1074    raeburn  14553: 
1.1172.2.27  raeburn  14554: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14555: {
                   14556:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14557:     if (-e $file) {
                   14558:         my $parser = HTML::LCParser->new($file);
                   14559:         while (my $token = $parser->get_token()) {
                   14560:             if ($token->[0] eq 'S') {
                   14561:                 my $item = $token->[1];
                   14562:                 my $name = $token->[2]{'name'};
                   14563:                 my $value = $token->[2]{'value'};
                   14564:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14565:                     my $release = $parser->get_text();
                   14566:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14567:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14568:                 }
                   14569:             }
                   14570:         }
                   14571:     }
1.1073    raeburn  14572: }
                   14573: 
1.1138    raeburn  14574: # ---------------------------------------------------------- Read managers table
                   14575: {
                   14576:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14577:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14578:             while (my $configline=<$config>) {
                   14579:                 chomp($configline);
                   14580:                 next if ($configline =~ /^\#/);
                   14581:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14582:                     $managerstab{$configline} = 1;
                   14583:                 }
                   14584:             }
                   14585:             close($config);
                   14586:         }
                   14587:     }
                   14588: }
                   14589: 
1.329     matthew  14590: # ------------- set up temporary directory
                   14591: {
1.1117    foxr     14592:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14593: 
1.11      www      14594: }
                   14595: 
1.1172.2.104  raeburn  14596: # ------------- set default texengine (domain default overrides this)
                   14597: {
                   14598:     $deftex = LONCAPA::texengine();
                   14599: }
                   14600: 
1.1172.2.114  raeburn  14601: # ------------- set default minimum length for passwords for internal auth users
                   14602: {
                   14603:     $passwdmin = LONCAPA::passwd_min();
                   14604: }
                   14605: 
1.794     albertel 14606: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14607: 				'compress_threshold'=> 20_000,
                   14608:  			        });
1.185     www      14609: 
1.281     www      14610: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14611: $dumpcount=0;
1.958     www      14612: $locknum=0;
1.22      www      14613: 
1.163     harris41 14614: &logtouch();
1.672     albertel 14615: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14616: $readit=1;
1.564     albertel 14617:     {
                   14618: 	use integer;
                   14619: 	my $test=(2**32)+1;
1.568     albertel 14620: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14621: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14622:     }
1.195     www      14623: }
1.1       albertel 14624: }
1.179     www      14625: 
1.1       albertel 14626: 1;
1.191     harris41 14627: __END__
                   14628: 
1.243     albertel 14629: =pod
                   14630: 
1.191     harris41 14631: =head1 NAME
                   14632: 
1.243     albertel 14633: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14634: 
                   14635: =head1 SYNOPSIS
                   14636: 
1.243     albertel 14637: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14638: 
                   14639:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14640: 
1.243     albertel 14641: Common parameters:
                   14642: 
                   14643: =over 4
                   14644: 
                   14645: =item *
                   14646: 
                   14647: $uname : an internal username (if $cname expecting a course Id specifically)
                   14648: 
                   14649: =item *
                   14650: 
                   14651: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14652: 
                   14653: =item *
                   14654: 
                   14655: $symb : a resource instance identifier
                   14656: 
                   14657: =item *
                   14658: 
                   14659: $namespace : the name of a .db file that contains the data needed or
                   14660: being set.
                   14661: 
                   14662: =back
                   14663: 
1.394     bowersj2 14664: =head1 OVERVIEW
1.191     harris41 14665: 
1.394     bowersj2 14666: lonnet provides subroutines which interact with the
                   14667: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14668: about classes, users, and resources.
1.243     albertel 14669: 
                   14670: For many of these objects you can also use this to store data about
                   14671: them or modify them in various ways.
1.191     harris41 14672: 
1.394     bowersj2 14673: =head2 Symbs
1.191     harris41 14674: 
1.394     bowersj2 14675: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14676: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14677: map, the resource number of the resource in the map, and the URL of
                   14678: the resource itself. The latter is somewhat redundant, but might help
                   14679: if maps change.
                   14680: 
                   14681: An example is
                   14682: 
                   14683:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14684: 
                   14685: The respective map entry is
                   14686: 
                   14687:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14688:   title="Problem 2">
                   14689:  </resource>
                   14690: 
                   14691: Symbs are used by the random number generator, as well as to store and
                   14692: restore data specific to a certain instance of for example a problem.
                   14693: 
                   14694: =head2 Storing And Retrieving Data
                   14695: 
                   14696: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14697: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14698: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14699: is is the non-critical message twin of cstore. These functions are for
                   14700: handlers to store a perl hash to a user's permanent data space in an
                   14701: easy manner, and to retrieve it again on another call. It is expected
                   14702: that a handler would use this once at the beginning to retrieve data,
                   14703: and then again once at the end to send only the new data back.
                   14704: 
                   14705: The data is stored in the user's data directory on the user's
                   14706: homeserver under the ID of the course.
                   14707: 
                   14708: The hash that is returned by restore will have all of the previous
                   14709: value for all of the elements of the hash.
                   14710: 
                   14711: Example:
                   14712: 
                   14713:  #creating a hash
                   14714:  my %hash;
                   14715:  $hash{'foo'}='bar';
                   14716: 
                   14717:  #storing it
                   14718:  &Apache::lonnet::cstore(\%hash);
                   14719: 
                   14720:  #changing a value
                   14721:  $hash{'foo'}='notbar';
                   14722: 
                   14723:  #adding a new value
                   14724:  $hash{'bar'}='foo';
                   14725:  &Apache::lonnet::cstore(\%hash);
                   14726: 
                   14727:  #retrieving the hash
                   14728:  my %history=&Apache::lonnet::restore();
                   14729: 
                   14730:  #print the hash
                   14731:  foreach my $key (sort(keys(%history))) {
                   14732:    print("\%history{$key} = $history{$key}");
                   14733:  }
                   14734: 
                   14735: Will print out:
1.191     harris41 14736: 
1.394     bowersj2 14737:  %history{1:foo} = bar
                   14738:  %history{1:keys} = foo:timestamp
                   14739:  %history{1:timestamp} = 990455579
                   14740:  %history{2:bar} = foo
                   14741:  %history{2:foo} = notbar
                   14742:  %history{2:keys} = foo:bar:timestamp
                   14743:  %history{2:timestamp} = 990455580
                   14744:  %history{bar} = foo
                   14745:  %history{foo} = notbar
                   14746:  %history{timestamp} = 990455580
                   14747:  %history{version} = 2
                   14748: 
                   14749: Note that the special hash entries C<keys>, C<version> and
                   14750: C<timestamp> were added to the hash. C<version> will be equal to the
                   14751: total number of versions of the data that have been stored. The
                   14752: C<timestamp> attribute will be the UNIX time the hash was
                   14753: stored. C<keys> is available in every historical section to list which
                   14754: keys were added or changed at a specific historical revision of a
                   14755: hash.
                   14756: 
                   14757: B<Warning>: do not store the hash that restore returns directly. This
                   14758: will cause a mess since it will restore the historical keys as if the
                   14759: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14760: 
1.394     bowersj2 14761: Calling convention:
1.191     harris41 14762: 
1.1172.2.27  raeburn  14763:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14764:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14765: 
1.394     bowersj2 14766: For more detailed information, see lonnet specific documentation.
1.191     harris41 14767: 
1.394     bowersj2 14768: =head1 RETURN MESSAGES
1.191     harris41 14769: 
1.394     bowersj2 14770: =over 4
1.191     harris41 14771: 
1.394     bowersj2 14772: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14773: 
1.394     bowersj2 14774: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14775: when the connection is brought back up
1.191     harris41 14776: 
1.394     bowersj2 14777: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14778: for later delivery
1.191     harris41 14779: 
1.967     bisitz   14780: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14781: 
1.394     bowersj2 14782: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14783: that was requested
1.191     harris41 14784: 
1.243     albertel 14785: =back
1.191     harris41 14786: 
1.243     albertel 14787: =head1 PUBLIC SUBROUTINES
1.191     harris41 14788: 
1.243     albertel 14789: =head2 Session Environment Functions
1.191     harris41 14790: 
1.243     albertel 14791: =over 4
1.191     harris41 14792: 
1.394     bowersj2 14793: =item * 
                   14794: X<appenv()>
1.949     raeburn  14795: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14796: the user envirnoment file, and will be restored for each access this
1.620     albertel 14797: user makes during this session, also modifies the %env for the current
1.949     raeburn  14798: process. Optional rolesarrayref - if defined contains a reference to an array
                   14799: of roles which are exempt from the restriction on modifying user.role entries 
                   14800: in the user's environment.db and in %env.    
1.191     harris41 14801: 
                   14802: =item *
1.394     bowersj2 14803: X<delenv()>
1.987     raeburn  14804: B<delenv($delthis,$regexp)>: removes all items from the session
                   14805: environment file that begin with $delthis. If the 
                   14806: optional second arg - $regexp - is true, $delthis is treated as a 
                   14807: regular expression, otherwise \Q$delthis\E is used. 
                   14808: The values are also deleted from the current processes %env.
1.191     harris41 14809: 
1.795     albertel 14810: =item * get_env_multiple($name) 
                   14811: 
                   14812: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14813: values may be defined and end up as an array ref.
                   14814: 
                   14815: returns an array of values
                   14816: 
1.243     albertel 14817: =back
                   14818: 
                   14819: =head2 User Information
1.191     harris41 14820: 
1.243     albertel 14821: =over 4
1.191     harris41 14822: 
                   14823: =item *
1.394     bowersj2 14824: X<queryauthenticate()>
                   14825: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14826: authentication scheme
                   14827: 
                   14828: =item *
1.394     bowersj2 14829: X<authenticate()>
1.1073    raeburn  14830: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14831: authenticate user from domain's lib servers (first use the current
                   14832: one). C<$upass> should be the users password.
1.1073    raeburn  14833: $checkdefauth is optional (value is 1 if a check should be made to
                   14834:    authenticate user using default authentication method, and allow
                   14835:    account creation if username does not have account in the domain).
                   14836: $clientcancheckhost is optional (value is 1 if checking whether the
                   14837:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14838: 
                   14839: =item *
1.394     bowersj2 14840: X<homeserver()>
                   14841: B<homeserver($uname,$udom)>: find the server which has
                   14842: the user's directory and files (there must be only one), this caches
                   14843: the answer, and also caches if there is a borken connection.
1.191     harris41 14844: 
                   14845: =item *
1.394     bowersj2 14846: X<idget()>
                   14847: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14848: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14849: username, and only 1 username per ID in a specific domain) (returns
                   14850: hash: id=>name,id=>name)
1.191     harris41 14851: 
                   14852: =item *
1.394     bowersj2 14853: X<idrget()>
                   14854: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14855: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14856: 
                   14857: =item *
1.394     bowersj2 14858: X<idput()>
                   14859: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14860: 
                   14861: =item *
1.394     bowersj2 14862: X<rolesinit()>
1.1169    droeschl 14863: B<rolesinit($udom,$username)>: get user privileges.
                   14864: returns user role, first access and timer interval hashes
1.243     albertel 14865: 
                   14866: =item *
1.1171    droeschl 14867: X<privileged()>
                   14868: B<privileged($username,$domain)>: returns a true if user has a
                   14869: privileged and active role (i.e. su or dc), false otherwise.
                   14870: 
                   14871: =item *
1.551     albertel 14872: X<getsection()>
                   14873: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14874: course $cname, return section name/number or '' for "not in course"
                   14875: and '-1' for "no section"
                   14876: 
                   14877: =item *
1.394     bowersj2 14878: X<userenvironment()>
                   14879: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14880: passed in @what from the requested user's environment, returns a hash
                   14881: 
1.858     raeburn  14882: =item * 
                   14883: X<userlog_query()>
1.859     albertel 14884: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14885: activity.log file. %filters defines filters applied when parsing the
                   14886: log file. These can be start or end timestamps, or the type of action
                   14887: - log to look for Login or Logout events, check for Checkin or
                   14888: Checkout, role for role selection. The response is in the form
                   14889: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14890: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14891: 
1.243     albertel 14892: =back
                   14893: 
                   14894: =head2 User Roles
                   14895: 
                   14896: =over 4
                   14897: 
                   14898: =item *
                   14899: 
1.1172.2.65  raeburn  14900: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14901: returns codes for allowed actions.
                   14902: 
                   14903: The first argument is required, all others are optional.
                   14904: 
                   14905: $priv is the privilege being checked.
                   14906: $uri contains additional information about what is being checked for access (e.g.,
                   14907: URL, course ID etc.).
                   14908: $symb is the unique resource instance identifier in a course; if needed,
                   14909: but not provided, it will be retrieved via a call to &symbread().
                   14910: $role is the role for which a priv is being checked (only used if priv is evb).
                   14911: $clientip is the user's IP address (only used when checking for access to portfolio
                   14912: files).
                   14913: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14914: prevents recursive calls to &allowed.
                   14915: 
1.243     albertel 14916:  F: full access
                   14917:  U,I,K: authentication modes (cxx only)
                   14918:  '': forbidden
                   14919:  1: user needs to choose course
                   14920:  2: browse allowed
1.766     albertel 14921:  A: passphrase authentication needed
1.1172.2.65  raeburn  14922:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14923: 
                   14924: =item *
                   14925: 
1.1172.2.13  raeburn  14926: constructaccess($url,$setpriv) : check for access to construction space URL
                   14927: 
                   14928: See if the owner domain and name in the URL match those in the
                   14929: expected environment.  If so, return three element list
                   14930: ($ownername,$ownerdomain,$ownerhome).
                   14931: 
                   14932: Otherwise return the null string.
                   14933: 
                   14934: If second argument 'setpriv' is true, it assigns the privileges,
                   14935: and returns the same three element list, unless the owner has
                   14936: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14937: in which case the null string is returned.
                   14938: 
                   14939: =item *
                   14940: 
1.1172.2.84  raeburn  14941: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14942: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14943: for system, domain, and course level. $uname and $udom are optional (current
                   14944: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14945: 
                   14946: =item *
                   14947: 
1.988     raeburn  14948: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14949: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14950: $type is Course (default) or Community.
1.988     raeburn  14951: If $forcedefault evaluates to true, text returned will be default 
                   14952: text for $type. Otherwise, if this is a course, the text returned 
                   14953: will be a custom name for the role (if defined in the course's 
                   14954: environment).  If no custom name is defined the default is returned.
                   14955:    
1.832     raeburn  14956: =item *
                   14957: 
1.1172.2.23  raeburn  14958: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14959: All arguments are optional. Returns a hash of a roles, either for
                   14960: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14961: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14962: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14963: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14964: For each key, value is set to colon-separated start and end times for
                   14965: the role.  If no username and domain are specified, will default to
1.934     raeburn  14966: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14967: of role statuses (active, future or previous), roles 
                   14968: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14969: to restrict the list of roles reported. If no array ref is 
                   14970: provided for types, will default to return only active roles.
1.834     albertel 14971: 
1.1172.2.13  raeburn  14972: =item *
                   14973: 
                   14974: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14975: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14976: 
                   14977: Additional optional arguments are: $type (if role checking is to be restricted
                   14978: to certain user status types -- previous (expired roles), active (currently
                   14979: available roles) or future (roles available in the future), and
                   14980: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14981: have active Domain Coordinator role in course's domain or in additional
                   14982: domains (specified in 'Domains to check for privileged users' in course
                   14983: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14984: 
                   14985: =item *
                   14986: 
                   14987: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14988: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14989: $possdomains and $possroles are optional array refs -- to domains to check and
                   14990: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14991: users' roles.db to check for a dc or su role in any domain. This can be
                   14992: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14993: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14994: this then allows &privileged_by_domain() to be used, which caches the identity
                   14995: of privileged users, eliminating the need for repeated calls to &dump().
                   14996: 
                   14997: =item *
                   14998: 
                   14999: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15000: where the outer hash keys are domains specified in the $possdomains array ref,
                   15001: next inner hash keys are privileged roles specified in the $roles array ref,
                   15002: and the innermost hash contains key = value pairs for username:domain = end:start
                   15003: for active or future "privileged" users with that role in that domain. To avoid
                   15004: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15005: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15006: 
1.243     albertel 15007: =back
                   15008: 
                   15009: =head2 User Modification
                   15010: 
                   15011: =over 4
                   15012: 
                   15013: =item *
                   15014: 
1.957     raeburn  15015: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15016: user for the level given by URL.  Optional start and end dates (leave empty
                   15017: string or zero for "no date")
1.191     harris41 15018: 
                   15019: =item *
                   15020: 
1.243     albertel 15021: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15022: change a users, password, possible return values are: ok,
                   15023: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15024: refused
1.191     harris41 15025: 
                   15026: =item *
                   15027: 
1.243     albertel 15028: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15029: 
                   15030: =item *
                   15031: 
1.1058    raeburn  15032: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15033:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15034: 
                   15035: will update user information (firstname,middlename,lastname,generation,
                   15036: permanentemail), and if forceid is true, student/employee ID also.
                   15037: A user's institutional affiliation(s) can also be updated.
                   15038: User information fields will not be overwritten with empty entries 
                   15039: unless the field is included in the $candelete array reference.
                   15040: This array is included when a single user is modified via "Manage Users",
                   15041: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15042: 
                   15043: =item *
                   15044: 
1.286     matthew  15045: modifystudent
                   15046: 
1.957     raeburn  15047: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15048: The course id is resolved based on the current user's environment.  
                   15049: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15050: associated with a course.
                   15051: 
1.297     matthew  15052: This call is essentially a wrapper for lonnet::modifyuser and
                   15053: lonnet::modify_student_enrollment
1.286     matthew  15054: 
                   15055: Inputs: 
                   15056: 
                   15057: =over 4
                   15058: 
1.957     raeburn  15059: =item B<$udom> Student's loncapa domain
1.286     matthew  15060: 
1.957     raeburn  15061: =item B<$uname> Student's loncapa login name
1.286     matthew  15062: 
1.964     bisitz   15063: =item B<$uid> Student/Employee ID
1.286     matthew  15064: 
1.957     raeburn  15065: =item B<$umode> Student's authentication mode
1.286     matthew  15066: 
1.957     raeburn  15067: =item B<$upass> Student's password
1.286     matthew  15068: 
1.957     raeburn  15069: =item B<$first> Student's first name
1.286     matthew  15070: 
1.957     raeburn  15071: =item B<$middle> Student's middle name
1.286     matthew  15072: 
1.957     raeburn  15073: =item B<$last> Student's last name
1.286     matthew  15074: 
1.957     raeburn  15075: =item B<$gene> Student's generation
1.286     matthew  15076: 
1.957     raeburn  15077: =item B<$usec> Student's section in course
1.286     matthew  15078: 
                   15079: =item B<$end> Unix time of the roles expiration
                   15080: 
                   15081: =item B<$start> Unix time of the roles start date
                   15082: 
                   15083: =item B<$forceid> If defined, allow $uid to be changed
                   15084: 
                   15085: =item B<$desiredhome> server to use as home server for student
                   15086: 
1.957     raeburn  15087: =item B<$email> Student's permanent e-mail address
                   15088: 
                   15089: =item B<$type> Type of enrollment (auto or manual)
                   15090: 
1.963     raeburn  15091: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15092: 
                   15093: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15094: 
1.963     raeburn  15095: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15096: 
1.963     raeburn  15097: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15098: 
1.1172.2.19  raeburn  15099: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15100: 
                   15101: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  15102: 
1.286     matthew  15103: =back
1.297     matthew  15104: 
                   15105: =item *
                   15106: 
                   15107: modify_student_enrollment
                   15108: 
1.1172.2.31  raeburn  15109: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15110: 'role.request.course' must be defined for this function to proceed.
                   15111: 
                   15112: Inputs:
                   15113: 
                   15114: =over 4
                   15115: 
1.1172.2.31  raeburn  15116: =item $udom, student's domain
1.297     matthew  15117: 
1.1172.2.31  raeburn  15118: =item $uname, student's name
1.297     matthew  15119: 
1.1172.2.31  raeburn  15120: =item $uid, student's user id
1.297     matthew  15121: 
1.1172.2.31  raeburn  15122: =item $first, student's first name
1.297     matthew  15123: 
                   15124: =item $middle
                   15125: 
                   15126: =item $last
                   15127: 
                   15128: =item $gene
                   15129: 
                   15130: =item $usec
                   15131: 
                   15132: =item $end
                   15133: 
                   15134: =item $start
                   15135: 
1.957     raeburn  15136: =item $type
                   15137: 
                   15138: =item $locktype
                   15139: 
                   15140: =item $cid
                   15141: 
                   15142: =item $selfenroll
                   15143: 
                   15144: =item $context
                   15145: 
1.1172.2.19  raeburn  15146: =item $credits, number of credits student will earn from this class
                   15147: 
1.1172.2.76  raeburn  15148: =item $instsec, institutional course section code for student
                   15149: 
1.297     matthew  15150: =back
                   15151: 
1.191     harris41 15152: 
                   15153: =item *
                   15154: 
1.243     albertel 15155: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15156: custom role; give a custom role to a user for the level given by URL.  Specify
                   15157: name and domain of role author, and role name
1.191     harris41 15158: 
                   15159: =item *
                   15160: 
1.243     albertel 15161: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15162: 
                   15163: =item *
                   15164: 
1.243     albertel 15165: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15166: 
                   15167: =back
                   15168: 
                   15169: =head2 Course Infomation
                   15170: 
                   15171: =over 4
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.1118    foxr     15175: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15176: specified course id, including all environment settings for the
                   15177: course, the description of the course will be in the hash under the
                   15178: key 'description'
1.191     harris41 15179: 
1.1118    foxr     15180: $options is an optional parameter that if supplied is a hash reference that controls
                   15181: what how this function works.  It has the following key/values:
                   15182: 
                   15183: =over 4
                   15184: 
                   15185: =item freshen_cache
                   15186: 
                   15187: If defined, and the environment cache for the course is valid, it is 
                   15188: returned in the returned hash.
                   15189: 
                   15190: =item one_time
                   15191: 
                   15192: If defined, the last cache time is set to _now_
                   15193: 
                   15194: =item user
                   15195: 
                   15196: If defined, the supplied username is used instead of the current user.
                   15197: 
                   15198: 
                   15199: =back
                   15200: 
1.191     harris41 15201: =item *
                   15202: 
1.624     albertel 15203: resdata($name,$domain,$type,@which) : request for current parameter
                   15204: setting for a specific $type, where $type is either 'course' or 'user',
                   15205: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15206: answers for 10 minutes.
1.243     albertel 15207: 
1.877     foxr     15208: =item *
                   15209: 
                   15210: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15211: data base, returning a hash that is keyed by the resource name and has
                   15212: values that are the resource value.  I believe that the timestamps and
                   15213: versions are also returned.
                   15214: 
1.1172.2.31  raeburn  15215: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15216: supplemental content area. This routine caches the number of files for
                   15217: 10 minutes.
                   15218: 
1.243     albertel 15219: =back
                   15220: 
                   15221: =head2 Course Modification
                   15222: 
                   15223: =over 4
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.243     albertel 15227: writecoursepref($courseid,%prefs) : write preferences (environment
                   15228: database) for a course
1.191     harris41 15229: 
                   15230: =item *
                   15231: 
1.1011    raeburn  15232: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15233: 
                   15234: =item *
                   15235: 
1.1038    raeburn  15236: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15237: 
1.1167    droeschl 15238: =item *
                   15239: 
                   15240: is_course($courseid), is_course($cdom, $cnum)
                   15241: 
                   15242: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15243: two component version $cdom, $cnum. It checks if the specified course exists.
                   15244: 
                   15245: Returns:
                   15246:     undef if the course doesn't exist, otherwise
                   15247:     in scalar context the combined courseid.
                   15248:     in list context the two components of the course identifier, domain and 
                   15249:     courseid.    
                   15250: 
1.243     albertel 15251: =back
                   15252: 
1.1172.2.109  raeburn  15253: =head2 Bubblesheet Configuration
                   15254: 
                   15255: =over 4
                   15256: 
                   15257: =item *
                   15258: 
                   15259: get_scantron_config($which)
                   15260: 
                   15261: $which - the name of the configuration to parse from the file.
                   15262: 
                   15263: Parses and returns the bubblesheet configuration line selected as a
                   15264: hash of configuration file fields.
                   15265: 
                   15266: 
                   15267: Returns:
                   15268:     If the named configuration is not in the file, an empty
                   15269:     hash is returned.
                   15270: 
                   15271:     a hash with the fields
                   15272:       name         - internal name for the this configuration setup
                   15273:       description  - text to display to operator that describes this config
                   15274:       CODElocation - if 0 or the string 'none'
                   15275:                           - no CODE exists for this config
                   15276:                      if -1 || the string 'letter'
                   15277:                           - a CODE exists for this config and is
                   15278:                             a string of letters
                   15279:                      Unsupported value (but planned for future support)
                   15280:                           if a positive integer
                   15281:                                - The CODE exists as the first n items from
                   15282:                                  the question section of the form
                   15283:                           if the string 'number'
                   15284:                                - The CODE exists for this config and is
                   15285:                                  a string of numbers
                   15286:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15287:                      the CODE starts
                   15288:       CODElength  - length of the CODE
                   15289:       IDstart     - column where the student/employee ID starts
                   15290:       IDlength    - length of the student/employee ID info
                   15291:       Qstart      - column where the information from the bubbled
                   15292:                     'questions' start
                   15293:       Qlength     - number of columns comprising a single bubble line from
                   15294:                     the sheet. (usually either 1 or 10)
                   15295:       Qon         - either a single character representing the character used
                   15296:                     to signal a bubble was chosen in the positional setup, or
                   15297:                     the string 'letter' if the letter of the chosen bubble is
                   15298:                     in the final, or 'number' if a number representing the
                   15299:                     chosen bubble is in the file (1->A 0->J)
                   15300:       Qoff        - the character used to represent that a bubble was
                   15301:                     left blank
                   15302:       PaperID     - if the scanning process generates a unique number for each
                   15303:                     sheet scanned the column that this ID number starts in
                   15304:       PaperIDlength - number of columns that comprise the unique ID number
                   15305:                       for the sheet of paper
                   15306:       FirstName   - column that the first name starts in
                   15307:       FirstNameLength - number of columns that the first name spans
                   15308:       LastName    - column that the last name starts in
                   15309:       LastNameLength - number of columns that the last name spans
                   15310:       BubblesPerRow - number of bubbles available in each row used to
                   15311:                       bubble an answer. (If not specified, 10 assumed).
                   15312: 
                   15313: 
                   15314: =item *
                   15315: 
                   15316: get_scantronformat_file($cdom)
                   15317: 
                   15318: $cdom - the course's domain (optional); if not supplied, uses
                   15319: domain for current $env{'request.course.id'}.
                   15320: 
                   15321: Returns an array containing lines from the scantron format file for
                   15322: the domain of the course.
                   15323: 
                   15324: If a url for a custom.tab file is listed in domain's configuration.db,
                   15325: lines are from this file.
                   15326: 
                   15327: Otherwise, if a default.tab has been published in RES space by the
                   15328: domainconfig user, lines are from this file.
                   15329: 
                   15330: Otherwise, fall back to getting lines from the legacy file on the
                   15331: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15332: 
                   15333: =back
                   15334: 
1.243     albertel 15335: =head2 Resource Subroutines
                   15336: 
                   15337: =over 4
1.191     harris41 15338: 
                   15339: =item *
                   15340: 
1.243     albertel 15341: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15342: 
                   15343: =item *
                   15344: 
1.243     albertel 15345: repcopy($filename) : subscribes to the requested file, and attempts to
                   15346: replicate from the owning library server, Might return
1.607     raeburn  15347: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15348: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15349: resource. Expects the local filesystem pathname
                   15350: (/home/httpd/html/res/....)
                   15351: 
                   15352: =back
                   15353: 
                   15354: =head2 Resource Information
                   15355: 
                   15356: =over 4
1.191     harris41 15357: 
                   15358: =item *
                   15359: 
1.1172.2.28  raeburn  15360: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15361: and returns the value of a variety of different possible values,
                   15362: $varname should be a request string, and the other parameters can be
                   15363: used to specify who and what one is asking about. Ordinarily, $cid 
                   15364: does not need to be specified, as it is retrived from 
                   15365: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15366: within lonuserstate::loadmap() when initializing a course, before
                   15367: $env{'request.course.id'} has been set, so it needs to be provided
                   15368: in that one case.
1.243     albertel 15369: 
                   15370: Possible values for $varname are environment.lastname (or other item
                   15371: from the envirnment hash), user.name (or someother aspect about the
                   15372: user), resource.0.maxtries (or some other part and parameter of a
                   15373: resource)
1.204     albertel 15374: 
                   15375: =item *
                   15376: 
1.243     albertel 15377: directcondval($number) : get current value of a condition; reads from a state
                   15378: string
1.204     albertel 15379: 
                   15380: =item *
                   15381: 
1.243     albertel 15382: condval($condidx) : value of condition index based on state
1.204     albertel 15383: 
                   15384: =item *
                   15385: 
1.243     albertel 15386: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15387: resource's metadata, $what should be either a specific key, or either
                   15388: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15389: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15390: 
                   15391: this function automatically caches all requests
1.191     harris41 15392: 
                   15393: =item *
                   15394: 
1.243     albertel 15395: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15396: network of library servers; returns file handle of where SQL and regex results
                   15397: will be stored for query
1.191     harris41 15398: 
                   15399: =item *
                   15400: 
1.1172.2.66  raeburn  15401: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15402: return symbolic list entry (all arguments optional).
                   15403: 
                   15404: Args: filename is the filename (including path) for the file for which a symb
                   15405: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15406: to check access status if more than one resource was found in the bighash
                   15407: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15408: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15409: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15410: cause possible symbs to be checked to determine if they are subject to content
                   15411: blocking, if so they will not be included as possible symbs; possibles is a
                   15412: ref to a hash, which, as a side effect, will be populated with all possible
                   15413: symbs (content blocking not tested).
                   15414: 
1.243     albertel 15415: returns the data handle
1.191     harris41 15416: 
                   15417: =item *
                   15418: 
1.1172.2.17  raeburn  15419: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15420: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15421: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15422: on failure, user must be in a course, as it assumes the existence of
                   15423: the course initial hash, and uses $env('request.course.id'}.  The third
                   15424: arg is an optional reference to a scalar.  If this arg is passed in the
                   15425: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15426: encrypted; otherwise it will be null.
1.243     albertel 15427: 
1.191     harris41 15428: =item *
                   15429: 
1.243     albertel 15430: symbclean($symb) : removes versions numbers from a symb, returns the
                   15431: cleaned symb
1.191     harris41 15432: 
                   15433: =item *
                   15434: 
1.243     albertel 15435: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15436: course map, user must be in a course for it to work.
1.191     harris41 15437: 
                   15438: =item *
                   15439: 
1.243     albertel 15440: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15441: 
                   15442: =item *
                   15443: 
1.243     albertel 15444: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15445: a random seed, all arguments are optional, if they aren't sent it uses the
                   15446: environment to derive them. Note: if symb isn't sent and it can't get one
                   15447: from &symbread it will use the current time as its return value
1.191     harris41 15448: 
                   15449: =item *
                   15450: 
1.243     albertel 15451: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15452: unfakeable, receipt
1.191     harris41 15453: 
                   15454: =item *
                   15455: 
1.620     albertel 15456: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15457: 
                   15458: =item *
                   15459: 
1.243     albertel 15460: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15461: 
                   15462: =item *
                   15463: 
1.243     albertel 15464: 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 15465: 
                   15466: =item *
                   15467: 
1.243     albertel 15468: 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 15469: 
                   15470: =item *
                   15471: 
1.243     albertel 15472: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15473: 
                   15474: =item *
                   15475: 
1.243     albertel 15476: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15477: forcing spreadsheet to reevaluate the resource scores next time.
                   15478: 
1.1172.2.13  raeburn  15479: =item *
                   15480: 
                   15481: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15482: when viewing in course context.
                   15483: 
                   15484:  input: six args -- filename (decluttered), course number, course domain,
                   15485:                     url, symb (if registered) and group (if this is a
                   15486:                     group item -- e.g., bulletin board, group page etc.).
                   15487: 
                   15488:  output: array of five scalars --
                   15489:          $cfile -- url for file editing if editable on current server
                   15490:          $home -- homeserver of resource (i.e., for author if published,
                   15491:                                           or course if uploaded.).
                   15492:          $switchserver --  1 if server switch will be needed.
                   15493:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15494:          $forceview -- 1 if icon/link should be to go to view mode
                   15495: 
                   15496: =item *
                   15497: 
                   15498: is_course_upload($file,$cnum,$cdom)
                   15499: 
                   15500: Used in course context to determine if current file was uploaded to
                   15501: the course (i.e., would be found in /userfiles/docs on the course's
                   15502: homeserver.
                   15503: 
                   15504:   input: 3 args -- filename (decluttered), course number and course domain.
                   15505:   output: boolean -- 1 if file was uploaded.
                   15506: 
1.243     albertel 15507: =back
                   15508: 
                   15509: =head2 Storing/Retreiving Data
                   15510: 
                   15511: =over 4
1.191     harris41 15512: 
                   15513: =item *
                   15514: 
1.1172.2.64  raeburn  15515: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15516: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15517: the remaining args aren't required and if they aren't passed or are '' they will
                   15518: be derived from the env (with the exception of $laststore, which is an
                   15519: optional arg used when a user's submission is stored in grading).
                   15520: $laststore is $version=$timestamp, where $version is the most recent version
                   15521: number retrieved for the corresponding $symb in the $namespace db file, and
                   15522: $timestamp is the timestamp for that transaction (UNIX time).
                   15523: $laststore is currently only passed when cstore() is called by
                   15524: structuretags::finalize_storage().
1.191     harris41 15525: 
                   15526: =item *
                   15527: 
1.1172.2.64  raeburn  15528: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15529: but uses critical subroutine
1.191     harris41 15530: 
                   15531: =item *
                   15532: 
1.243     albertel 15533: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15534: all args are optional
1.191     harris41 15535: 
                   15536: =item *
                   15537: 
1.717     albertel 15538: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15539: dumps the complete (or key matching regexp) namespace into a hash
                   15540: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15541: normally &store()ed into
                   15542: 
                   15543: $range should be either an integer '100' (give me the first 100
                   15544:                                            matching records)
                   15545:               or be  two integers sperated by a - with no spaces
                   15546:                  '30-50' (give me the 30th through the 50th matching
                   15547:                           records)
                   15548: 
                   15549: 
                   15550: =item *
                   15551: 
1.1172.2.59  raeburn  15552: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15553: replaces a &store() version of data with a replacement set of data
                   15554: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15555: reference. If $tolog is true, the transaction is logged in the courselog
                   15556: with an action=PUTSTORE.
1.717     albertel 15557: 
                   15558: =item *
                   15559: 
1.243     albertel 15560: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15561: works very similar to store/cstore, but all data is stored in a
                   15562: temporary location and can be reset using tmpreset, $storehash should
                   15563: be a hash reference, returns nothing on success
1.191     harris41 15564: 
                   15565: =item *
                   15566: 
1.243     albertel 15567: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15568: similar to restore, but all data is stored in a temporary location and
                   15569: can be reset using tmpreset. Returns a hash of values on success,
                   15570: error string otherwise.
1.191     harris41 15571: 
                   15572: =item *
                   15573: 
1.243     albertel 15574: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15575: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15576: 
                   15577: =item *
                   15578: 
1.243     albertel 15579: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15580: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15581: 
                   15582: =item *
                   15583: 
1.243     albertel 15584: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15585: namesp ($udom and $uname are optional)
1.191     harris41 15586: 
                   15587: =item *
                   15588: 
1.702     albertel 15589: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15590: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15591: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15592: 
1.702     albertel 15593: $range should be either an integer '100' (give me the first 100
                   15594:                                            matching records)
                   15595:               or be  two integers sperated by a - with no spaces
                   15596:                  '30-50' (give me the 30th through the 50th matching
                   15597:                           records)
1.449     matthew  15598: =item *
                   15599: 
                   15600: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15601: $store can be a scalar, an array reference, or if the amount to be 
                   15602: incremented is > 1, a hash reference.
                   15603: 
                   15604: ($udom and $uname are optional)
1.191     harris41 15605: 
                   15606: =item *
                   15607: 
1.243     albertel 15608: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15609: ($udom and $uname are optional)
1.191     harris41 15610: 
                   15611: =item *
                   15612: 
1.243     albertel 15613: cput($namespace,$storehash,$udom,$uname) : critical put
                   15614: ($udom and $uname are optional)
1.191     harris41 15615: 
                   15616: =item *
                   15617: 
1.748     albertel 15618: newput($namespace,$storehash,$udom,$uname) :
                   15619: 
                   15620: Attempts to store the items in the $storehash, but only if they don't
                   15621: currently exist, if this succeeds you can be certain that you have 
                   15622: successfully created a new key value pair in the $namespace db.
                   15623: 
                   15624: 
                   15625: Args:
                   15626:  $namespace: name of database to store values to
                   15627:  $storehash: hashref to store to the db
                   15628:  $udom: (optional) domain of user containing the db
                   15629:  $uname: (optional) name of user caontaining the db
                   15630: 
                   15631: Returns:
                   15632:  'ok' -> succeeded in storing all keys of $storehash
                   15633:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15634:                         least <key> already existed in the db (other
                   15635:                         requested keys may also already exist)
1.967     bisitz   15636:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15637:  'con_lost' -> unable to contact request server
                   15638:  'refused' -> action was not allowed by remote machine
                   15639: 
                   15640: 
                   15641: =item *
                   15642: 
1.243     albertel 15643: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15644: reference filled in from namesp (encrypts the return communication)
                   15645: ($udom and $uname are optional)
1.191     harris41 15646: 
                   15647: =item *
                   15648: 
1.243     albertel 15649: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15650: critical subroutine
                   15651: 
1.806     raeburn  15652: =item *
                   15653: 
1.860     raeburn  15654: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15655: array reference filled in from namespace found in domain level on either
                   15656: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15657: 
                   15658: =item *
                   15659: 
1.860     raeburn  15660: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15661: domain level either on specified domain server ($uhome) or primary domain 
                   15662: server ($udom and $uhome are optional)
1.806     raeburn  15663: 
1.943     raeburn  15664: =item * 
                   15665: 
1.1172.2.35  raeburn  15666: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15667: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15668: the target domain.
                   15669: 
                   15670: May also include additional key => value pairs for the following groups:
                   15671: 
                   15672: =over
                   15673: 
                   15674: =item
                   15675: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15676: 
                   15677: =over
                   15678: 
                   15679: =item defaultquota, authorquota
                   15680: 
                   15681: =back
                   15682: 
                   15683: =item
                   15684: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15685: portfolio for users).
                   15686: 
                   15687: =over
                   15688: 
                   15689: =item
                   15690: aboutme, blog, webdav, portfolio
                   15691: 
                   15692: =back
                   15693: 
                   15694: =item
                   15695: requestcourses: ability to request courses, and how requests are processed.
                   15696: 
                   15697: =over
                   15698: 
                   15699: =item
1.1172.2.37  raeburn  15700: official, unofficial, community, textbook
1.1172.2.35  raeburn  15701: 
                   15702: =back
                   15703: 
                   15704: =item
                   15705: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15706: 
                   15707: =over
                   15708: 
                   15709: =item
1.1172.2.44  raeburn  15710: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15711: 
                   15712: =back
                   15713: 
                   15714: =item
                   15715: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15716: for course's uploaded content.
                   15717: 
                   15718: =over
                   15719: 
                   15720: =item
1.1172.2.68  raeburn  15721: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15722: communityquota, textbookquota
1.1172.2.35  raeburn  15723: 
                   15724: =back
                   15725: 
                   15726: =item
                   15727: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15728: on your servers.
                   15729: 
                   15730: =over
                   15731: 
                   15732: =item
                   15733: remotesessions, hostedsessions
                   15734: 
                   15735: =back
                   15736: 
                   15737: =back
                   15738: 
                   15739: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15740: utility to create a configuration.db file on a domain's primary library server
                   15741: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15742: -- corresponding values are authentication type (internal, krb4, krb5,
                   15743: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15744: will be available. Values are retrieved from cache (if current), unless the
                   15745: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15746: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15747: 
                   15748: Typical usage:
1.943     raeburn  15749: 
1.1172.2.35  raeburn  15750: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15751: 
1.243     albertel 15752: =back
                   15753: 
                   15754: =head2 Network Status Functions
                   15755: 
                   15756: =over 4
1.191     harris41 15757: 
                   15758: =item *
                   15759: 
1.1137    raeburn  15760: dirlist() : return directory list based on URI (first arg).
                   15761: 
                   15762: Inputs: 1 required, 5 optional.
                   15763: 
                   15764: =over
                   15765: 
                   15766: =item 
                   15767: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15768: 
                   15769: =item
                   15770: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15771: 
                   15772: =item
                   15773: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15774: 
                   15775: =item
                   15776: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15777: 
                   15778: =item
                   15779: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15780: 
                   15781: =item 
                   15782: $alternateRoot - path to prepend in place of path from $uri.
                   15783: 
                   15784: =back
                   15785: 
                   15786: Returns: Array of up to two items.
                   15787: 
                   15788: =over
                   15789: 
                   15790: a reference to an array of files/subdirectories
                   15791: 
                   15792: =over
                   15793: 
                   15794: Each element in the array of files/subdirectories is a & separated list of
                   15795: item name and the result of running stat on the item.  If dirlist was requested
                   15796: for a file instead of a directory, the item name will be ''. For a directory 
                   15797: listing, if the item is a metadata file, the element will end &N&M 
                   15798: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15799: default copyright set (1).  
                   15800: 
                   15801: =back
                   15802: 
                   15803: a scalar containing error condition (if encountered).
                   15804: 
                   15805: =over
                   15806: 
                   15807: =item 
                   15808: no_host (no homeserver identified for $username:$domain).
                   15809: 
                   15810: =item 
                   15811: no_such_host (server contacted for listing not identified as valid host).
                   15812: 
                   15813: =item 
                   15814: con_lost (connection to remote server failed).
                   15815: 
                   15816: =item 
                   15817: refused (invalid $username:$domain received on lond side).
                   15818: 
                   15819: =item 
                   15820: no_such_dir (directory at specified path on lond side does not exist). 
                   15821: 
                   15822: =item 
                   15823: empty (directory at specified path on lond side is empty).
                   15824: 
                   15825: =over
                   15826: 
                   15827: This is currently not encountered because the &ls3, &ls2, 
                   15828: &ls (_handler) routines on the lond side do not filter out
                   15829: . and .. from a directory listing. 
                   15830: 
                   15831: =back
                   15832: 
                   15833: =back
                   15834: 
                   15835: =back
1.191     harris41 15836: 
                   15837: =item *
                   15838: 
1.243     albertel 15839: spareserver() : find server with least workload from spare.tab
                   15840: 
1.986     foxr     15841: 
                   15842: =item *
                   15843: 
                   15844: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15845: if there is no corresponding loncapa host.
                   15846: 
1.243     albertel 15847: =back
                   15848: 
1.986     foxr     15849: 
1.243     albertel 15850: =head2 Apache Request
                   15851: 
                   15852: =over 4
1.191     harris41 15853: 
                   15854: =item *
                   15855: 
1.243     albertel 15856: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15857: localhost, posts hash
                   15858: 
                   15859: =back
                   15860: 
                   15861: =head2 Data to String to Data
                   15862: 
                   15863: =over 4
1.191     harris41 15864: 
                   15865: =item *
                   15866: 
1.243     albertel 15867: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15868: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15869: 
                   15870: =item *
                   15871: 
1.243     albertel 15872: hashref2str($hashref) : convert a hashref into a string complete with
                   15873: escaping and '=' and '&' separators, supports elements that are
                   15874: arrayrefs and hashrefs
1.191     harris41 15875: 
                   15876: =item *
                   15877: 
1.243     albertel 15878: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15879: with escaping and '&' separators, supports elements that are arrayrefs
                   15880: and hashrefs
1.191     harris41 15881: 
                   15882: =item *
                   15883: 
1.243     albertel 15884: str2hash($string) : convert string to hash using unescaping and
                   15885: splitting on '=' and '&', supports elements that are arrayrefs and
                   15886: hashrefs
1.191     harris41 15887: 
                   15888: =item *
                   15889: 
1.243     albertel 15890: str2array($string) : convert string to hash using unescaping and
                   15891: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15892: 
                   15893: =back
                   15894: 
                   15895: =head2 Logging Routines
                   15896: 
                   15897: 
                   15898: These routines allow one to make log messages in the lonnet.log and
                   15899: lonnet.perm logfiles.
1.191     harris41 15900: 
1.1119    foxr     15901: =over 4
                   15902: 
1.191     harris41 15903: =item *
                   15904: 
1.243     albertel 15905: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15906: 
                   15907: =item *
                   15908: 
1.243     albertel 15909: logthis() : append message to the normal lonnet.log file, it gets
                   15910: preiodically rolled over and deleted.
1.191     harris41 15911: 
                   15912: =item *
                   15913: 
1.243     albertel 15914: logperm() : append a permanent message to lonnet.perm.log, this log
                   15915: file never gets deleted by any automated portion of the system, only
                   15916: messages of critical importance should go in here.
                   15917: 
1.1119    foxr     15918: 
1.243     albertel 15919: =back
                   15920: 
                   15921: =head2 General File Helper Routines
                   15922: 
                   15923: =over 4
1.191     harris41 15924: 
                   15925: =item *
                   15926: 
1.481     raeburn  15927: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15928: (a) files in /uploaded
                   15929:   (i) If a local copy of the file exists - 
                   15930:       compares modification date of local copy with last-modified date for 
                   15931:       definitive version stored on home server for course. If local copy is 
                   15932:       stale, requests a new version from the home server and stores it. 
                   15933:       If the original has been removed from the home server, then local copy 
                   15934:       is unlinked.
                   15935:   (ii) If local copy does not exist -
                   15936:       requests the file from the home server and stores it. 
                   15937:   
                   15938:   If $caller is 'uploadrep':  
                   15939:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15940:     for request for files originally uploaded via DOCS. 
                   15941:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15942:   
                   15943:   Otherwise:
                   15944:      This indicates a call from the content generation phase of the request.
                   15945:      -  returns the entire contents of the file or -1.
                   15946:      
                   15947: (b) files in /res
                   15948:    - returns the entire contents of a file or -1; 
                   15949:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15950: 
1.712     albertel 15951: 
                   15952: =item *
                   15953: 
                   15954: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15955:                   reference
                   15956: 
                   15957: returns either a stat() list of data about the file or an empty list
                   15958: if the file doesn't exist or couldn't find out about it (connection
                   15959: problems or user unknown)
                   15960: 
1.191     harris41 15961: =item *
                   15962: 
1.243     albertel 15963: filelocation($dir,$file) : returns file system location of a file
                   15964: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15965: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15966: and a file of ../bob will become /a/bob)
1.191     harris41 15967: 
                   15968: =item *
                   15969: 
                   15970: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15971: filelocation except for hrefs
                   15972: 
                   15973: =item *
                   15974: 
1.1172.2.49  raeburn  15975: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15976: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15977: 
1.243     albertel 15978: =back
                   15979: 
1.608     albertel 15980: =head2 Usererfile file routines (/uploaded*)
                   15981: 
                   15982: =over 4
                   15983: 
                   15984: =item *
                   15985: 
                   15986: userfileupload(): main rotine for putting a file in a user or course's
                   15987:                   filespace, arguments are,
                   15988: 
1.620     albertel 15989:  formname - required - this is the name of the element in $env where the
1.608     albertel 15990:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15991:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15992:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15993:  context - if coursedoc, store the file in the course of the active role
                   15994:              of the current user; 
                   15995:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15996:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15997:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15998:          if undefined, it will be placed in "unknown"
                   15999: 
                   16000:  (This routine calls clean_filename() to remove any dangerous
                   16001:  characters from the filename, and then calls finuserfileupload() to
                   16002:  complete the transaction)
                   16003: 
                   16004:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16005:  and /adm/notfound.html if unsuccessful
                   16006: 
                   16007: =item *
                   16008: 
                   16009: clean_filename(): routine for cleaing a filename up for storage in
                   16010:                  userfile space, argument is:
                   16011: 
                   16012:  filename - proposed filename
                   16013: 
                   16014: returns: the new clean filename
                   16015: 
                   16016: =item *
                   16017: 
1.1090    raeburn  16018: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16019: userspace, probably shouldn't be called directly
                   16020: 
                   16021:   docuname: username or courseid of destination for the file
                   16022:   docudom: domain of user/course of destination for the file
                   16023:   formname: same as for userfileupload()
1.1090    raeburn  16024:   fname: filename (including subdirectories) for the file
                   16025:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16026:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16027:   allfiles: reference to hash used to store objects found by parser
                   16028:   codebase: reference to hash used for codebases of java objects found by parser
                   16029:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16030:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16031:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16032:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16033:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16034:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16035:   mimetype: reference to scalar to accommodate mime type determined
                   16036:             from File::MMagic if $parser = parse.
1.608     albertel 16037: 
                   16038:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16039:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16040:  was 'overwrite').
                   16041:  
1.608     albertel 16042: 
                   16043: =item *
                   16044: 
                   16045: renameuserfile(): renames an existing userfile to a new name
                   16046: 
                   16047:   Args:
                   16048:    docuname: username or courseid of destination for the file
                   16049:    docudom: domain of user/course of destination for the file
                   16050:    old: current file name (including any subdirs under userfiles)
                   16051:    new: desired file name (including any subdirs under userfiles)
                   16052: 
                   16053: =item *
                   16054: 
                   16055: mkdiruserfile(): creates a directory is a userfiles dir
                   16056: 
                   16057:   Args:
                   16058:    docuname: username or courseid of destination for the file
                   16059:    docudom: domain of user/course of destination for the file
                   16060:    dir: dir to create (including any subdirs under userfiles)
                   16061: 
                   16062: =item *
                   16063: 
                   16064: removeuserfile(): removes a file that exists in userfiles
                   16065: 
                   16066:   Args:
                   16067:    docuname: username or courseid of destination for the file
                   16068:    docudom: domain of user/course of destination for the file
                   16069:    fname: filname to delete (including any subdirs under userfiles)
                   16070: 
                   16071: =item *
                   16072: 
                   16073: removeuploadedurl(): convience function for removeuserfile()
                   16074: 
                   16075:   Args:
                   16076:    url:  a full /uploaded/... url to delete
                   16077: 
1.747     albertel 16078: =item * 
                   16079: 
                   16080: get_portfile_permissions():
                   16081:   Args:
                   16082:     domain: domain of user or course contain the portfolio files
                   16083:     user: name of user or num of course contain the portfolio files
                   16084:   Returns:
                   16085:     hashref of a dump of the proper file_permissions.db
                   16086:    
                   16087: 
                   16088: =item * 
                   16089: 
                   16090: get_access_controls():
                   16091: 
                   16092: Args:
                   16093:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16094:   group: (optional) the group you want the files associated with
                   16095:   file: (optional) the file you want access info on
                   16096: 
                   16097: Returns:
1.749     raeburn  16098:     a hash (keys are file names) of hashes containing
                   16099:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16100:         values are XML containing access control settings (see below) 
1.747     albertel 16101: 
                   16102: Internal notes:
                   16103: 
1.749     raeburn  16104:  access controls are stored in file_permissions.db as key=value pairs.
                   16105:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16106:         where scope -> public,guest,course,group,domains or users.
                   16107:               end -> UNIX time for end of access (0 -> no end date)
                   16108:               start -> UNIX time for start of access
                   16109: 
                   16110:     value -> XML description of access control
                   16111:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16112:             <start></start>
                   16113:             <end></end>
                   16114: 
                   16115:             <password></password>  for scope type = guest
                   16116: 
                   16117:             <domain></domain>     for scope type = course or group
                   16118:             <number></number>
                   16119:             <roles id="">
                   16120:              <role></role>
                   16121:              <access></access>
                   16122:              <section></section>
                   16123:              <group></group>
                   16124:             </roles>
                   16125: 
                   16126:             <dom></dom>         for scope type = domains
                   16127: 
                   16128:             <users>             for scope type = users
                   16129:              <user>
                   16130:               <uname></uname>
                   16131:               <udom></udom>
                   16132:              </user>
                   16133:             </users>
                   16134:            </scope> 
                   16135:               
                   16136:  Access data is also aggregated for each file in an additional key=value pair:
                   16137:  key -> path to file/file_name\0accesscontrol 
                   16138:  value -> reference to hash
                   16139:           hash contains key = value pairs
                   16140:           where key = uniqueID:scope_end_start
                   16141:                 value = UNIX time record was last updated
                   16142: 
                   16143:           Used to improve speed of look-ups of access controls for each file.  
                   16144:  
                   16145:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16146: 
1.1172.2.13  raeburn  16147: =item *
                   16148: 
1.749     raeburn  16149: modify_access_controls():
                   16150: 
                   16151: Modifies access controls for a portfolio file
                   16152: Args
                   16153: 1. file name
                   16154: 2. reference to hash of required changes,
                   16155: 3. domain
                   16156: 4. username
                   16157:   where domain,username are the domain of the portfolio owner 
                   16158:   (either a user or a course) 
                   16159: 
                   16160: Returns:
                   16161: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16162: 2. result of deletions ('ok' or 'error', with error message).
                   16163: 3. reference to hash of any new or updated access controls.
                   16164: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16165:    key = integer (inbound ID)
1.1172.2.13  raeburn  16166:    value = uniqueID
                   16167: 
                   16168: =item *
                   16169: 
                   16170: get_timebased_id():
                   16171: 
                   16172: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16173: course via the Course Editor (e.g., folders, composite pages,
                   16174: group bulletin boards).
                   16175: 
                   16176: Args: (first three required; six others optional)
                   16177: 
                   16178: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16179:    docssequence, or name of group
                   16180: 
                   16181: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16182:    e.g., num, boardids
                   16183: 
                   16184: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16185:    file will be named nohist_namespace.db
                   16186: 
                   16187: 4. cdom: domain of course; default is current course domain from %env
                   16188: 
                   16189: 5. cnum: course number; default is current course number from %env
                   16190: 
                   16191: 6. idtype: set to concat if an additional digit is to be appended to the
                   16192:    unix timestamp to form the suffix, if the plain timestamp is already
                   16193:    in use.  Default is to not do this, but simply increment the unix
                   16194:    timestamp by 1 until a unique key is obtained.
                   16195: 
                   16196: 7. who: holder of locking key; defaults to user:domain for user.
                   16197: 
                   16198: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16199:    retrying); default is 3.
                   16200: 
                   16201: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16202: 
                   16203: Returns:
                   16204: 
                   16205: 1. suffix obtained (numeric)
                   16206: 
                   16207: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16208: 
                   16209: 3. error: contains (localized) error message if an error occurred.
                   16210: 
1.747     albertel 16211: 
1.608     albertel 16212: =back
                   16213: 
1.243     albertel 16214: =head2 HTTP Helper Routines
                   16215: 
                   16216: =over 4
                   16217: 
1.191     harris41 16218: =item *
                   16219: 
                   16220: escape() : unpack non-word characters into CGI-compatible hex codes
                   16221: 
                   16222: =item *
                   16223: 
                   16224: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16225: 
1.243     albertel 16226: =back
                   16227: 
                   16228: =head1 PRIVATE SUBROUTINES
                   16229: 
                   16230: =head2 Underlying communication routines (Shouldn't call)
                   16231: 
                   16232: =over 4
                   16233: 
                   16234: =item *
                   16235: 
                   16236: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16237: 
                   16238: =item *
                   16239: 
                   16240: reply() : uses subreply to send a message to remote machine, logs all failures
                   16241: 
                   16242: =item *
                   16243: 
                   16244: critical() : passes a critical message to another server; if cannot
                   16245: get through then place message in connection buffer directory and
                   16246: returns con_delayed, if incapable of saving message, returns
                   16247: con_failed
                   16248: 
                   16249: =item *
                   16250: 
                   16251: reconlonc() : tries to reconnect lonc client processes.
                   16252: 
                   16253: =back
                   16254: 
                   16255: =head2 Resource Access Logging
                   16256: 
                   16257: =over 4
                   16258: 
                   16259: =item *
                   16260: 
                   16261: flushcourselogs() : flush (save) buffer logs and access logs
                   16262: 
                   16263: =item *
                   16264: 
                   16265: courselog($what) : save message for course in hash
                   16266: 
                   16267: =item *
                   16268: 
                   16269: courseacclog($what) : save message for course using &courselog().  Perform
                   16270: special processing for specific resource types (problems, exams, quizzes, etc).
                   16271: 
1.191     harris41 16272: =item *
                   16273: 
                   16274: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16275: as a PerlChildExitHandler
1.243     albertel 16276: 
                   16277: =back
                   16278: 
                   16279: =head2 Other
                   16280: 
                   16281: =over 4
                   16282: 
                   16283: =item *
                   16284: 
                   16285: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16286: 
                   16287: =back
                   16288: 
                   16289: =cut
1.877     foxr     16290: 

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