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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.145! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.144 2021/12/24 21:13:15 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'};
1.1172.2.144  raeburn  2397:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2398:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2399:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2400:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2401:         }
1.1172.2.41  raeburn  2402:         foreach my $type (@coursetypes) {
                   2403:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2404:                 unless ($type eq 'community') {
                   2405:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2406:                 }
                   2407:             }
                   2408:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2409:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2410:             }
1.1172.2.60  raeburn  2411:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2412:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2413:                     $domdefaults{$type.'postsubtimeout'} =
                   2414:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2415:                 }
                   2416:             }
1.1172.2.30  raeburn  2417:         }
1.1172.2.67  raeburn  2418:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2419:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2420:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2421:                 if (@clonecodes) {
                   2422:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2423:                 }
                   2424:             }
                   2425:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2426:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2427:         }
1.1172.2.103  raeburn  2428:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2429:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2430:         }
1.1047    raeburn  2431:     }
1.1073    raeburn  2432:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2433:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2434:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2435:         }
                   2436:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2437:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2438:         }
1.1172.2.62  raeburn  2439:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2440:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2441:         }
1.1172.2.137  raeburn  2442:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2443:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2444:         }
1.1073    raeburn  2445:     }
1.1172.2.41  raeburn  2446:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2447:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2448:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2449:                             'approval','limit');
                   2450:             foreach my $type (@coursetypes) {
                   2451:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2452:                     my @mgrdc = ();
                   2453:                     foreach my $item (@settings) {
                   2454:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2455:                             push(@mgrdc,$item);
                   2456:                         }
                   2457:                     }
                   2458:                     if (@mgrdc) {
                   2459:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2460:                     }
                   2461:                 }
                   2462:             }
                   2463:         }
                   2464:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2465:             foreach my $type (@coursetypes) {
                   2466:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2467:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2468:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2469:                     }
                   2470:                 }
                   2471:             }
                   2472:         }
                   2473:     }
1.1172.2.46  raeburn  2474:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2475:         $domdefaults{'catauth'} = 'std';
                   2476:         $domdefaults{'catunauth'} = 'std';
                   2477:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2478:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2479:         }
                   2480:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2481:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2482:         }
                   2483:     }
1.1172.2.76  raeburn  2484:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2485:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2486:     }
1.1172.2.89  raeburn  2487:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2488:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2489:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2490:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2491:         }
                   2492:     }
1.1172.2.142  raeburn  2493:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2494:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2495:             if ($domconfig{'wafproxy'}{$item}) {
                   2496:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2497:             }
                   2498:         }
                   2499:     }
1.1172.2.23  raeburn  2500:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2501:     return %domdefaults;
                   2502: }
                   2503: 
1.1172.2.106  raeburn  2504: sub get_dom_cats {
                   2505:     my ($dom) = @_;
                   2506:     return unless (&domain($dom));
                   2507:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2508:     unless (defined($cached)) {
                   2509:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2510:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2511:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2512:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2513:             } else {
                   2514:                 $cats = {};
                   2515:             }
                   2516:         } else {
                   2517:             $cats = {};
                   2518:         }
                   2519:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2520:     }
                   2521:     return $cats;
                   2522: }
                   2523: 
                   2524: sub get_dom_instcats {
                   2525:     my ($dom) = @_;
                   2526:     return unless (&domain($dom));
                   2527:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2528:     unless (defined($cached)) {
                   2529:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2530:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2531:         if ($totcodes > 0) {
                   2532:             my $caller = 'global';
                   2533:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2534:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2535:                 $instcats = {
                   2536:                                 codes => \%codes,
                   2537:                                 codetitles => \@codetitles,
                   2538:                                 cat_titles => \%cat_titles,
                   2539:                                 cat_order => \%cat_order,
                   2540:                             };
                   2541:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2542:             }
                   2543:         }
                   2544:     }
                   2545:     return $instcats;
                   2546: }
                   2547: 
                   2548: sub retrieve_instcodes {
                   2549:     my ($coursecodes,$dom) = @_;
                   2550:     my $totcodes;
                   2551:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2552:     foreach my $course (keys(%courses)) {
                   2553:         if (ref($courses{$course}) eq 'HASH') {
                   2554:             if ($courses{$course}{'inst_code'} ne '') {
                   2555:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2556:                 $totcodes ++;
                   2557:             }
                   2558:         }
                   2559:     }
                   2560:     return $totcodes;
                   2561: }
                   2562: 
1.1172.2.113  raeburn  2563: # --------------------------------------------- Get domain config for passwords
                   2564: 
                   2565: sub get_passwdconf {
                   2566:     my ($dom) = @_;
                   2567:     my (%passwdconf,$gotconf,$lookup);
                   2568:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2569:     if (defined($cached)) {
                   2570:         if (ref($result) eq 'HASH') {
                   2571:             %passwdconf = %{$result};
                   2572:             $gotconf = 1;
                   2573:         }
                   2574:     }
                   2575:     unless ($gotconf) {
                   2576:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2577:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2578:             %passwdconf = %{$domconfig{'passwords'}};
                   2579:         }
                   2580:         my $cachetime = 24*60*60;
                   2581:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2582:     }
                   2583:     return %passwdconf;
                   2584: }
                   2585: 
1.344     www      2586: # --------------------------------------------------- Assign a key to a student
                   2587: 
                   2588: sub assign_access_key {
1.364     www      2589: #
                   2590: # a valid key looks like uname:udom#comments
                   2591: # comments are being appended
                   2592: #
1.498     www      2593:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2594:     $kdom=
1.620     albertel 2595:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2596:     $knum=
1.620     albertel 2597:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2598:     $cdom=
1.620     albertel 2599:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2600:     $cnum=
1.620     albertel 2601:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2602:     $udom=$env{'user.name'} unless (defined($udom));
                   2603:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2604:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2605:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2606:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2607:                                                   # assigned to this person
                   2608:                                                   # - this should not happen,
1.345     www      2609:                                                   # unless something went wrong
                   2610:                                                   # the first time around
                   2611: # ready to assign
1.364     www      2612:         $logentry=$1.'; '.$logentry;
1.496     www      2613:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2614:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2615: # key now belongs to user
1.346     www      2616: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2617:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2618:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2619:                 return 'ok';
                   2620:             } else {
                   2621:                 return 
                   2622:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2623: 	    }
                   2624:         } else {
                   2625:             return 'error: Could not assign key, try again later.';
                   2626:         }
1.364     www      2627:     } elsif (!$existing{$ckey}) {
1.345     www      2628: # the key does not exist
                   2629: 	return 'error: The key does not exist';
                   2630:     } else {
                   2631: # the key is somebody else's
                   2632: 	return 'error: The key is already in use';
                   2633:     }
1.344     www      2634: }
                   2635: 
1.364     www      2636: # ------------------------------------------ put an additional comment on a key
                   2637: 
                   2638: sub comment_access_key {
                   2639: #
                   2640: # a valid key looks like uname:udom#comments
                   2641: # comments are being appended
                   2642: #
                   2643:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2644:     $cdom=
1.620     albertel 2645:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2646:     $cnum=
1.620     albertel 2647:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2648:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2649:     if ($existing{$ckey}) {
                   2650:         $existing{$ckey}.='; '.$logentry;
                   2651: # ready to assign
1.367     www      2652:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2653:                                                  $cdom,$cnum) eq 'ok') {
                   2654: 	    return 'ok';
                   2655:         } else {
                   2656: 	    return 'error: Count not store comment.';
                   2657:         }
                   2658:     } else {
                   2659: # the key does not exist
                   2660: 	return 'error: The key does not exist';
                   2661:     }
                   2662: }
                   2663: 
1.344     www      2664: # ------------------------------------------------------ Generate a set of keys
                   2665: 
                   2666: sub generate_access_keys {
1.364     www      2667:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2668:     $cdom=
1.620     albertel 2669:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2670:     $cnum=
1.620     albertel 2671:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2672:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2673:     unless (($cdom) && ($cnum)) { return 0; }
                   2674:     if ($number>10000) { return 0; }
                   2675:     sleep(2); # make sure don't get same seed twice
                   2676:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2677:     my $total=0;
                   2678:     for (my $i=1;$i<=$number;$i++) {
                   2679:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2680:                   sprintf("%lx",int(100000*rand)).'-'.
                   2681:                   sprintf("%lx",int(100000*rand));
                   2682:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2683:        $newkey=~s/0/h/g; # and also 0 and O
                   2684:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2685:        if ($existing{$newkey}) {
                   2686:            $i--;
                   2687:        } else {
1.364     www      2688: 	  if (&put('accesskeys',
                   2689:               { $newkey => '# generated '.localtime().
1.620     albertel 2690:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2691:                            '; '.$logentry },
                   2692: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2693:               $total++;
                   2694: 	  }
                   2695:        }
                   2696:     }
1.620     albertel 2697:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2698:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2699:     return $total;
                   2700: }
                   2701: 
                   2702: # ------------------------------------------------------- Validate an accesskey
                   2703: 
                   2704: sub validate_access_key {
                   2705:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2706:     $cdom=
1.620     albertel 2707:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2708:     $cnum=
1.620     albertel 2709:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2710:     $udom=$env{'user.domain'} unless (defined($udom));
                   2711:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2712:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2713:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2714: }
                   2715: 
                   2716: # ------------------------------------- Find the section of student in a course
1.652     albertel 2717: sub devalidate_getsection_cache {
                   2718:     my ($udom,$unam,$courseid)=@_;
                   2719:     my $hashid="$udom:$unam:$courseid";
                   2720:     &devalidate_cache_new('getsection',$hashid);
                   2721: }
1.298     matthew  2722: 
1.815     albertel 2723: sub courseid_to_courseurl {
                   2724:     my ($courseid) = @_;
                   2725:     #already url style courseid
                   2726:     return $courseid if ($courseid =~ m{^/});
                   2727: 
                   2728:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2729: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2730: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2731: 	return "/$cdom/$cnum";
                   2732:     }
                   2733: 
                   2734:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2735:     if (exists($courseinfo{'num'})) {
                   2736: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2737:     }
                   2738: 
                   2739:     return undef;
                   2740: }
                   2741: 
1.298     matthew  2742: sub getsection {
                   2743:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2744:     my $cachetime=1800;
1.551     albertel 2745: 
                   2746:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2747:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2748:     if (defined($cached)) { return $result; }
                   2749: 
1.298     matthew  2750:     my %Pending; 
                   2751:     my %Expired;
                   2752:     #
                   2753:     # Each role can either have not started yet (pending), be active, 
                   2754:     #    or have expired.
                   2755:     #
                   2756:     # If there is an active role, we are done.
                   2757:     #
                   2758:     # If there is more than one role which has not started yet, 
                   2759:     #     choose the one which will start sooner
                   2760:     # If there is one role which has not started yet, return it.
                   2761:     #
                   2762:     # If there is more than one expired role, choose the one which ended last.
                   2763:     # If there is a role which has expired, return it.
                   2764:     #
1.815     albertel 2765:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2766:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2767:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2768:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2769:         my $section=$1;
                   2770:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2771:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2772:         my $now=time;
1.548     albertel 2773:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2774:             $Expired{$end}=$section;
                   2775:             next;
                   2776:         }
1.548     albertel 2777:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2778:             $Pending{$start}=$section;
                   2779:             next;
                   2780:         }
1.599     albertel 2781:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2782:     }
                   2783:     #
                   2784:     # Presumedly there will be few matching roles from the above
                   2785:     # loop and the sorting time will be negligible.
                   2786:     if (scalar(keys(%Pending))) {
                   2787:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2788:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2789:     } 
                   2790:     if (scalar(keys(%Expired))) {
                   2791:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2792:         my $time = pop(@sorted);
1.599     albertel 2793:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2794:     }
1.599     albertel 2795:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2796: }
1.70      www      2797: 
1.599     albertel 2798: sub save_cache {
                   2799:     &purge_remembered();
1.722     albertel 2800:     #&Apache::loncommon::validate_page();
1.620     albertel 2801:     undef(%env);
1.780     albertel 2802:     undef($env_loaded);
1.599     albertel 2803: }
1.452     albertel 2804: 
1.599     albertel 2805: my $to_remember=-1;
                   2806: my %remembered;
                   2807: my %accessed;
                   2808: my $kicks=0;
                   2809: my $hits=0;
1.849     albertel 2810: sub make_key {
                   2811:     my ($name,$id) = @_;
1.872     albertel 2812:     if (length($id) > 65 
                   2813: 	&& length(&escape($id)) > 200) {
                   2814: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2815:     }
1.849     albertel 2816:     return &escape($name.':'.$id);
                   2817: }
                   2818: 
1.599     albertel 2819: sub devalidate_cache_new {
                   2820:     my ($name,$id,$debug) = @_;
                   2821:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2822:     my $remembered_id=$name.':'.$id;
1.849     albertel 2823:     $id=&make_key($name,$id);
1.599     albertel 2824:     $memcache->delete($id);
1.1172.2.81  raeburn  2825:     delete($remembered{$remembered_id});
                   2826:     delete($accessed{$remembered_id});
1.599     albertel 2827: }
                   2828: 
                   2829: sub is_cached_new {
                   2830:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2831:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2832:                                      # keys in %remembered hash, which persists for
                   2833:                                      # duration of request (no restriction on key length).
                   2834:     if (exists($remembered{$remembered_id})) {
                   2835: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2836: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2837: 	$hits++;
1.1172.2.81  raeburn  2838: 	return ($remembered{$remembered_id},1);
1.599     albertel 2839:     }
1.1172.2.81  raeburn  2840:     $id=&make_key($name,$id);
1.599     albertel 2841:     my $value = $memcache->get($id);
                   2842:     if (!(defined($value))) {
                   2843: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2844: 	return (undef,undef);
1.416     albertel 2845:     }
1.599     albertel 2846:     if ($value eq '__undef__') {
                   2847: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2848: 	$value=undef;
                   2849:     }
1.1172.2.81  raeburn  2850:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2851:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2852:     return ($value,1);
                   2853: }
                   2854: 
                   2855: sub do_cache_new {
                   2856:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2857:     my $remembered_id=$name.':'.$id;
1.849     albertel 2858:     $id=&make_key($name,$id);
1.599     albertel 2859:     my $setvalue=$value;
                   2860:     if (!defined($setvalue)) {
                   2861: 	$setvalue='__undef__';
                   2862:     }
1.623     albertel 2863:     if (!defined($time) ) {
                   2864: 	$time=600;
                   2865:     }
1.599     albertel 2866:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2867:     my $result = $memcache->set($id,$setvalue,$time);
                   2868:     if (! $result) {
1.872     albertel 2869: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2870: 	$memcache->disconnect_all();
1.872     albertel 2871:     }
1.600     albertel 2872:     # need to make a copy of $value
1.1172.2.81  raeburn  2873:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2874:     return $value;
                   2875: }
                   2876: 
                   2877: sub make_room {
1.1172.2.81  raeburn  2878:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2879: 
1.1172.2.81  raeburn  2880:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2881:                                     : $value;
1.599     albertel 2882:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2883:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2884:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2885:     my $to_kick;
                   2886:     my $max_time=0;
                   2887:     foreach my $other (keys(%accessed)) {
                   2888: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2889: 	    $to_kick=$other;
                   2890: 	    $max_time=&tv_interval($accessed{$other});
                   2891: 	}
                   2892:     }
                   2893:     delete($remembered{$to_kick});
                   2894:     delete($accessed{$to_kick});
                   2895:     $kicks++;
                   2896:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2897:     return;
                   2898: }
                   2899: 
1.599     albertel 2900: sub purge_remembered {
1.604     albertel 2901:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2902:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2903:     undef(%remembered);
                   2904:     undef(%accessed);
1.428     albertel 2905: }
1.70      www      2906: # ------------------------------------- Read an entry from a user's environment
                   2907: 
                   2908: sub userenvironment {
                   2909:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2910:     my $items;
                   2911:     foreach my $item (@what) {
                   2912:         $items.=&escape($item).'&';
                   2913:     }
                   2914:     $items=~s/\&$//;
1.70      www      2915:     my %returnhash=();
1.1009    raeburn  2916:     my $uhome = &homeserver($unam,$udom);
                   2917:     unless ($uhome eq 'no_host') {
                   2918:         my @answer=split(/\&/, 
                   2919:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2920:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2921:             return %returnhash;
                   2922:         }
1.1009    raeburn  2923:         my $i;
                   2924:         for ($i=0;$i<=$#what;$i++) {
                   2925: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2926:         }
1.70      www      2927:     }
                   2928:     return %returnhash;
1.1       albertel 2929: }
                   2930: 
1.617     albertel 2931: # ---------------------------------------------------------- Get a studentphoto
                   2932: sub studentphoto {
                   2933:     my ($udom,$unam,$ext) = @_;
                   2934:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2935:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2936:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2937:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2938:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2939:             } else {
                   2940:                 my ($result,$perm_reqd)=
1.707     albertel 2941: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2942:                 if ($result eq 'ok') {
                   2943:                     if (!($perm_reqd eq 'yes')) {
                   2944:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2945:                     }
                   2946:                 }
                   2947:             }
                   2948:         }
                   2949:     } else {
                   2950:         my ($result,$perm_reqd) = 
1.707     albertel 2951: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2952:         if ($result eq 'ok') {
                   2953:             if (!($perm_reqd eq 'yes')) {
                   2954:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2955:             }
                   2956:         }
                   2957:     }
                   2958:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2959: }
                   2960: 
                   2961: sub retrievestudentphoto {
                   2962:     my ($udom,$unam,$ext,$type) = @_;
                   2963:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2964:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2965:     if ($ret eq 'ok') {
                   2966:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2967:         if ($type eq 'thumbnail') {
                   2968:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2969:         }
                   2970:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2971:         return $tokenurl;
                   2972:     } else {
                   2973:         if ($type eq 'thumbnail') {
                   2974:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2975:         } else { 
                   2976:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2977:         }
1.617     albertel 2978:     }
                   2979: }
                   2980: 
1.263     www      2981: # -------------------------------------------------------------------- New chat
                   2982: 
                   2983: sub chatsend {
1.724     raeburn  2984:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2985:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2986:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2987:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2988:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2989: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2990: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2991: }
                   2992: 
                   2993: # ------------------------------------------ Find current version of a resource
                   2994: 
                   2995: sub getversion {
                   2996:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2997:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2998:     return &currentversion(&filelocation('',$fname));
                   2999: }
                   3000: 
                   3001: sub currentversion {
                   3002:     my $fname=shift;
                   3003:     my $author=$fname;
                   3004:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3005:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3006:     my $home=&homeserver($uname,$udom);
1.292     www      3007:     if ($home eq 'no_host') { 
                   3008:         return -1; 
                   3009:     }
1.1112    www      3010:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3011:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3012: 	return -1;
                   3013:     }
1.1112    www      3014:     return $answer;
1.263     www      3015: }
                   3016: 
1.1111    www      3017: #
                   3018: # Return special version number of resource if set by override, empty otherwise
                   3019: #
                   3020: sub usedversion {
                   3021:     my $fname=shift;
                   3022:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3023:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3024:     if ($urlversion) { return $urlversion; }
                   3025:     return '';
                   3026: }
                   3027: 
1.1       albertel 3028: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3029: 
1.1       albertel 3030: sub subscribe {
                   3031:     my $fname=shift;
1.761     raeburn  3032:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3033:     $fname=~s/[\n\r]//g;
1.1       albertel 3034:     my $author=$fname;
                   3035:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3036:     my ($udom,$uname)=split(/\//,$author);
                   3037:     my $home=homeserver($uname,$udom);
1.335     albertel 3038:     if ($home eq 'no_host') {
                   3039:         return 'not_found';
1.1       albertel 3040:     }
                   3041:     my $answer=reply("sub:$fname",$home);
1.64      www      3042:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3043: 	$answer.=' by '.$home;
                   3044:     }
1.1       albertel 3045:     return $answer;
                   3046: }
                   3047:     
1.8       www      3048: # -------------------------------------------------------------- Replicate file
                   3049: 
                   3050: sub repcopy {
                   3051:     my $filename=shift;
1.23      www      3052:     $filename=~s/\/+/\//g;
1.1142    raeburn  3053:     my $londocroot = $perlvar{'lonDocRoot'};
                   3054:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3055:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3056:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3057: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3058: 	return &repcopy_userfile($filename);
                   3059:     }
1.532     albertel 3060:     $filename=~s/[\n\r]//g;
1.8       www      3061:     my $transname="$filename.in.transfer";
1.828     www      3062: # FIXME: this should flock
1.607     raeburn  3063:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3064:     my $remoteurl=subscribe($filename);
1.64      www      3065:     if ($remoteurl =~ /^con_lost by/) {
                   3066: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3067:            return 'unavailable';
1.8       www      3068:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3069: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3070: 	   return 'not_found';
1.64      www      3071:     } elsif ($remoteurl =~ /^rejected by/) {
                   3072: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3073:            return 'forbidden';
1.20      www      3074:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3075:            return 'ok';
1.8       www      3076:     } else {
1.290     www      3077:         my $author=$filename;
                   3078:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3079:         my ($udom,$uname)=split(/\//,$author);
                   3080:         my $home=homeserver($uname,$udom);
                   3081:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3082:            my @parts=split(/\//,$filename);
                   3083:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3084:            if ($path ne "$londocroot/res") {
1.8       www      3085:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3086: 	       return 'bad_request';
1.8       www      3087:            }
                   3088:            my $count;
                   3089:            for ($count=5;$count<$#parts;$count++) {
                   3090:                $path.="/$parts[$count]";
                   3091:                if ((-e $path)!=1) {
                   3092: 		   mkdir($path,0777);
                   3093:                }
                   3094:            }
                   3095:            my $ua=new LWP::UserAgent;
                   3096:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3097:            my $response=$ua->request($request,$transname);
                   3098:            if ($response->is_error()) {
                   3099: 	       unlink($transname);
                   3100:                my $message=$response->status_line;
1.672     albertel 3101:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3102:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3103:                return 'unavailable';
1.8       www      3104:            } else {
1.16      www      3105: 	       if ($remoteurl!~/\.meta$/) {
                   3106:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3107:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3108:                   if ($mresponse->is_error()) {
                   3109: 		      unlink($filename.'.meta');
                   3110:                       &logthis(
1.672     albertel 3111:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3112:                   }
                   3113: 	       }
1.8       www      3114:                rename($transname,$filename);
1.607     raeburn  3115:                return 'ok';
1.8       www      3116:            }
1.290     www      3117:        }
1.8       www      3118:     }
1.330     www      3119: }
                   3120: 
1.1172.2.124  raeburn  3121: # ------------------------------------------------- Unsubscribe from a resource
                   3122: 
                   3123: sub unsubscribe {
                   3124:     my ($fname) = @_;
                   3125:     my $answer;
                   3126:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3127:     $fname=~s/[\n\r]//g;
                   3128:     my $author=$fname;
                   3129:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3130:     my ($udom,$uname)=split(/\//,$author);
                   3131:     my $home=homeserver($uname,$udom);
                   3132:     if ($home eq 'no_host') {
                   3133:         $answer = 'no_host';
                   3134:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3135:         $answer = 'home';
                   3136:     } else {
1.1172.2.125  raeburn  3137:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3138:     }
                   3139:     return $answer;
                   3140: }
                   3141: 
1.330     www      3142: # ------------------------------------------------ Get server side include body
                   3143: sub ssi_body {
1.381     albertel 3144:     my ($filelink,%form)=@_;
1.606     matthew  3145:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3146:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3147:     }
1.953     www      3148:     my $output='';
                   3149:     my $response;
1.980     raeburn  3150:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3151:        ($output,$response)=&externalssi($filelink);
1.953     www      3152:     } else {
1.1004    droeschl 3153:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3154:        $filelink .= 'inhibitmenu=yes';
1.953     www      3155:        ($output,$response)=&ssi($filelink,%form);
                   3156:     }
1.778     albertel 3157:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3158:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3159:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3160:     if (wantarray) {
                   3161:         return ($output, $response);
                   3162:     } else {
                   3163:         return $output;
                   3164:     }
1.8       www      3165: }
                   3166: 
1.15      www      3167: # --------------------------------------------------------- Server Side Include
                   3168: 
1.782     albertel 3169: sub absolute_url {
1.1172.2.145! raeburn  3170:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3171:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3172:     if ($host_name eq '') {
                   3173: 	$host_name = $ENV{'SERVER_NAME'};
                   3174:     }
1.1172.2.145! raeburn  3175:     if ($unalias) {
        !          3176:         my $alias = &get_proxy_alias();
        !          3177:         if ($alias eq $host_name) {
        !          3178:             my $lonhost = $perlvar{'lonHostID'};
        !          3179:             my $hostname = &hostname($lonhost);
        !          3180:             my $lcproto;
        !          3181:             if (($keep_proto) || ($hostname eq '')) {
        !          3182:                 $lcproto = $protocol;
        !          3183:             } else {
        !          3184:                 $lcproto = $protocol{$lonhost};
        !          3185:                 $lcproto = 'http' if ($lcproto ne 'https');
        !          3186:                 $lcproto .= '://';
        !          3187:             }
        !          3188:             unless ($hostname eq '') {
        !          3189:                 return $lcproto.$hostname;
        !          3190:             }
        !          3191:         }
        !          3192:     } 
1.782     albertel 3193:     return $protocol.$host_name;
                   3194: }
                   3195: 
1.942     foxr     3196: #
                   3197: #   Server side include.
                   3198: # Parameters:
                   3199: #  fn     Possibly encrypted resource name/id.
                   3200: #  form   Hash that describes how the rendering should be done
                   3201: #         and other things.
1.944     foxr     3202: # Returns:
1.950     raeburn  3203: #   Scalar context: The content of the response.
                   3204: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3205: #     
1.15      www      3206: sub ssi {
                   3207: 
1.944     foxr     3208:     my ($fn,%form)=@_;
1.1172.2.145! raeburn  3209:     my ($host,$request,$response);
        !          3210:     $host = &absolute_url('',1);
1.711     albertel 3211: 
                   3212:     $form{'no_update_last_known'}=1;
1.895     albertel 3213:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3214:     if (%form) {
1.1172.2.145! raeburn  3215:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3216:       $request->content(join('&',map {
                   3217:             my $name = escape($_);
                   3218:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3219:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3220:             : &escape($form{$_}) );
                   3221:         } keys(%form)));
1.23      www      3222:     } else {
1.1172.2.145! raeburn  3223:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3224:     }
                   3225: 
1.15      www      3226:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3227: 
1.1172.2.101  raeburn  3228:     if (($env{'request.course.id'}) &&
                   3229:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3230:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3231:         ($form{'grade_symb'} ne '') &&
                   3232:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3233:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3234:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3235:             my $ua=new LWP::UserAgent;
                   3236:             $ua->local_address('127.0.0.1');
                   3237:             $response = $ua->request($request);
                   3238:         } else {
                   3239:             {
                   3240:                 require LWP::Protocol::http;
                   3241:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3242:                 my $ua=new LWP::UserAgent;
                   3243:                 $response = $ua->request($request);
                   3244:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3245:             }
                   3246:         }
                   3247:     } else {
                   3248:         my $ua=new LWP::UserAgent;
                   3249:         $response = $ua->request($request);
                   3250:     }
1.944     foxr     3251:     if (wantarray) {
1.1172.2.3  raeburn  3252: 	return ($response->content, $response);
1.944     foxr     3253:     } else {
1.1172.2.3  raeburn  3254: 	return $response->content;
1.942     foxr     3255:     }
1.324     www      3256: }
                   3257: 
                   3258: sub externalssi {
                   3259:     my ($url)=@_;
                   3260:     my $ua=new LWP::UserAgent;
                   3261:     my $request=new HTTP::Request('GET',$url);
                   3262:     my $response=$ua->request($request);
1.954     raeburn  3263:     if (wantarray) {
                   3264:         return ($response->content, $response);
                   3265:     } else {
                   3266:         return $response->content;
                   3267:     }
1.15      www      3268: }
1.254     www      3269: 
1.1172.2.98  raeburn  3270: # If the local copy of a replicated resource is outdated, trigger a
                   3271: # connection from the homeserver to flush the delayed queue. If no update
                   3272: # happens, remove local copies of outdated resource (and corresponding
                   3273: # metadata file).
                   3274: 
                   3275: sub remove_stale_resfile {
                   3276:     my ($url) = @_;
                   3277:     my $removed;
                   3278:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3279:         my $audom = $1;
                   3280:         my $auname = $2;
                   3281:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3282:             my $homeserver = &homeserver($auname,$audom);
                   3283:             unless (($homeserver eq 'no_host') ||
                   3284:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3285:                 my $fname = &filelocation('',$url);
                   3286:                 if (-e $fname) {
                   3287:                     my $hostname = &hostname($homeserver);
                   3288:                     if ($hostname) {
1.1172.2.120  raeburn  3289:                         my $protocol = $protocol{$homeserver};
                   3290:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3291:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3292:                         my $ua=new LWP::UserAgent;
                   3293:                         $ua->timeout(5);
1.1172.2.98  raeburn  3294:                         my $request=new HTTP::Request('HEAD',$uri);
                   3295:                         my $response=$ua->request($request);
                   3296:                         if ($response->is_success()) {
                   3297:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3298:                             my $locmodtime = (stat($fname))[9];
                   3299:                             if ($locmodtime < $remmodtime) {
                   3300:                                 my $stale;
                   3301:                                 my $answer = &reply('pong',$homeserver);
                   3302:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3303:                                     sleep(0.2);
                   3304:                                     $locmodtime = (stat($fname))[9];
                   3305:                                     if ($locmodtime < $remmodtime) {
                   3306:                                         my $posstransfer = $fname.'.in.transfer';
                   3307:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3308:                                             $removed = 1;
                   3309:                                         } else {
                   3310:                                             $stale = 1;
                   3311:                                         }
                   3312:                                     } else {
                   3313:                                         $removed = 1;
                   3314:                                     }
                   3315:                                 } else {
                   3316:                                     $stale = 1;
                   3317:                                 }
                   3318:                                 if ($stale) {
1.1172.2.124  raeburn  3319:                                     if (unlink($fname)) {
                   3320:                                         if ($uri!~/\.meta$/) {
                   3321:                                             if (-e $fname.'.meta') {
                   3322:                                                 unlink($fname.'.meta');
                   3323:                                             }
                   3324:                                         }
                   3325:                                         my $unsubresult = &unsubscribe($fname);
                   3326:                                         unless ($unsubresult eq 'ok') {
                   3327:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3328:                                         }
                   3329:                                         $removed = 1;
1.1172.2.98  raeburn  3330:                                     }
                   3331:                                 }
                   3332:                             }
                   3333:                         }
                   3334:                     }
                   3335:                 }
                   3336:             }
                   3337:         }
                   3338:     }
                   3339:     return $removed;
                   3340: }
                   3341: 
1.492     albertel 3342: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3343: 
                   3344: sub allowuploaded {
                   3345:     my ($srcurl,$url)=@_;
                   3346:     $url=&clutter(&declutter($url));
                   3347:     my $dir=$url;
                   3348:     $dir=~s/\/[^\/]+$//;
                   3349:     my %httpref=();
                   3350:     my $httpurl=&hreflocation('',$url);
                   3351:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3352:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3353: }
1.477     raeburn  3354: 
1.1172.2.13  raeburn  3355: #
                   3356: # Determine if the current user should be able to edit a particular resource,
                   3357: # when viewing in course context.
                   3358: # (a) When viewing resource used to determine if "Edit" item is included in
                   3359: #     Functions.
                   3360: # (b) When displaying folder contents in course editor, used to determine if
                   3361: #     "Edit" link will be displayed alongside resource.
                   3362: #
                   3363: #  input: six args -- filename (decluttered), course number, course domain,
                   3364: #                   url, symb (if registered) and group (if this is a group
                   3365: #                   item -- e.g., bulletin board, group page etc.).
                   3366: #  output: array of five scalars --
                   3367: #          $cfile -- url for file editing if editable on current server
                   3368: #          $home -- homeserver of resource (i.e., for author if published,
                   3369: #                                           or course if uploaded.).
                   3370: #          $switchserver --  1 if server switch will be needed.
                   3371: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3372: #          $forceview -- 1 if icon/link should be to go to view mode
                   3373: #
                   3374: 
                   3375: sub can_edit_resource {
                   3376:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3377:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3378: #
                   3379: # For aboutme pages user can only edit his/her own.
                   3380: #
                   3381:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3382:         my ($sdom,$sname) = ($1,$2);
                   3383:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3384:             $home = $env{'user.home'};
                   3385:             $cfile = $resurl;
                   3386:             if ($env{'form.forceedit'}) {
                   3387:                 $forceview = 1;
                   3388:             } else {
                   3389:                 $forceedit = 1;
                   3390:             }
                   3391:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3392:         } else {
                   3393:             return;
                   3394:         }
                   3395:     }
                   3396: 
                   3397:     if ($env{'request.course.id'}) {
                   3398:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3399:         if ($group ne '') {
                   3400: # if this is a group homepage or group bulletin board, check group privs
                   3401:             my $allowed = 0;
                   3402:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3403:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3404:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3405:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3406:                     $allowed = 1;
                   3407:                 }
                   3408:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3409:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3410:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3411:                     $allowed = 1;
                   3412:                 }
                   3413:             }
                   3414:             if ($allowed) {
                   3415:                 $home=&homeserver($cnum,$cdom);
                   3416:                 if ($env{'form.forceedit'}) {
                   3417:                     $forceview = 1;
                   3418:                 } else {
                   3419:                     $forceedit = 1;
                   3420:                 }
                   3421:                 $cfile = $resurl;
                   3422:             } else {
                   3423:                 return;
                   3424:             }
                   3425:         } else {
1.1172.2.15  raeburn  3426:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3427:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3428:                     return;
                   3429:                 }
                   3430:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3431: #
                   3432: # No edit allowed where CC has switched to student role.
                   3433: #
                   3434:                 return;
                   3435:             }
                   3436:         }
                   3437:     }
                   3438: 
                   3439:     if ($file ne '') {
                   3440:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3441:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3442:                 $uploaded = 1;
                   3443:                 $incourse = 1;
                   3444:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3445:                     $cfile = &hreflocation('',$file);
                   3446:                     if ($env{'form.forceedit'}) {
                   3447:                         $forceview = 1;
                   3448:                     } else {
                   3449:                         $forceedit = 1;
                   3450:                     }
                   3451:                 }
                   3452:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3453:                 $incourse = 1;
                   3454:                 if ($env{'form.forceedit'}) {
                   3455:                     $forceview = 1;
                   3456:                 } else {
                   3457:                     $forceedit = 1;
                   3458:                 }
                   3459:                 $cfile = $resurl;
                   3460:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3461:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3462:                     $incourse = 1;
                   3463:                     if ($env{'form.forceedit'}) {
                   3464:                         $forceview = 1;
                   3465:                     } else {
                   3466:                         $forceedit = 1;
                   3467:                     }
                   3468:                     $cfile = $resurl;
                   3469:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3470:                     $incourse = 1;
                   3471:                     $cfile = $resurl.'/smpedit';
                   3472:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3473:                     $incourse = 1;
                   3474:                     if ($env{'form.forceedit'}) {
                   3475:                         $forceview = 1;
                   3476:                     } else {
                   3477:                         $forceedit = 1;
                   3478:                     }
                   3479:                     $cfile = $resurl;
1.1172.2.122  raeburn  3480:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3481:                     my ($map,$id,$res) = &decode_symb($symb);
                   3482:                     if ($map =~ /\.page$/) {
                   3483:                         $incourse = 1;
                   3484:                         if ($env{'form.forceedit'}) {
                   3485:                             $forceview = 1;
                   3486:                             $cfile = $map;
                   3487:                         } else {
                   3488:                             $forceedit = 1;
                   3489:                             $cfile =  '/adm/wrapper'.$resurl;
                   3490:                         }
                   3491:                     }
1.1172.2.15  raeburn  3492:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3493:                     $incourse = 1;
                   3494:                     if ($env{'form.forceedit'}) {
                   3495:                         $forceview = 1;
                   3496:                     } else {
                   3497:                         $forceedit = 1;
                   3498:                     }
                   3499:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3500:                 }
                   3501:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3502:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3503:                 if (&is_on_map($template)) {
                   3504:                     $incourse = 1;
                   3505:                     $forceview = 1;
                   3506:                     $cfile = $template;
                   3507:                 }
                   3508:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3509:                 $incourse = 1;
                   3510:                 if ($env{'form.forceedit'}) {
                   3511:                     $forceview = 1;
                   3512:                 } else {
                   3513:                     $forceedit = 1;
                   3514:                 }
                   3515:                 $cfile = $resurl;
1.1172.2.13  raeburn  3516:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3517:                 $incourse = 1;
                   3518:                 $forceview = 1;
                   3519:                 if ($symb) {
                   3520:                     my ($map,$id,$res)=&decode_symb($symb);
                   3521:                     $env{'request.symb'} = $symb;
                   3522:                     $cfile = &clutter($res);
                   3523:                 } else {
                   3524:                     $cfile = $env{'form.suppurl'};
                   3525:                     $cfile =~ s{^http://}{};
                   3526:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3527:                 }
1.1172.2.31  raeburn  3528:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3529:                 if ($env{'form.forceedit'}) {
                   3530:                     $forceview = 1;
                   3531:                 } else {
                   3532:                     $forceedit = 1;
                   3533:                 }
                   3534:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3535:             }
                   3536:         }
                   3537:         if ($uploaded || $incourse) {
                   3538:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3539:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3540:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3541:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3542:             # Check that the user has permission to edit this resource
                   3543:             my $setpriv = 1;
                   3544:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3545:             if (defined($cfudom)) {
                   3546:                 $home=&homeserver($cfuname,$cfudom);
                   3547:                 $cfile=$file;
                   3548:             }
                   3549:         }
                   3550:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3551:             (($home ne '') && ($home ne 'no_host'))) {
                   3552:             my @ids=&current_machine_ids();
                   3553:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3554:                 $switchserver=1;
                   3555:             }
                   3556:         }
                   3557:     }
                   3558:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3559: }
                   3560: 
                   3561: sub is_course_upload {
                   3562:     my ($file,$cnum,$cdom) = @_;
                   3563:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3564:     $uploadpath =~ s{^\/}{};
                   3565:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3566:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3567:         return 1;
                   3568:     }
                   3569:     return;
                   3570: }
                   3571: 
                   3572: sub in_course {
                   3573:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3574:     if ($hideprivileged) {
                   3575:         my $skipuser;
1.1172.2.23  raeburn  3576:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3577:         my @possdoms = ($cdom);
                   3578:         if ($coursehash{'checkforpriv'}) {
                   3579:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3580:         }
                   3581:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3582:             $skipuser = 1;
                   3583:             if ($coursehash{'nothideprivileged'}) {
                   3584:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3585:                     my $user;
                   3586:                     if ($item =~ /:/) {
                   3587:                         $user = $item;
                   3588:                     } else {
                   3589:                         $user = join(':',split(/[\@]/,$item));
                   3590:                     }
                   3591:                     if ($user eq $uname.':'.$udom) {
                   3592:                         undef($skipuser);
                   3593:                         last;
                   3594:                     }
                   3595:                 }
                   3596:             }
                   3597:             if ($skipuser) {
                   3598:                 return 0;
                   3599:             }
                   3600:         }
                   3601:     }
                   3602:     $type ||= 'any';
                   3603:     if (!defined($cdom) || !defined($cnum)) {
                   3604:         my $cid  = $env{'request.course.id'};
                   3605:         $cdom = $env{'course.'.$cid.'.domain'};
                   3606:         $cnum = $env{'course.'.$cid.'.num'};
                   3607:     }
                   3608:     my $typesref;
                   3609:     if (($type eq 'any') || ($type eq 'all')) {
                   3610:         $typesref = ['active','previous','future'];
                   3611:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3612:         $typesref = [$type];
                   3613:     }
                   3614:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3615:                               $typesref,undef,[$cdom]);
                   3616:     my ($tmp) = keys(%roles);
                   3617:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3618:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3619:     if (@course_roles > 0) {
                   3620:         return 1;
                   3621:     }
                   3622:     return 0;
                   3623: }
                   3624: 
1.478     albertel 3625: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3626: # input: action, courseID, current domain, intended
1.637     raeburn  3627: #        path to file, source of file, instruction to parse file for objects,
                   3628: #        ref to hash for embedded objects,
                   3629: #        ref to hash for codebase of java objects.
1.1095    raeburn  3630: #        reference to scalar to accommodate mime type determined
                   3631: #          from File::MMagic if $parser = parse.
1.637     raeburn  3632: #
1.485     raeburn  3633: # output: url to file (if action was uploaddoc), 
                   3634: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3635: #
1.478     albertel 3636: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3637: # course.
1.477     raeburn  3638: #
1.478     albertel 3639: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3640: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3641: #          course's home server.
1.477     raeburn  3642: #
1.478     albertel 3643: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3644: #          be copied from $source (current location) to 
                   3645: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3646: #         and will then be copied to
                   3647: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3648: #         course's home server.
1.485     raeburn  3649: #
1.481     raeburn  3650: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3651: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3652: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3653: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3654: #         in course's home server.
1.637     raeburn  3655: #
1.477     raeburn  3656: 
                   3657: sub process_coursefile {
1.1095    raeburn  3658:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3659:         $mimetype)=@_;
1.477     raeburn  3660:     my $fetchresult;
1.638     albertel 3661:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3662:     if ($action eq 'propagate') {
1.638     albertel 3663:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3664: 			     $home);
1.481     raeburn  3665:     } else {
1.477     raeburn  3666:         my $fpath = '';
                   3667:         my $fname = $file;
1.478     albertel 3668:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3669:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3670:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3671:         if ($action eq 'copy') {
                   3672:             if ($source eq '') {
                   3673:                 $fetchresult = 'no source file';
                   3674:                 return $fetchresult;
                   3675:             } else {
                   3676:                 my $destination = $filepath.'/'.$fname;
                   3677:                 rename($source,$destination);
                   3678:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3679:                                  $home);
1.481     raeburn  3680:             }
                   3681:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3682:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3683:             print $fh $env{'form.'.$source};
1.481     raeburn  3684:             close($fh);
1.637     raeburn  3685:             if ($parser eq 'parse') {
1.1024    raeburn  3686:                 my $mm = new File::MMagic;
1.1095    raeburn  3687:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3688:                 if ($type eq 'text/html') {
1.1024    raeburn  3689:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3690:                     unless ($parse_result eq 'ok') {
                   3691:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3692:                     }
1.637     raeburn  3693:                 }
1.1095    raeburn  3694:                 if (ref($mimetype)) {
                   3695:                     $$mimetype = $type;
                   3696:                 } 
1.637     raeburn  3697:             }
1.477     raeburn  3698:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3699:                                  $home);
1.481     raeburn  3700:             if ($fetchresult eq 'ok') {
                   3701:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3702:             } else {
                   3703:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3704:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3705:                 return '/adm/notfound.html';
                   3706:             }
1.477     raeburn  3707:         }
                   3708:     }
1.485     raeburn  3709:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3710:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3711:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3712:     }
                   3713:     return $fetchresult;
                   3714: }
                   3715: 
1.637     raeburn  3716: sub build_filepath {
                   3717:     my ($fpath) = @_;
                   3718:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3719:     unless ($fpath eq '') {
                   3720:         my @parts=split('/',$fpath);
                   3721:         foreach my $part (@parts) {
                   3722:             $filepath.= '/'.$part;
                   3723:             if ((-e $filepath)!=1) {
                   3724:                 mkdir($filepath,0777);
                   3725:             }
                   3726:         }
                   3727:     }
                   3728:     return $filepath;
                   3729: }
                   3730: 
                   3731: sub store_edited_file {
1.638     albertel 3732:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3733:     my $file = $primary_url;
                   3734:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3735:     my $fpath = '';
                   3736:     my $fname = $file;
                   3737:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3738:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3739:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3740:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3741:     print $fh $content;
                   3742:     close($fh);
1.638     albertel 3743:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3744:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3745: 			  $home);
1.637     raeburn  3746:     if ($$fetchresult eq 'ok') {
                   3747:         return '/uploaded/'.$fpath.'/'.$fname;
                   3748:     } else {
1.638     albertel 3749:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3750: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3751:         return '/adm/notfound.html';
                   3752:     }
                   3753: }
                   3754: 
1.531     albertel 3755: sub clean_filename {
1.831     albertel 3756:     my ($fname,$args)=@_;
1.315     www      3757: # Replace Windows backslashes by forward slashes
1.257     www      3758:     $fname=~s/\\/\//g;
1.831     albertel 3759:     if (!$args->{'keep_path'}) {
                   3760:         # Get rid of everything but the actual filename
                   3761: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3762:     }
1.315     www      3763: # Replace spaces by underscores
                   3764:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3765: # Transliterate non-ascii text to ascii
                   3766:     my $lang = &Apache::lonlocal::current_language();
                   3767:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3768: # Replace all other weird characters by nothing
1.831     albertel 3769:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3770: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3771: # numbers
                   3772:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3773: # Replace three or more adjacent underscores with one for consistency
                   3774: # with loncfile::filename_check() so complete url can be extracted by
                   3775: # lonnet::decode_symb()
                   3776:     $fname=~s/_{3,}/_/g;
1.531     albertel 3777:     return $fname;
                   3778: }
1.1172.2.110  raeburn  3779: 
1.1051    raeburn  3780: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3781: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3782: # image with the same aspect ratio as the original, but with dimensions which do 
                   3783: # not exceed $resizewidth and $resizeheight.
                   3784:  
1.984     neumanie 3785: sub resizeImage {
1.1051    raeburn  3786:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3787:     my $ima = Image::Magick->new;
                   3788:     my $resized;
                   3789:     if (-e $img_path) {
                   3790:         $ima->Read($img_path);
                   3791:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3792:             my $width = $ima->Get('width');
                   3793:             my $height = $ima->Get('height');
                   3794:             if ($width > $resizewidth) {
                   3795: 	        my $factor = $width/$resizewidth;
                   3796:                 my $newheight = $height/$factor;
                   3797:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3798:                 $resized = 1;
                   3799:             }
                   3800:         }
                   3801:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3802:             my $width = $ima->Get('width');
                   3803:             my $height = $ima->Get('height');
                   3804:             if ($height > $resizeheight) {
                   3805:                 my $factor = $height/$resizeheight;
                   3806:                 my $newwidth = $width/$factor;
                   3807:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3808:                 $resized = 1;
                   3809:             }
                   3810:         }
                   3811:         if ($resized) {
                   3812:             $ima->Write($img_path);
                   3813:         }
                   3814:     }
                   3815:     return;
1.977     amueller 3816: }
                   3817: 
1.608     albertel 3818: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3819: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3820: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3821: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3822: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3823: #                   if 'coursedoc': upload to the current course
                   3824: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3825: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3826: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3827: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3828: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3829: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3830: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3831: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3832: #        $allfiles - reference to hash for embedded objects
                   3833: #        $codebase - reference to hash for codebase of java objects
                   3834: #        $desuname - username for permanent storage of uploaded file
                   3835: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3836: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3837: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3838: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3839: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3840: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3841: #                    from File::MMagic.
1.858     raeburn  3842: # 
1.686     albertel 3843: # output: url of file in userspace, or error: <message> 
                   3844: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3845: 
1.531     albertel 3846: sub userfileupload {
1.1090    raeburn  3847:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3848:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3849:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3850:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3851:     $fname=&clean_filename($fname);
1.1090    raeburn  3852:     # See if there is anything left
1.257     www      3853:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3854:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3855:     if ($fname =~ /^\./) {
                   3856:         my ($s,$usec) = &gettimeofday();
                   3857:         while (length($usec) < 6) {
                   3858:             $usec = '0'.$usec;
                   3859:         }
                   3860:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3861:     }
1.1090    raeburn  3862:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3863:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3864:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3865:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3866:         my $now = time;
1.1090    raeburn  3867:         my $filepath;
1.1095    raeburn  3868:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3869:              $filepath = 'tmp/helprequests/'.$now;
                   3870:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3871:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3872:                          '_'.$env{'user.domain'}.'/pending';
                   3873:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3874:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3875:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3876:                 $docudom = $destudom;
                   3877:             } else {
                   3878:                 $docudom = $env{'user.domain'};
                   3879:             }
1.1172.2.96  raeburn  3880:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3881:                 $docuname = $destuname;
                   3882:             } else {
                   3883:                 $docuname = $env{'user.name'};
                   3884:             }
                   3885:             if (exists($env{'form.group'})) {
                   3886:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3887:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3888:             }
                   3889:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3890:             if ($context eq 'canceloverwrite') {
                   3891:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3892:                 if (-e  $tempfile) {
                   3893:                     my @info = stat($tempfile);
                   3894:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3895:                         unlink($tempfile);
                   3896:                     }
                   3897:                 }
                   3898:                 return;
1.523     raeburn  3899:             }
                   3900:         }
1.1090    raeburn  3901:         # Create the directory if not present
1.741     raeburn  3902:         my @parts=split(/\//,$filepath);
                   3903:         my $fullpath = $perlvar{'lonDaemons'};
                   3904:         for (my $i=0;$i<@parts;$i++) {
                   3905:             $fullpath .= '/'.$parts[$i];
                   3906:             if ((-e $fullpath)!=1) {
                   3907:                 mkdir($fullpath,0777);
                   3908:             }
                   3909:         }
1.1172.2.96  raeburn  3910:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3911:         print $fh $env{'form.'.$formname};
                   3912:         close($fh);
1.1090    raeburn  3913:         if ($context eq 'existingfile') {
                   3914:             my @info = stat($fullpath.'/'.$fname);
                   3915:             return ($fullpath.'/'.$fname,$info[9]);
                   3916:         } else {
                   3917:             return $fullpath.'/'.$fname;
                   3918:         }
1.523     raeburn  3919:     }
1.995     raeburn  3920:     if ($subdir eq 'scantron') {
                   3921:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3922:     } else {
1.995     raeburn  3923:         $fname="$subdir/$fname";
                   3924:     }
1.1090    raeburn  3925:     if ($context eq 'coursedoc') {
1.638     albertel 3926: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3927: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3928:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3929:             return &finishuserfileupload($docuname,$docudom,
                   3930: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3931: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3932:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3933:         } else {
1.1172.2.21  raeburn  3934:             if ($env{'form.folder'}) {
                   3935:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3936:             }
1.638     albertel 3937:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3938: 				       $fname,$formname,$parser,
1.1095    raeburn  3939: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3940:         }
1.719     banghart 3941:     } elsif (defined($destuname)) {
                   3942:         my $docuname=$destuname;
                   3943:         my $docudom=$destudom;
1.860     raeburn  3944: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3945: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3946:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3947:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3948:     } else {
1.638     albertel 3949:         my $docuname=$env{'user.name'};
                   3950:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3951:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3952:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3953:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3954:         }
1.860     raeburn  3955: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3956: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3957:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3958:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3959:     }
1.271     www      3960: }
                   3961: 
                   3962: sub finishuserfileupload {
1.860     raeburn  3963:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3964:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3965:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3966:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3967:   
1.860     raeburn  3968:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3969:     $file=$fname;
                   3970:     if ($fname=~m|/|) {
                   3971:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3972: 	$path.=$fnamepath.'/';
                   3973:     }
1.259     www      3974:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3975:     my $count;
                   3976:     for ($count=4;$count<=$#parts;$count++) {
                   3977:         $filepath.="/$parts[$count]";
                   3978:         if ((-e $filepath)!=1) {
                   3979: 	    mkdir($filepath,0777);
                   3980:         }
                   3981:     }
1.984     neumanie 3982: 
1.258     www      3983: # Save the file
                   3984:     {
1.1172.2.96  raeburn  3985: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3986: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3987: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3988: 	    return '/adm/notfound.html';
                   3989: 	}
1.1090    raeburn  3990:         if ($context eq 'overwrite') {
1.1117    foxr     3991:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3992:             my $target = $filepath.'/'.$file;
                   3993:             if (-e $source) {
                   3994:                 my @info = stat($source);
                   3995:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3996:                     unless (&File::Copy::move($source,$target)) {
                   3997:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3998:                         return "Moving from $source failed";
                   3999:                     }
                   4000:                 } else {
                   4001:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4002:                 }
                   4003:             } else {
                   4004:                 return "Temporary file: $source missing";
                   4005:             }
                   4006:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4007: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4008: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4009: 	    return '/adm/notfound.html';
                   4010: 	}
1.570     albertel 4011: 	close(FH);
1.1051    raeburn  4012:         if ($resizewidth && $resizeheight) {
                   4013:             my $mm = new File::MMagic;
                   4014:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4015:             if ($mime_type =~ m{^image/}) {
                   4016: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4017:             }  
1.977     amueller 4018: 	}
1.258     www      4019:     }
1.1152    raeburn  4020:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4021:         if (ref($mimetype)) {
                   4022:             if ($$mimetype eq '') {
                   4023:                 my $mm = new File::MMagic;
                   4024:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4025:                 $$mimetype = $type;
                   4026:             }
                   4027:         }
                   4028:     }
1.1172.2.109  raeburn  4029:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4030:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4031:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4032:                                                        $allfiles,$codebase);
                   4033:             unless ($parse_result eq 'ok') {
                   4034:                 &logthis('Failed to parse '.$filepath.$file.
                   4035: 	   	         ' for embedded media: '.$parse_result); 
                   4036:             }
1.637     raeburn  4037:         }
1.1172.2.109  raeburn  4038:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4039:         my $format = $env{'form.scantron_format'};
                   4040:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4041:     }
1.860     raeburn  4042:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4043:         my $input = $filepath.'/'.$file;
                   4044:         my $output = $filepath.'/'.'tn-'.$file;
                   4045:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4046:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4047:         system({$args[0]} @args);
1.860     raeburn  4048:         if (-e $filepath.'/'.'tn-'.$file) {
                   4049:             $fetchthumb  = 1; 
                   4050:         }
                   4051:     }
1.858     raeburn  4052:  
1.259     www      4053: # Notify homeserver to grep it
                   4054: #
1.984     neumanie 4055:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4056:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4057:     if ($fetchresult eq 'ok') {
1.860     raeburn  4058:         if ($fetchthumb) {
                   4059:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4060:             if ($thumbresult ne 'ok') {
                   4061:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4062:                          $docuhome.': '.$thumbresult);
                   4063:             }
                   4064:         }
1.259     www      4065: #
1.258     www      4066: # Return the URL to it
1.494     albertel 4067:         return '/uploaded/'.$path.$file;
1.263     www      4068:     } else {
1.494     albertel 4069:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4070: 		 ': '.$fetchresult);
1.263     www      4071:         return '/adm/notfound.html';
1.858     raeburn  4072:     }
1.493     albertel 4073: }
                   4074: 
1.637     raeburn  4075: sub extract_embedded_items {
1.961     raeburn  4076:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4077:     my @state = ();
1.1164    raeburn  4078:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4079:     my %javafiles = (
                   4080:                       codebase => '',
                   4081:                       code => '',
                   4082:                       archive => ''
                   4083:                     );
                   4084:     my %mediafiles = (
                   4085:                       src => '',
                   4086:                       movie => '',
                   4087:                      );
1.648     raeburn  4088:     my $p;
                   4089:     if ($content) {
                   4090:         $p = HTML::LCParser->new($content);
                   4091:     } else {
1.961     raeburn  4092:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4093:     }
1.641     albertel 4094:     while (my $t=$p->get_token()) {
1.640     albertel 4095: 	if ($t->[0] eq 'S') {
                   4096: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4097: 	    push(@state, $tagname);
1.648     raeburn  4098:             if (lc($tagname) eq 'allow') {
                   4099:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4100:             }
1.640     albertel 4101: 	    if (lc($tagname) eq 'img') {
                   4102: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4103: 	    }
1.886     albertel 4104: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4105:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4106: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4107:                 }
1.886     albertel 4108: 	    }
1.645     raeburn  4109:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4110:                 my $src;
1.645     raeburn  4111:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4112:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4113:                 } else {
1.1164    raeburn  4114:                     if ($attr->{'src'} ne '') {
                   4115:                         $src = $attr->{'src'};
                   4116:                         &add_filetype($allfiles,$src,'src');
                   4117:                     }
                   4118:                 }
                   4119:                 my $text = $p->get_trimmed_text();
                   4120:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4121:                     my @swfargs = split(/,/,$1);
                   4122:                     foreach my $item (@swfargs) {
                   4123:                         $item =~ s/["']//g;
                   4124:                         $item =~ s/^\s+//;
                   4125:                         $item =~ s/\s+$//;
                   4126:                     }
                   4127:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4128:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4129:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4130:                         } else {
                   4131:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4132:                         }
                   4133:                     }
1.645     raeburn  4134:                 }
                   4135:             }
                   4136:             if (lc($tagname) eq 'link') {
                   4137:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4138:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4139:                 }
                   4140:             }
1.640     albertel 4141: 	    if (lc($tagname) eq 'object' ||
                   4142: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4143: 		foreach my $item (keys(%javafiles)) {
                   4144: 		    $javafiles{$item} = '';
                   4145: 		}
1.1164    raeburn  4146:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4147:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4148:                 }
1.640     albertel 4149: 	    }
                   4150: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4151: 		my $name = lc($attr->{'name'});
                   4152: 		foreach my $item (keys(%javafiles)) {
                   4153: 		    if ($name eq $item) {
                   4154: 			$javafiles{$item} = $attr->{'value'};
                   4155: 			last;
                   4156: 		    }
                   4157: 		}
1.1164    raeburn  4158:                 my $pathfrom;
1.640     albertel 4159: 		foreach my $item (keys(%mediafiles)) {
                   4160: 		    if ($name eq $item) {
1.1164    raeburn  4161:                         $pathfrom = $attr->{'value'};
                   4162:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4163: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4164: 			last;
                   4165: 		    }
                   4166: 		}
1.1164    raeburn  4167:                 if ($name eq 'flashvars') {
                   4168:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4169:                 }
                   4170:                 if ($pathfrom ne '') {
                   4171:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4172:                                          $pathfrom);
                   4173:                 }
1.640     albertel 4174: 	    }
                   4175: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4176: 		foreach my $item (keys(%javafiles)) {
                   4177: 		    if ($attr->{$item}) {
                   4178: 			$javafiles{$item} = $attr->{$item};
                   4179: 			last;
                   4180: 		    }
                   4181: 		}
                   4182: 		foreach my $item (keys(%mediafiles)) {
                   4183: 		    if ($attr->{$item}) {
                   4184: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4185: 			last;
                   4186: 		    }
                   4187: 		}
1.1164    raeburn  4188:                 if (lc($tagname) eq 'embed') {
                   4189:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4190:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4191:                                              $attr->{'src'});
                   4192:                     }
                   4193:                 }
1.640     albertel 4194: 	    }
1.1172.2.35  raeburn  4195:             if (lc($tagname) eq 'iframe') {
                   4196:                 my $src = $attr->{'src'} ;
                   4197:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4198:                     &add_filetype($allfiles,$src,'src');
                   4199:                 } elsif ($src =~ m{^/}) {
                   4200:                     if ($env{'request.course.id'}) {
                   4201:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4202:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4203:                         my $url = &hreflocation('',$fullpath);
                   4204:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4205:                             my $relpath = $1;
                   4206:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4207:                                 &add_filetype($allfiles,$1,'src');
                   4208:                             }
                   4209:                         }
                   4210:                     }
                   4211:                 }
                   4212:             }
1.1164    raeburn  4213:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4214:                 pop(@state);
1.1164    raeburn  4215:             }
1.640     albertel 4216: 	} elsif ($t->[0] eq 'E') {
                   4217: 	    my ($tagname) = ($t->[1]);
                   4218: 	    if ($javafiles{'codebase'} ne '') {
                   4219: 		$javafiles{'codebase'} .= '/';
                   4220: 	    }  
                   4221: 	    if (lc($tagname) eq 'applet' ||
                   4222: 		lc($tagname) eq 'object' ||
                   4223: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4224: 		) {
                   4225: 		foreach my $item (keys(%javafiles)) {
                   4226: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4227: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4228: 			&add_filetype($allfiles,$file,$item);
                   4229: 		    }
                   4230: 		}
                   4231: 	    } 
                   4232: 	    pop @state;
                   4233: 	}
                   4234:     }
1.1164    raeburn  4235:     foreach my $id (sort(keys(%flashvars))) {
                   4236:         if ($shockwave{$id} ne '') {
                   4237:             my @pairs = split(/\&/,$flashvars{$id});
                   4238:             foreach my $pair (@pairs) {
                   4239:                 my ($key,$value) = split(/\=/,$pair);
                   4240:                 if ($key eq 'thumb') {
                   4241:                     &add_filetype($allfiles,$value,$key);
                   4242:                 } elsif ($key eq 'content') {
                   4243:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4244:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4245:                     if ($ext ne '') {
                   4246:                         &add_filetype($allfiles,$path.$value,$ext);
                   4247:                     }
                   4248:                 }
                   4249:             }
                   4250:         }
                   4251:     }
1.637     raeburn  4252:     return 'ok';
                   4253: }
                   4254: 
1.639     albertel 4255: sub add_filetype {
                   4256:     my ($allfiles,$file,$type)=@_;
                   4257:     if (exists($allfiles->{$file})) {
                   4258: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4259: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4260: 	}
                   4261:     } else {
                   4262: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4263:     }
                   4264: }
                   4265: 
1.1164    raeburn  4266: sub embedded_dependency {
                   4267:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4268:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4269:         if (($identifier ne '') &&
                   4270:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4271:             ($pathfrom ne '')) {
                   4272:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4273:             foreach my $dep (@{$related->{$identifier}}) {
                   4274:                 &add_filetype($allfiles,$path.$dep,'object');
                   4275:             }
                   4276:         }
                   4277:     }
                   4278:     return;
                   4279: }
                   4280: 
1.1172.2.109  raeburn  4281: sub bubblesheet_converter {
                   4282:     my ($cdom,$fullpath,$config,$format) = @_;
                   4283:     if ((&domain($cdom) ne '') &&
                   4284:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4285:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4286:         my (%csvcols,%csvoptions);
                   4287:         if (ref($config->{'fields'}) eq 'HASH') {
                   4288:             %csvcols = %{$config->{'fields'}};
                   4289:         }
                   4290:         if (ref($config->{'options'}) eq 'HASH') {
                   4291:             %csvoptions = %{$config->{'options'}};
                   4292:         }
                   4293:         my %csvbynum = reverse(%csvcols);
                   4294:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4295:         if (keys(%scantronconf)) {
                   4296:             my %bynum = (
                   4297:                           $scantronconf{CODEstart} => 'CODEstart',
                   4298:                           $scantronconf{IDstart}   => 'IDstart',
                   4299:                           $scantronconf{PaperID}   => 'PaperID',
                   4300:                           $scantronconf{FirstName} => 'FirstName',
                   4301:                           $scantronconf{LastName}  => 'LastName',
                   4302:                           $scantronconf{Qstart}    => 'Qstart',
                   4303:                         );
                   4304:             my @ordered;
                   4305:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4306:                 push(@ordered,$bynum{$item});
                   4307:             }
                   4308:             my %mapstart = (
                   4309:                               CODEstart => 'CODE',
                   4310:                               IDstart   => 'ID',
                   4311:                               PaperID   => 'PaperID',
                   4312:                               FirstName => 'FirstName',
                   4313:                               LastName  => 'LastName',
                   4314:                               Qstart    => 'FirstQuestion',
                   4315:                            );
                   4316:             my %maplength = (
                   4317:                               CODEstart => 'CODElength',
                   4318:                               IDstart   => 'IDlength',
                   4319:                               PaperID   => 'PaperIDlength',
                   4320:                               FirstName => 'FirstNamelength',
                   4321:                               LastName  => 'LastNamelength',
                   4322:             );
                   4323:             if (open(my $fh,'<',$fullpath)) {
                   4324:                 my $output;
                   4325:                 my %lettdig = &letter_to_digits();
                   4326:                 my %diglett = reverse(%lettdig);
                   4327:                 my $numletts = scalar(keys(%lettdig));
                   4328:                 my $num = 0;
                   4329:                 while (my $line=<$fh>) {
                   4330:                     $num ++;
                   4331:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4332:                     $line =~ s{[\r\n]+$}{};
                   4333:                     my %found;
1.1172.2.143  raeburn  4334:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4335:                     my ($qstart,$record);
                   4336:                     for (my $i=0; $i<@values; $i++) {
                   4337:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4338:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4339:                             if ($values[$i] eq '') {
                   4340:                                 $values[$i] = $scantronconf{'Qoff'};
                   4341:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4342:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4343:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4344:                                 }
                   4345:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4346:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4347:                                     $values[$i] = $diglett{$values[$i]};
                   4348:                                 }
                   4349:                             } else {
                   4350:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4351:                                     my $digit;
                   4352:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4353:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4354:                                         if ($values[$i] eq 'J') {
                   4355:                                             $digit += $numletts;
                   4356:                                         }
                   4357:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4358:                                         $digit = $values[$i]-1;
                   4359:                                         if ($values[$i] eq '0') {
                   4360:                                             $digit += $numletts;
                   4361:                                         }
                   4362:                                     }
                   4363:                                     my $qval='';
                   4364:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4365:                                         if ($j == $digit) {
                   4366:                                             $qval .= $scantronconf{'Qon'};
                   4367:                                         } else {
                   4368:                                             $qval .= $scantronconf{'Qoff'};
                   4369:                                         }
                   4370:                                     }
                   4371:                                     $values[$i] = $qval;
                   4372:                                 }
                   4373:                             }
                   4374:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4375:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4376:                             }
                   4377:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4378:                             if ($numblank > 0) {
                   4379:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4380:                             }
                   4381:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4382:                                 $qstart = $i;
                   4383:                                 $found{$csvbynum{$i}} = $values[$i];
                   4384:                             } else {
                   4385:                                 $found{'FirstQuestion'} .= $values[$i];
                   4386:                             }
                   4387:                         } elsif (exists($csvbynum{$i})) {
                   4388:                             if ($csvoptions{'rem'}) {
                   4389:                                 $values[$i] =~ s/^\s+//;
                   4390:                             }
                   4391:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4392:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4393:                                     $values[$i] = '0'.$values[$i];
                   4394:                                 }
                   4395:                             }
                   4396:                             $found{$csvbynum{$i}} = $values[$i];
                   4397:                         }
                   4398:                     }
                   4399:                     foreach my $item (@ordered) {
                   4400:                         my $currlength = 1+length($record);
                   4401:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4402:                         if ($numspaces > 0) {
                   4403:                             $record .= (' ' x $numspaces);
                   4404:                         }
                   4405:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4406:                             unless ($item eq 'Qstart') {
                   4407:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4408:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4409:                                 }
                   4410:                             }
                   4411:                             $record .= $found{$mapstart{$item}};
                   4412:                         }
                   4413:                     }
                   4414:                     $output .= "$record\n";
                   4415:                 }
                   4416:                 close($fh);
                   4417:                 if ($output) {
                   4418:                     if (open(my $fh,'>',$fullpath)) {
                   4419:                         print $fh $output;
                   4420:                         close($fh);
                   4421:                     }
                   4422:                 }
                   4423:             }
                   4424:         }
                   4425:         return;
                   4426:     }
                   4427: }
                   4428: 
                   4429: sub letter_to_digits {
                   4430:     my %lettdig = (
                   4431:                     A => 1,
                   4432:                     B => 2,
                   4433:                     C => 3,
                   4434:                     D => 4,
                   4435:                     E => 5,
                   4436:                     F => 6,
                   4437:                     G => 7,
                   4438:                     H => 8,
                   4439:                     I => 9,
                   4440:                     J => 0,
                   4441:                   );
                   4442:     return %lettdig;
                   4443: }
                   4444: 
                   4445: sub get_scantron_config {
                   4446:     my ($which,$cdom) = @_;
                   4447:     my @lines = &get_scantronformat_file($cdom);
                   4448:     my %config;
                   4449:     #FIXME probably should move to XML it has already gotten a bit much now
                   4450:     foreach my $line (@lines) {
                   4451:         my ($name,$descrip)=split(/:/,$line);
                   4452:         if ($name ne $which ) { next; }
                   4453:         chomp($line);
                   4454:         my @config=split(/:/,$line);
                   4455:         $config{'name'}=$config[0];
                   4456:         $config{'description'}=$config[1];
                   4457:         $config{'CODElocation'}=$config[2];
                   4458:         $config{'CODEstart'}=$config[3];
                   4459:         $config{'CODElength'}=$config[4];
                   4460:         $config{'IDstart'}=$config[5];
                   4461:         $config{'IDlength'}=$config[6];
                   4462:         $config{'Qstart'}=$config[7];
                   4463:         $config{'Qlength'}=$config[8];
                   4464:         $config{'Qoff'}=$config[9];
                   4465:         $config{'Qon'}=$config[10];
                   4466:         $config{'PaperID'}=$config[11];
                   4467:         $config{'PaperIDlength'}=$config[12];
                   4468:         $config{'FirstName'}=$config[13];
                   4469:         $config{'FirstNamelength'}=$config[14];
                   4470:         $config{'LastName'}=$config[15];
                   4471:         $config{'LastNamelength'}=$config[16];
                   4472:         $config{'BubblesPerRow'}=$config[17];
                   4473:         last;
                   4474:     }
                   4475:     return %config;
                   4476: }
                   4477: 
                   4478: sub get_scantronformat_file {
                   4479:     my ($cdom) = @_;
                   4480:     if ($cdom eq '') {
                   4481:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4482:     }
                   4483:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4484:     my $gottab = 0;
                   4485:     my @lines;
                   4486:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4487:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4488:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4489:             if ($formatfile ne '-1') {
                   4490:                 @lines = split("\n",$formatfile,-1);
                   4491:                 $gottab = 1;
                   4492:             }
                   4493:         }
                   4494:     }
                   4495:     if (!$gottab) {
                   4496:         my $confname = $cdom.'-domainconfig';
                   4497:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4498:         my $formatfile = &getfile($default);
                   4499:         if ($formatfile ne '-1') {
                   4500:             @lines = split("\n",$formatfile,-1);
                   4501:             $gottab = 1;
                   4502:         }
                   4503:     }
                   4504:     if (!$gottab) {
                   4505:         my @domains = &current_machine_domains();
                   4506:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4507:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4508:                 @lines = <$fh>;
                   4509:                 close($fh);
                   4510:             }
                   4511:         } else {
                   4512:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4513:                 @lines = <$fh>;
                   4514:                 close($fh);
                   4515:             }
                   4516:         }
                   4517:     }
                   4518:     return @lines;
                   4519: }
                   4520: 
1.493     albertel 4521: sub removeuploadedurl {
1.984     neumanie 4522:     my ($url)=@_;	
                   4523:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4524:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4525: }
                   4526: 
                   4527: sub removeuserfile {
                   4528:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4529:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4530:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4531:     if ($result eq 'ok') {	
1.798     raeburn  4532:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4533:             my $metafile = $fname.'.meta';
                   4534:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4535: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4536:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4537:             my $sqlresult = 
1.823     albertel 4538:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4539:                                         'portfolio_metadata',$group,
                   4540:                                         'delete');
1.798     raeburn  4541:         }
                   4542:     }
                   4543:     return $result;
1.257     www      4544: }
1.15      www      4545: 
1.530     albertel 4546: sub mkdiruserfile {
                   4547:     my ($docuname,$docudom,$dir)=@_;
                   4548:     my $home=&homeserver($docuname,$docudom);
                   4549:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4550: }
                   4551: 
1.531     albertel 4552: sub renameuserfile {
                   4553:     my ($docuname,$docudom,$old,$new)=@_;
                   4554:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4555:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4556:                         &escape("$old").':'.&escape("$new"),$home);
                   4557:     if ($result eq 'ok') {
                   4558:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4559:             my $oldmeta = $old.'.meta';
                   4560:             my $newmeta = $new.'.meta';
                   4561:             my $metaresult = 
                   4562:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4563: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4564:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4565:             my $sqlresult = 
1.823     albertel 4566:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4567:                                         'portfolio_metadata',$group,
                   4568:                                         'delete');
1.798     raeburn  4569:         }
                   4570:     }
                   4571:     return $result;
1.531     albertel 4572: }
                   4573: 
1.14      www      4574: # ------------------------------------------------------------------------- Log
                   4575: 
                   4576: sub log {
                   4577:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4578:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4579: }
                   4580: 
                   4581: # ------------------------------------------------------------------ Course Log
1.352     www      4582: #
                   4583: # This routine flushes several buffers of non-mission-critical nature
                   4584: #
1.157     www      4585: 
                   4586: sub flushcourselogs {
1.352     www      4587:     &logthis('Flushing log buffers');
                   4588: #
                   4589: # course logs
                   4590: # This is a log of all transactions in a course, which can be used
                   4591: # for data mining purposes
                   4592: #
                   4593: # It also collects the courseid database, which lists last transaction
                   4594: # times and course titles for all courseids
                   4595: #
                   4596:     my %courseidbuffer=();
1.921     raeburn  4597:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4598:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4599: 		          &escape($courselogs{$crsid}),
                   4600: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4601: 	    delete $courselogs{$crsid};
                   4602:         } else {
                   4603:             &logthis('Failed to flush log buffer for '.$crsid);
                   4604:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4605:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4606:                         " exceeded maximum size, deleting.</font>");
                   4607:                delete $courselogs{$crsid};
                   4608:             }
1.352     www      4609:         }
1.920     raeburn  4610:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4611:             'description' => $coursedescrbuf{$crsid},
                   4612:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4613:             'type'        => $coursetypebuf{$crsid},
                   4614:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4615:         };
1.191     harris41 4616:     }
1.352     www      4617: #
                   4618: # Write course id database (reverse lookup) to homeserver of courses 
                   4619: # Is used in pickcourse
                   4620: #
1.840     albertel 4621:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4622:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4623:                                     $courseidbuffer{$crs_home},
                   4624:                                     $crs_home,'timeonly');
1.352     www      4625:     }
                   4626: #
                   4627: # File accesses
                   4628: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4629: #
1.449     matthew  4630:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4631:         if ($entry =~ /___count$/) {
                   4632:             my ($dom,$name);
1.807     albertel 4633:             ($dom,$name,undef)=
1.811     albertel 4634: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4635:             if (! defined($dom) || $dom eq '' || 
                   4636:                 ! defined($name) || $name eq '') {
1.620     albertel 4637:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4638: #
                   4639: # FIXME 11/29/2021
                   4640: # Typo in rev. 1.458 (2003/12/09)??
                   4641: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4642: #
                   4643: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4644: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4645: # in a nohist_accesscount.db file for the user rather than the course.
                   4646: #
                   4647: # That said there is a lot of noise in the data being stored.
                   4648: # So counts for prtspool/  and adm/ etc. are recorded.
                   4649: #
                   4650: # A review of which items ending '___count' are written to %accesshash should likely be
                   4651: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4652: #
                   4653: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4654: # accesses for things which are not published resources, regardless of course, and
                   4655: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4656: # anyone in the course for things which are not published resources.
                   4657: #
                   4658: # For an author, nohist_accesscount.db ends up having records for other items
                   4659: # mixed up with the legitimate access counts for the author's published resources.
                   4660: #
1.620     albertel 4661:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4662:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4663:             }
1.450     matthew  4664:             my $value = $accesshash{$entry};
                   4665:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4666:             my %temphash=($url => $value);
1.449     matthew  4667:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4668:             if ($result eq 'ok') {
                   4669:                 delete $accesshash{$entry};
                   4670:             }
                   4671:         } else {
1.811     albertel 4672:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4673:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4674:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4675:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4676:                 delete $accesshash{$entry};
                   4677:             }
1.185     www      4678:         }
1.191     harris41 4679:     }
1.352     www      4680: #
                   4681: # Roles
                   4682: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4683: #
1.800     albertel 4684:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4685:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4686: 	    split(/\:/,$entry);
                   4687:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4688:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4689:                 $rudom,$runame) eq 'ok') {
                   4690: 	    delete $userrolehash{$entry};
                   4691:         }
                   4692:     }
1.662     raeburn  4693: #
1.1172.2.90  raeburn  4694: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4695: #
                   4696:     my %domrolebuffer = ();
1.1000    raeburn  4697:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4698:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4699:         if ($domrolebuffer{$rudom}) {
                   4700:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4701:                       '='.&escape($domainrolehash{$entry});
                   4702:         } else {
                   4703:             $domrolebuffer{$rudom}.=&escape($entry).
                   4704:                       '='.&escape($domainrolehash{$entry});
                   4705:         }
                   4706:         delete $domainrolehash{$entry};
                   4707:     }
                   4708:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4709:         my %servers;
                   4710:         if (defined(&domain($dom,'primary'))) {
                   4711:             my $primary=&domain($dom,'primary');
                   4712:             my $hostname=&hostname($primary);
                   4713:             $servers{$primary} = $hostname;
                   4714:         } else {
                   4715:             %servers = &get_servers($dom,'library');
                   4716:         }
1.841     albertel 4717: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4718: 	    if (&reply('domroleput:'.$dom.':'.
                   4719: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4720: 	        last;
                   4721: 	    } else {
1.841     albertel 4722: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4723: 	    }
1.662     raeburn  4724:         }
                   4725:     }
1.186     www      4726:     $dumpcount++;
1.157     www      4727: }
                   4728: 
                   4729: sub courselog {
                   4730:     my $what=shift;
1.158     www      4731:     $what=time.':'.$what;
1.620     albertel 4732:     unless ($env{'request.course.id'}) { return ''; }
                   4733:     $coursedombuf{$env{'request.course.id'}}=
                   4734:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4735:     $coursenumbuf{$env{'request.course.id'}}=
                   4736:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4737:     $coursehombuf{$env{'request.course.id'}}=
                   4738:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4739:     $coursedescrbuf{$env{'request.course.id'}}=
                   4740:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4741:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4742:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4743:     $courseownerbuf{$env{'request.course.id'}}=
                   4744:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4745:     $coursetypebuf{$env{'request.course.id'}}=
                   4746:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4747:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4748: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4749:     } else {
1.620     albertel 4750: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4751:     }
1.620     albertel 4752:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4753: 	&flushcourselogs();
                   4754:     }
1.158     www      4755: }
                   4756: 
                   4757: sub courseacclog {
                   4758:     my $fnsymb=shift;
1.620     albertel 4759:     unless ($env{'request.course.id'}) { return ''; }
                   4760:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4761:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4762:         $what.=':POST';
1.583     matthew  4763:         # FIXME: Probably ought to escape things....
1.800     albertel 4764: 	foreach my $key (keys(%env)) {
                   4765:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4766:                 my $formitem = $1;
                   4767:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4768:                     $what.=':'.$formitem.'='.$env{$key};
                   4769:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4770:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4771:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4772:                     } else {
                   4773:                         $what.=':'.$formitem.'='.$env{$key};
                   4774:                     }
1.975     raeburn  4775:                 }
1.158     www      4776:             }
1.191     harris41 4777:         }
1.583     matthew  4778:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4779:         # FIXME: We should not be depending on a form parameter that someone
                   4780:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4781:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4782:             $what.= ':POST';
                   4783:             # FIXME: Probably ought to escape things....
                   4784:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4785:                                  'crsdiscuss') {
1.620     albertel 4786:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4787:             }
                   4788:         }
1.158     www      4789:     }
                   4790:     &courselog($what);
1.149     www      4791: }
                   4792: 
1.185     www      4793: sub countacc {
                   4794:     my $url=&declutter(shift);
1.458     matthew  4795:     return if (! defined($url) || $url eq '');
1.620     albertel 4796:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4797: #
                   4798: # Mark that this url was used in this course
                   4799: #
1.620     albertel 4800:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4801: #
                   4802: # Increase the access count for this resource in this child process
                   4803: #
1.281     www      4804:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4805:     $accesshash{$key}++;
1.185     www      4806: }
1.349     www      4807: 
1.361     www      4808: sub linklog {
                   4809:     my ($from,$to)=@_;
                   4810:     $from=&declutter($from);
                   4811:     $to=&declutter($to);
                   4812:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4813:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4814: }
1.1160    www      4815: 
                   4816: sub statslog {
                   4817:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4818:     if ($users<2) { return; }
                   4819:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4820:             'course'       => $env{'request.course.id'},
                   4821:             'sections'     => '"all"',
                   4822:             'num_students' => $users,
                   4823:             'part'         => $part,
                   4824:             'symb'         => $symb,
                   4825:             'mean_tries'   => $av_attempts,
                   4826:             'deg_of_diff'  => $degdiff});
                   4827:     foreach my $key (keys(%dynstore)) {
                   4828:         $accesshash{$key}=$dynstore{$key};
                   4829:     }
                   4830: }
1.361     www      4831:   
1.349     www      4832: sub userrolelog {
                   4833:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4834:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4835:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4836:        $userrolehash
                   4837:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4838:                     =$tend.':'.$tstart;
1.662     raeburn  4839:     }
1.1169    droeschl 4840:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4841:        $userrolehash
                   4842:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4843:                     =$tend.':'.$tstart;
                   4844:     }
1.1172.2.90  raeburn  4845:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4846:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4847:        $domainrolehash
                   4848:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4849:                     = $tend.':'.$tstart;
                   4850:     }
1.351     www      4851: }
                   4852: 
1.957     raeburn  4853: sub courserolelog {
                   4854:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4855:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4856:         my $cdom = $1;
                   4857:         my $cnum = $2;
                   4858:         my $sec = $3;
                   4859:         my $namespace = 'rolelog';
                   4860:         my %storehash = (
                   4861:                            role    => $trole,
                   4862:                            start   => $tstart,
                   4863:                            end     => $tend,
                   4864:                            selfenroll => $selfenroll,
                   4865:                            context    => $context,
                   4866:                         );
                   4867:         if ($trole eq 'gr') {
                   4868:             $namespace = 'groupslog';
                   4869:             $storehash{'group'} = $sec;
                   4870:         } else {
                   4871:             $storehash{'section'} = $sec;
                   4872:         }
                   4873:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4874:                    $domain,$cnum,$cdom);
                   4875:         if (($trole ne 'st') || ($sec ne '')) {
                   4876:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4877:         }
                   4878:     }
                   4879:     return;
                   4880: }
                   4881: 
1.1172.2.9  raeburn  4882: sub domainrolelog {
                   4883:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4884:     if ($area =~ m{^/($match_domain)/$}) {
                   4885:         my $cdom = $1;
                   4886:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4887:         my $namespace = 'rolelog';
                   4888:         my %storehash = (
                   4889:                            role    => $trole,
                   4890:                            start   => $tstart,
                   4891:                            end     => $tend,
                   4892:                            context => $context,
                   4893:                         );
                   4894:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4895:                    $domain,$domconfiguser,$cdom);
                   4896:     }
                   4897:     return;
                   4898: 
                   4899: }
                   4900: 
                   4901: sub coauthorrolelog {
                   4902:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4903:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4904:         my $audom = $1;
                   4905:         my $auname = $2;
                   4906:         my $namespace = 'rolelog';
                   4907:         my %storehash = (
                   4908:                            role    => $trole,
                   4909:                            start   => $tstart,
                   4910:                            end     => $tend,
                   4911:                            context => $context,
                   4912:                         );
                   4913:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4914:                    $domain,$auname,$audom);
                   4915:     }
                   4916:     return;
                   4917: }
                   4918: 
1.351     www      4919: sub get_course_adv_roles {
1.948     raeburn  4920:     my ($cid,$codes) = @_;
1.620     albertel 4921:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4922:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4923:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4924:     my %nothide=();
1.800     albertel 4925:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4926:         if ($user !~ /:/) {
                   4927: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4928:         } else {
                   4929:             $nothide{$user}=1;
                   4930:         }
1.470     www      4931:     }
1.1172.2.23  raeburn  4932:     my @possdoms = ($coursehash{'domain'});
                   4933:     if ($coursehash{'checkforpriv'}) {
                   4934:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4935:     }
1.351     www      4936:     my %returnhash=();
                   4937:     my %dumphash=
                   4938:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4939:     my $now=time;
1.997     raeburn  4940:     my %privileged;
1.1000    raeburn  4941:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4942: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4943:         if (($tstart) && ($tstart<0)) { next; }
                   4944:         if (($tend) && ($tend<$now)) { next; }
                   4945:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4946:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4947: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4948:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4949:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4950: 	if ($role eq 'cr') { next; }
1.948     raeburn  4951:         if ($codes) {
                   4952:             if ($section) { $role .= ':'.$section; }
                   4953:             if ($returnhash{$role}) {
                   4954:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4955:             } else {
                   4956:                 $returnhash{$role}=$username.':'.$domain;
                   4957:             }
1.351     www      4958:         } else {
1.988     raeburn  4959:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4960:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4961:             if ($returnhash{$key}) {
                   4962: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4963:             } else {
                   4964:                 $returnhash{$key}=$username.':'.$domain;
                   4965:             }
1.351     www      4966:         }
1.948     raeburn  4967:     }
1.400     www      4968:     return %returnhash;
                   4969: }
                   4970: 
                   4971: sub get_my_roles {
1.937     raeburn  4972:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4973:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4974:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4975:     my (%dumphash,%nothide);
1.1086    raeburn  4976:     if ($context eq 'userroles') {
1.1166    raeburn  4977:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4978:     } else {
1.1172.2.23  raeburn  4979:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4980:         if ($hidepriv) {
                   4981:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4982:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4983:                 if ($user !~ /:/) {
                   4984:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4985:                 } else {
                   4986:                     $nothide{$user} = 1;
                   4987:                 }
                   4988:             }
                   4989:         }
1.858     raeburn  4990:     }
1.400     www      4991:     my %returnhash=();
                   4992:     my $now=time;
1.999     raeburn  4993:     my %privileged;
1.800     albertel 4994:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4995:         my ($role,$tend,$tstart);
                   4996:         if ($context eq 'userroles') {
1.1149    raeburn  4997:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4998: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4999:         } else {
                   5000:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5001:         }
1.400     www      5002:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5003:         my $status = 'active';
1.939     raeburn  5004:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5005:             $status = 'previous';
                   5006:         } 
                   5007:         if (($tstart) && ($now<$tstart)) {
                   5008:             $status = 'future';
                   5009:         }
                   5010:         if (ref($types) eq 'ARRAY') {
                   5011:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5012:                 next;
                   5013:             } 
                   5014:         } else {
                   5015:             if ($status ne 'active') {
                   5016:                 next;
                   5017:             }
                   5018:         }
1.867     raeburn  5019:         my ($rolecode,$username,$domain,$section,$area);
                   5020:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5021:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5022:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5023:         } else {
                   5024:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5025:         }
1.832     raeburn  5026:         if (ref($roledoms) eq 'ARRAY') {
                   5027:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5028:                 next;
                   5029:             }
                   5030:         }
                   5031:         if (ref($roles) eq 'ARRAY') {
                   5032:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5033:                 if ($role =~ /^cr\//) {
                   5034:                     if (!grep(/^cr$/,@{$roles})) {
                   5035:                         next;
                   5036:                     }
1.1104    raeburn  5037:                 } elsif ($role =~ /^gr\//) {
                   5038:                     if (!grep(/^gr$/,@{$roles})) {
                   5039:                         next;
                   5040:                     }
1.922     raeburn  5041:                 } else {
                   5042:                     next;
                   5043:                 }
1.832     raeburn  5044:             }
1.867     raeburn  5045:         }
1.937     raeburn  5046:         if ($hidepriv) {
1.1172.2.23  raeburn  5047:             my @privroles = ('dc','su');
1.999     raeburn  5048:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5049:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5050:             } else {
1.1172.2.23  raeburn  5051:                 my $possdoms = [$domain];
                   5052:                 if (ref($roledoms) eq 'ARRAY') {
                   5053:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5054:                 }
1.1172.2.23  raeburn  5055:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5056:                     if (!$nothide{$username.':'.$domain}) {
                   5057:                         next;
                   5058:                     }
                   5059:                 }
1.937     raeburn  5060:             }
                   5061:         }
1.933     raeburn  5062:         if ($withsec) {
                   5063:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5064:                 $tstart.':'.$tend;
                   5065:         } else {
                   5066:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5067:         }
1.832     raeburn  5068:     }
1.373     www      5069:     return %returnhash;
1.399     www      5070: }
                   5071: 
1.1172.2.89  raeburn  5072: sub get_all_adhocroles {
                   5073:     my ($dom) = @_;
                   5074:     my @roles_by_num = ();
                   5075:     my %domdefaults = &get_domain_defaults($dom);
                   5076:     my (%description,%access_in_dom,%access_info);
                   5077:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5078:         my $count = 0;
                   5079:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5080:         my %ordered;
                   5081:         foreach my $role (sort(keys(%domcurrent))) {
                   5082:             my ($order,$desc,$access_in_dom);
                   5083:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5084:                 $order = $domcurrent{$role}{'order'};
                   5085:                 $desc = $domcurrent{$role}{'desc'};
                   5086:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5087:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5088:             }
                   5089:             if ($order eq '') {
                   5090:                 $order = $count;
                   5091:             }
                   5092:             $ordered{$order} = $role;
                   5093:             if ($desc ne '') {
                   5094:                 $description{$role} = $desc;
                   5095:             } else {
                   5096:                 $description{$role}= $role;
                   5097:             }
                   5098:             $count++;
                   5099:         }
                   5100:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5101:             push(@roles_by_num,$ordered{$item});
                   5102:         }
                   5103:     }
                   5104:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5105: }
                   5106: 
                   5107: sub get_my_adhocroles {
                   5108:     my ($cid,$checkreg) = @_;
                   5109:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5110:     if ($env{'request.course.id'} eq $cid) {
                   5111:         $cdom = $env{'course.'.$cid.'.domain'};
                   5112:         $cnum = $env{'course.'.$cid.'.num'};
                   5113:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5114:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5115:         $cdom = $1;
                   5116:         $cnum = $2;
                   5117:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5118:                                      $cdom,$cnum);
                   5119:     }
                   5120:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5121:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5122:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5123:         if ($rosterhash{$user} ne '') {
                   5124:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5125:             return ([],{}) if ($type eq 'auto');
                   5126:         }
                   5127:     }
                   5128:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5129:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5130:             my $then=$env{'user.login.time'};
                   5131:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5132:             if (!$update) {
                   5133:                 $update = $then;
                   5134:             }
                   5135:             my @liveroles;
                   5136:             foreach my $role ('dh','da') {
                   5137:                 if ($env{"user.role.$role./$cdom/"}) {
                   5138:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5139:                     my $limit = $update;
                   5140:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5141:                         $limit = $then;
                   5142:                     }
                   5143:                     my $activerole = 1;
                   5144:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5145:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5146:                     if ($activerole) {
                   5147:                         push(@liveroles,$role);
                   5148:                     }
                   5149:                 }
                   5150:             }
                   5151:             if (@liveroles) {
1.1172.2.89  raeburn  5152:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5153:                     my ($accessref,$accessinfo,%access_in_dom);
                   5154:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5155:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5156:                         if (@{$roles_by_num}) {
                   5157:                             my %settings;
                   5158:                             if ($env{'request.course.id'} eq $cid) {
                   5159:                                 foreach my $envkey (keys(%env)) {
                   5160:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5161:                                         $settings{$1} = $env{$envkey};
                   5162:                                     }
                   5163:                                 }
                   5164:                             } else {
                   5165:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5166:                             }
                   5167:                             my %setincrs;
                   5168:                             if ($settings{'internal.adhocaccess'}) {
                   5169:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5170:                             }
                   5171:                             my @statuses;
                   5172:                             if ($env{'environment.inststatus'}) {
                   5173:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5174:                             }
                   5175:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5176:                             if (ref($accessref) eq 'HASH') {
                   5177:                                 %access_in_dom = %{$accessref};
                   5178:                             }
                   5179:                             foreach my $role (@{$roles_by_num}) {
                   5180:                                 my ($curraccess,@okstatus,@personnel);
                   5181:                                 if ($setincrs{$role}) {
                   5182:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5183:                                     if ($curraccess eq 'status') {
                   5184:                                         @okstatus = split(/\&/,$rest);
                   5185:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5186:                                         @personnel = split(/\&/,$rest);
                   5187:                                     }
                   5188:                                 } else {
                   5189:                                     $curraccess = $access_in_dom{$role};
                   5190:                                     if (ref($accessinfo) eq 'HASH') {
                   5191:                                         if ($curraccess eq 'status') {
                   5192:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5193:                                                 @okstatus = @{$accessinfo->{$role}};
                   5194:                                             }
                   5195:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5196:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5197:                                                 @personnel = @{$accessinfo->{$role}};
                   5198:                                             }
                   5199:                                         }
                   5200:                                     }
                   5201:                                 }
                   5202:                                 if ($curraccess eq 'none') {
                   5203:                                     next;
                   5204:                                 } elsif ($curraccess eq 'all') {
                   5205:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5206:                                 } elsif ($curraccess eq 'dh') {
                   5207:                                     if (grep(/^dh$/,@liveroles)) {
                   5208:                                         push(@possroles,$role);
                   5209:                                     } else {
                   5210:                                         next;
                   5211:                                     }
                   5212:                                 } elsif ($curraccess eq 'da') {
                   5213:                                     if (grep(/^da$/,@liveroles)) {
                   5214:                                         push(@possroles,$role);
                   5215:                                     } else {
                   5216:                                         next;
                   5217:                                     }
1.1172.2.89  raeburn  5218:                                 } elsif ($curraccess eq 'status') {
                   5219:                                     if (@okstatus) {
                   5220:                                         if (!@statuses) {
                   5221:                                             if (grep(/^default$/,@okstatus)) {
                   5222:                                                 push(@possroles,$role);
                   5223:                                             }
                   5224:                                         } else {
                   5225:                                             foreach my $status (@okstatus) {
                   5226:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5227:                                                     push(@possroles,$role);
                   5228:                                                     last;
                   5229:                                                 }
                   5230:                                             }
                   5231:                                         }
                   5232:                                     }
                   5233:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5234:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5235:                                         if ($curraccess eq 'exc') {
                   5236:                                             push(@possroles,$role);
                   5237:                                         }
                   5238:                                     } elsif ($curraccess eq 'inc') {
                   5239:                                         push(@possroles,$role);
                   5240:                                     }
                   5241:                                 }
                   5242:                             }
                   5243:                         }
                   5244:                     }
                   5245:                 }
                   5246:             }
                   5247:         }
                   5248:     }
                   5249:     unless (ref($description) eq 'HASH') {
                   5250:         if (ref($roles_by_num) eq 'ARRAY') {
                   5251:             my %desc;
                   5252:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5253:             $description = \%desc;
                   5254:         } else {
                   5255:             $description = {};
                   5256:         }
                   5257:     }
                   5258:     return (\@possroles,$description);
                   5259: }
                   5260: 
1.399     www      5261: # ----------------------------------------------------- Frontpage Announcements
                   5262: #
                   5263: #
                   5264: 
                   5265: sub postannounce {
                   5266:     my ($server,$text)=@_;
1.844     albertel 5267:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5268:     unless ($text=~/\w/) { $text=''; }
                   5269:     return &reply('setannounce:'.&escape($text),$server);
                   5270: }
                   5271: 
                   5272: sub getannounce {
1.448     albertel 5273: 
1.1172.2.96  raeburn  5274:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5275: 	my $announcement='';
1.800     albertel 5276: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5277: 	close($fh);
1.399     www      5278: 	if ($announcement=~/\w/) { 
                   5279: 	    return 
                   5280:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5281:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5282: 	} else {
                   5283: 	    return '';
                   5284: 	}
                   5285:     } else {
                   5286: 	return '';
                   5287:     }
1.351     www      5288: }
1.353     www      5289: 
                   5290: # ---------------------------------------------------------- Course ID routines
                   5291: # Deal with domain's nohist_courseid.db files
                   5292: #
                   5293: 
                   5294: sub courseidput {
1.921     raeburn  5295:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5296:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5297:     my $outcome;
                   5298:     if ($caller eq 'timeonly') {
                   5299:         my $cids = '';
                   5300:         foreach my $item (keys(%$storehash)) {
                   5301:             $cids.=&escape($item).'&';
                   5302:         }
                   5303:         $cids=~s/\&$//;
                   5304:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5305:                           $coursehome);       
                   5306:     } else {
                   5307:         my $items = '';
                   5308:         foreach my $item (keys(%$storehash)) {
                   5309:             $items.= &escape($item).'='.
                   5310:                      &freeze_escape($$storehash{$item}).'&';
                   5311:         }
                   5312:         $items=~s/\&$//;
                   5313:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5314:                           $coursehome);
1.918     raeburn  5315:     }
                   5316:     if ($outcome eq 'unknown_cmd') {
                   5317:         my $what;
                   5318:         foreach my $cid (keys(%$storehash)) {
                   5319:             $what .= &escape($cid).'=';
1.921     raeburn  5320:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5321:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5322:             }
                   5323:             $what =~ s/\:$/&/;
                   5324:         }
                   5325:         $what =~ s/\&$//;  
                   5326:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5327:     } else {
                   5328:         return $outcome;
                   5329:     }
1.353     www      5330: }
                   5331: 
                   5332: sub courseiddump {
1.921     raeburn  5333:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5334:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5335:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5336:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5337:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5338:     my $as_hash = 1;
                   5339:     my %returnhash;
                   5340:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5341:     my %libserv = &all_library();
                   5342:     foreach my $tryserver (keys(%libserv)) {
                   5343:         if ( (  $hostidflag == 1 
                   5344: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5345: 	     || (!defined($hostidflag)) ) {
                   5346: 
1.918     raeburn  5347: 	    if (($domfilter eq '') ||
                   5348: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5349:                 my $rep;
                   5350:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5351:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5352:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5353:                                 &escape($descfilter), &escape($instcodefilter),
                   5354:                                 &escape($ownerfilter), &escape($coursefilter),
                   5355:                                 &escape($typefilter), &escape($regexp_ok),
                   5356:                                 $as_hash, &escape($selfenrollonly),
                   5357:                                 &escape($catfilter), $showhidden, $caller,
                   5358:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5359:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5360:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5361:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5362:                 } else {
                   5363:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5364:                              $sincefilter.':'.&escape($descfilter).':'.
                   5365:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5366:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5367:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5368:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5369:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5370:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5371:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5372:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5373:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5374:                 }
                   5375: 
1.918     raeburn  5376:                 my @pairs=split(/\&/,$rep);
                   5377:                 foreach my $item (@pairs) {
                   5378:                     my ($key,$value)=split(/\=/,$item,2);
                   5379:                     $key = &unescape($key);
                   5380:                     next if ($key =~ /^error: 2 /);
                   5381:                     my $result = &thaw_unescape($value);
                   5382:                     if (ref($result) eq 'HASH') {
                   5383:                         $returnhash{$key}=$result;
                   5384:                     } else {
1.921     raeburn  5385:                         my @responses = split(/:/,$value);
                   5386:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5387:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5388:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5389:                         }
1.1008    raeburn  5390:                     }
1.353     www      5391:                 }
                   5392:             }
                   5393:         }
                   5394:     }
                   5395:     return %returnhash;
                   5396: }
                   5397: 
1.1055    raeburn  5398: sub courselastaccess {
                   5399:     my ($cdom,$cnum,$hostidref) = @_;
                   5400:     my %returnhash;
                   5401:     if ($cdom && $cnum) {
                   5402:         my $chome = &homeserver($cnum,$cdom);
                   5403:         if ($chome ne 'no_host') {
                   5404:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5405:             &extract_lastaccess(\%returnhash,$rep);
                   5406:         }
                   5407:     } else {
                   5408:         if (!$cdom) { $cdom=''; }
                   5409:         my %libserv = &all_library();
                   5410:         foreach my $tryserver (keys(%libserv)) {
                   5411:             if (ref($hostidref) eq 'ARRAY') {
                   5412:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5413:             } 
                   5414:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5415:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5416:                 &extract_lastaccess(\%returnhash,$rep);
                   5417:             }
                   5418:         }
                   5419:     }
                   5420:     return %returnhash;
                   5421: }
                   5422: 
                   5423: sub extract_lastaccess {
                   5424:     my ($returnhash,$rep) = @_;
                   5425:     if (ref($returnhash) eq 'HASH') {
                   5426:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5427:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5428:                  $rep eq '') {
                   5429:             my @pairs=split(/\&/,$rep);
                   5430:             foreach my $item (@pairs) {
                   5431:                 my ($key,$value)=split(/\=/,$item,2);
                   5432:                 $key = &unescape($key);
                   5433:                 next if ($key =~ /^error: 2 /);
                   5434:                 $returnhash->{$key} = &thaw_unescape($value);
                   5435:             }
                   5436:         }
                   5437:     }
                   5438:     return;
                   5439: }
                   5440: 
1.658     raeburn  5441: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5442: 
                   5443: sub dcmailput {
1.685     raeburn  5444:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5445:     my $status = &Apache::lonnet::critical(
1.740     www      5446:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5447:        &escape($message),$server);
1.662     raeburn  5448:     return $status;
                   5449: }
                   5450: 
1.658     raeburn  5451: sub dcmaildump {
                   5452:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5453:     my %returnhash=();
1.846     albertel 5454: 
                   5455:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5456:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5457:                                                          &escape($enddate).':';
                   5458: 	my @esc_senders=map { &escape($_)} @$senders;
                   5459: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5460: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5461:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5462:             if (($key) && ($value)) {
                   5463:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5464:             }
                   5465:         }
                   5466:     }
                   5467:     return %returnhash;
                   5468: }
1.662     raeburn  5469: # ---------------------------------------------------------- Domain roles
                   5470: 
                   5471: sub get_domain_roles {
                   5472:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5473:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5474:         $startdate = '.';
                   5475:     }
1.1018    raeburn  5476:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5477:         $enddate = '.';
                   5478:     }
1.922     raeburn  5479:     my $rolelist;
                   5480:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5481:         $rolelist = join('&',@{$roles});
1.922     raeburn  5482:     }
1.662     raeburn  5483:     my %personnel = ();
1.841     albertel 5484: 
                   5485:     my %servers = &get_servers($dom,'library');
                   5486:     foreach my $tryserver (keys(%servers)) {
                   5487: 	%{$personnel{$tryserver}}=();
                   5488: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5489: 					    &escape($startdate).':'.
                   5490: 					    &escape($enddate).':'.
                   5491: 					    &escape($rolelist), $tryserver))) {
                   5492: 	    my ($key,$value) = split(/\=/,$line,2);
                   5493: 	    if (($key) && ($value)) {
                   5494: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5495: 	    }
                   5496: 	}
1.662     raeburn  5497:     }
                   5498:     return %personnel;
                   5499: }
1.658     raeburn  5500: 
1.1172.2.89  raeburn  5501: sub get_active_domroles {
                   5502:     my ($dom,$roles) = @_;
                   5503:     return () unless (ref($roles) eq 'ARRAY');
                   5504:     my $now = time;
                   5505:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5506:     my %domroles;
                   5507:     foreach my $server (keys(%dompersonnel)) {
                   5508:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5509:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5510:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5511:         }
                   5512:     }
                   5513:     return %domroles;
                   5514: }
                   5515: 
1.1057    www      5516: # ----------------------------------------------------------- Interval timing 
1.149     www      5517: 
1.1153    www      5518: {
                   5519: # Caches needed for speedup of navmaps
                   5520: # We don't want to cache this for very long at all (5 seconds at most)
                   5521: # 
                   5522: # The user for whom we cache
                   5523: my $cachedkey='';
                   5524: # The cached times for this user
                   5525: my %cachedtimes=();
                   5526: # When this was last done
1.1172.2.66  raeburn  5527: my $cachedtime='';
1.1153    www      5528: 
                   5529: sub load_all_first_access {
1.1154    raeburn  5530:     my ($uname,$udom)=@_;
1.1156    www      5531:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5532:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5533:         return;
                   5534:     }
                   5535:     $cachedtime=time;
                   5536:     $cachedkey=$uname.':'.$udom;
                   5537:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5538: }
                   5539: 
1.504     albertel 5540: sub get_first_access {
1.1162    raeburn  5541:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5542:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5543:     if ($argsymb) { $symb=$argsymb; }
                   5544:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5545:     if ($argmap) { $map = $argmap; }
1.926     albertel 5546:     if ($type eq 'course') {
                   5547: 	$res='course';
                   5548:     } elsif ($type eq 'map') {
1.588     albertel 5549: 	$res=&symbread($map);
                   5550:     } else {
                   5551: 	$res=$symb;
                   5552:     }
1.1153    www      5553:     &load_all_first_access($uname,$udom);
                   5554:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5555: }
                   5556: 
                   5557: sub set_first_access {
1.1162    raeburn  5558:     my ($type,$interval)=@_;
1.790     albertel 5559:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5560:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5561:     if ($type eq 'course') {
                   5562: 	$res='course';
                   5563:     } elsif ($type eq 'map') {
1.588     albertel 5564: 	$res=&symbread($map);
                   5565:     } else {
                   5566: 	$res=$symb;
                   5567:     }
1.1153    www      5568:     $cachedkey='';
1.1162    raeburn  5569:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5570:     if ($firstaccess) {
                   5571:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5572:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5573:                  "in $courseid");
                   5574:         return 'already_set';
                   5575:     } else {
1.1162    raeburn  5576:         my $start = time;
                   5577: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5578:                           $udom,$uname);
                   5579:         if ($putres eq 'ok') {
                   5580:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5581:                  $udom,$uname); 
                   5582:             &appenv(
                   5583:                      {
                   5584:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5585:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5586:                      }
                   5587:                   );
1.1172.2.97  raeburn  5588:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5589:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5590:             }
1.1172.2.102  raeburn  5591:         } elsif ($putres ne 'refused') {
                   5592:             &logthis("Result: $putres when attempting to set first access time ".
                   5593:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5594:         }
                   5595:         return $putres;
1.505     albertel 5596:     }
                   5597:     return 'already_set';
1.504     albertel 5598: }
1.1153    www      5599: }
1.1172.2.32  raeburn  5600: 
                   5601: sub checkout {
                   5602:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5603:     my $now=time;
                   5604:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5605:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5606:     my $infostr=&escape(
                   5607:                  'CHECKOUTTOKEN&'.
                   5608:                  $tuname.'&'.
                   5609:                  $tudom.'&'.
                   5610:                  $tcrsid.'&'.
                   5611:                  $symb.'&'.
1.1172.2.134  raeburn  5612:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5613:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5614:     if ($token=~/^error\:/) {
                   5615:         &logthis("<font color=\"blue\">WARNING: ".
                   5616:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5617:                  "</font>");
                   5618:         return '';
                   5619:     }
                   5620: 
                   5621:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5622:     $token=~tr/a-z/A-Z/;
                   5623: 
                   5624:     my %infohash=('resource.0.outtoken' => $token,
                   5625:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5626:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5627: 
                   5628:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5629:        return '';
                   5630:     } else {
                   5631:         &logthis("<font color=\"blue\">WARNING: ".
                   5632:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5633:                  "</font>");
                   5634:     }
                   5635: 
                   5636:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5637:                          &escape('Checkout '.$infostr.' - '.
                   5638:                                                  $token)) ne 'ok') {
                   5639:         return '';
                   5640:     } else {
                   5641:         &logthis("<font color=\"blue\">WARNING: ".
                   5642:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5643:                  "</font>");
                   5644:     }
                   5645:     return $token;
                   5646: }
                   5647: 
                   5648: # ------------------------------------------------------------ Check in an item
                   5649: 
                   5650: sub checkin {
                   5651:     my $token=shift;
                   5652:     my $now=time;
                   5653:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5654:     $lonhost=~tr/A-Z/a-z/;
                   5655:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5656:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5657:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5658:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5659:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5660: 
                   5661:     unless (($tuname) && ($tudom)) {
                   5662:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5663:         return '';
                   5664:     }
                   5665: 
                   5666:     unless (&allowed('mgr',$tcrsid)) {
                   5667:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5668:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5669:         return '';
                   5670:     }
                   5671: 
                   5672:     my %infohash=('resource.0.intoken' => $token,
                   5673:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5674:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5675: 
                   5676:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5677:        return '';
                   5678:     }
                   5679: 
                   5680:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5681:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5682:         return '';
                   5683:     }
                   5684: 
                   5685:     return ($symb,$tuname,$tudom,$tcrsid);
                   5686: }
                   5687: 
1.110     www      5688: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5689: 
                   5690: sub expirespread {
                   5691:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5692:     my $cid=$env{'request.course.id'}; 
1.110     www      5693:     if ($cid) {
                   5694:        my $now=time;
                   5695:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5696:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5697:                             $env{'course.'.$cid.'.num'}.
1.110     www      5698: 	        	    ':nohist_expirationdates:'.
                   5699:                             &escape($key).'='.$now,
1.620     albertel 5700:                             $env{'course.'.$cid.'.home'})
1.110     www      5701:     }
                   5702:     return 'ok';
1.14      www      5703: }
                   5704: 
1.109     www      5705: # ----------------------------------------------------- Devalidate Spreadsheets
                   5706: 
                   5707: sub devalidate {
1.325     www      5708:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5709:     my $cid=$env{'request.course.id'}; 
1.109     www      5710:     if ($cid) {
1.391     matthew  5711:         # delete the stored spreadsheets for
                   5712:         # - the student level sheet of this user in course's homespace
                   5713:         # - the assessment level sheet for this resource 
                   5714:         #   for this user in user's homespace
1.553     albertel 5715: 	# - current conditional state info
1.325     www      5716: 	my $key=$uname.':'.$udom.':';
1.109     www      5717:         my $status=
1.299     matthew  5718: 	    &del('nohist_calculatedsheets',
1.391     matthew  5719: 		 [$key.'studentcalc:'],
1.620     albertel 5720: 		 $env{'course.'.$cid.'.domain'},
                   5721: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5722: 		.' '.
                   5723: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5724: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5725:         unless ($status eq 'ok ok') {
                   5726:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5727:                     $uname.' at '.$udom.' for '.
1.109     www      5728: 		    $symb.': '.$status);
1.133     albertel 5729:         }
1.553     albertel 5730: 	&delenv('user.state.'.$cid);
1.109     www      5731:     }
                   5732: }
                   5733: 
1.265     albertel 5734: sub get_scalar {
                   5735:     my ($string,$end) = @_;
                   5736:     my $value;
                   5737:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5738: 	$value = $1;
                   5739:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5740: 	$value = $1;
                   5741:     }
                   5742:     return &unescape($value);
                   5743: }
                   5744: 
                   5745: sub array2str {
                   5746:   my (@array) = @_;
                   5747:   my $result=&arrayref2str(\@array);
                   5748:   $result=~s/^__ARRAY_REF__//;
                   5749:   $result=~s/__END_ARRAY_REF__$//;
                   5750:   return $result;
                   5751: }
                   5752: 
1.204     albertel 5753: sub arrayref2str {
                   5754:   my ($arrayref) = @_;
1.265     albertel 5755:   my $result='__ARRAY_REF__';
1.204     albertel 5756:   foreach my $elem (@$arrayref) {
1.265     albertel 5757:     if(ref($elem) eq 'ARRAY') {
                   5758:       $result.=&arrayref2str($elem).'&';
                   5759:     } elsif(ref($elem) eq 'HASH') {
                   5760:       $result.=&hashref2str($elem).'&';
                   5761:     } elsif(ref($elem)) {
                   5762:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5763:     } else {
                   5764:       $result.=&escape($elem).'&';
                   5765:     }
                   5766:   }
                   5767:   $result=~s/\&$//;
1.265     albertel 5768:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5769:   return $result;
                   5770: }
                   5771: 
1.168     albertel 5772: sub hash2str {
1.204     albertel 5773:   my (%hash) = @_;
                   5774:   my $result=&hashref2str(\%hash);
1.265     albertel 5775:   $result=~s/^__HASH_REF__//;
                   5776:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5777:   return $result;
                   5778: }
                   5779: 
                   5780: sub hashref2str {
                   5781:   my ($hashref)=@_;
1.265     albertel 5782:   my $result='__HASH_REF__';
1.800     albertel 5783:   foreach my $key (sort(keys(%$hashref))) {
                   5784:     if (ref($key) eq 'ARRAY') {
                   5785:       $result.=&arrayref2str($key).'=';
                   5786:     } elsif (ref($key) eq 'HASH') {
                   5787:       $result.=&hashref2str($key).'=';
                   5788:     } elsif (ref($key)) {
1.265     albertel 5789:       $result.='=';
1.800     albertel 5790:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5791:     } else {
1.1132    raeburn  5792: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5793:     }
                   5794: 
1.800     albertel 5795:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5796:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5797:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5798:       $result.=&hashref2str($hashref->{$key}).'&';
                   5799:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5800:        $result.='&';
1.800     albertel 5801:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5802:     } else {
1.800     albertel 5803:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5804:     }
                   5805:   }
1.168     albertel 5806:   $result=~s/\&$//;
1.265     albertel 5807:   $result .= '__END_HASH_REF__';
1.168     albertel 5808:   return $result;
                   5809: }
                   5810: 
                   5811: sub str2hash {
1.265     albertel 5812:     my ($string)=@_;
                   5813:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5814:     return %$hash;
                   5815: }
                   5816: 
                   5817: sub str2hashref {
1.168     albertel 5818:   my ($string) = @_;
1.265     albertel 5819: 
                   5820:   my %hash;
                   5821: 
                   5822:   if($string !~ /^__HASH_REF__/) {
                   5823:       if (! ($string eq '' || !defined($string))) {
                   5824: 	  $hash{'error'}='Not hash reference';
                   5825:       }
                   5826:       return (\%hash, $string);
                   5827:   }
                   5828: 
                   5829:   $string =~ s/^__HASH_REF__//;
                   5830: 
                   5831:   while($string !~ /^__END_HASH_REF__/) {
                   5832:       #key
                   5833:       my $key='';
                   5834:       if($string =~ /^__HASH_REF__/) {
                   5835:           ($key, $string)=&str2hashref($string);
                   5836:           if(defined($key->{'error'})) {
                   5837:               $hash{'error'}='Bad data';
                   5838:               return (\%hash, $string);
                   5839:           }
                   5840:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5841:           ($key, $string)=&str2arrayref($string);
                   5842:           if($key->[0] eq 'Array reference error') {
                   5843:               $hash{'error'}='Bad data';
                   5844:               return (\%hash, $string);
                   5845:           }
                   5846:       } else {
                   5847:           $string =~ s/^(.*?)=//;
1.267     albertel 5848: 	  $key=&unescape($1);
1.265     albertel 5849:       }
                   5850:       $string =~ s/^=//;
                   5851: 
                   5852:       #value
                   5853:       my $value='';
                   5854:       if($string =~ /^__HASH_REF__/) {
                   5855:           ($value, $string)=&str2hashref($string);
                   5856:           if(defined($value->{'error'})) {
                   5857:               $hash{'error'}='Bad data';
                   5858:               return (\%hash, $string);
                   5859:           }
                   5860:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5861:           ($value, $string)=&str2arrayref($string);
                   5862:           if($value->[0] eq 'Array reference error') {
                   5863:               $hash{'error'}='Bad data';
                   5864:               return (\%hash, $string);
                   5865:           }
                   5866:       } else {
                   5867: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5868:       }
                   5869:       $string =~ s/^&//;
                   5870: 
                   5871:       $hash{$key}=$value;
1.204     albertel 5872:   }
1.265     albertel 5873: 
                   5874:   $string =~ s/^__END_HASH_REF__//;
                   5875: 
                   5876:   return (\%hash, $string);
1.204     albertel 5877: }
                   5878: 
                   5879: sub str2array {
1.265     albertel 5880:     my ($string)=@_;
                   5881:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5882:     return @$array;
                   5883: }
                   5884: 
                   5885: sub str2arrayref {
1.204     albertel 5886:   my ($string) = @_;
1.265     albertel 5887:   my @array;
                   5888: 
                   5889:   if($string !~ /^__ARRAY_REF__/) {
                   5890:       if (! ($string eq '' || !defined($string))) {
                   5891: 	  $array[0]='Array reference error';
                   5892:       }
                   5893:       return (\@array, $string);
                   5894:   }
                   5895: 
                   5896:   $string =~ s/^__ARRAY_REF__//;
                   5897: 
                   5898:   while($string !~ /^__END_ARRAY_REF__/) {
                   5899:       my $value='';
                   5900:       if($string =~ /^__HASH_REF__/) {
                   5901:           ($value, $string)=&str2hashref($string);
                   5902:           if(defined($value->{'error'})) {
                   5903:               $array[0] ='Array reference error';
                   5904:               return (\@array, $string);
                   5905:           }
                   5906:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5907:           ($value, $string)=&str2arrayref($string);
                   5908:           if($value->[0] eq 'Array reference error') {
                   5909:               $array[0] ='Array reference error';
                   5910:               return (\@array, $string);
                   5911:           }
                   5912:       } else {
                   5913: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5914:       }
                   5915:       $string =~ s/^&//;
                   5916: 
                   5917:       push(@array, $value);
1.191     harris41 5918:   }
1.265     albertel 5919: 
                   5920:   $string =~ s/^__END_ARRAY_REF__//;
                   5921: 
                   5922:   return (\@array, $string);
1.168     albertel 5923: }
                   5924: 
1.167     albertel 5925: # -------------------------------------------------------------------Temp Store
                   5926: 
1.168     albertel 5927: sub tmpreset {
                   5928:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5929:   if (!$symb) {
                   5930:     $symb=&symbread();
1.620     albertel 5931:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5932:   }
                   5933:   $symb=escape($symb);
                   5934: 
1.620     albertel 5935:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5936:   $namespace=~s/\//\_/g;
                   5937:   $namespace=~s/\W//g;
                   5938: 
1.620     albertel 5939:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5940:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5941:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5942:       $stuname=&get_requestor_ip();
1.591     albertel 5943:   }
1.1117    foxr     5944:   my $path=LONCAPA::tempdir();
1.168     albertel 5945:   my %hash;
                   5946:   if (tie(%hash,'GDBM_File',
                   5947: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5948: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5949:     foreach my $key (keys(%hash)) {
1.180     albertel 5950:       if ($key=~ /:$symb/) {
1.168     albertel 5951: 	delete($hash{$key});
                   5952:       }
                   5953:     }
                   5954:   }
                   5955: }
                   5956: 
1.167     albertel 5957: sub tmpstore {
1.168     albertel 5958:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5959: 
                   5960:   if (!$symb) {
                   5961:     $symb=&symbread();
1.620     albertel 5962:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5963:   }
                   5964:   $symb=escape($symb);
                   5965: 
                   5966:   if (!$namespace) {
                   5967:     # I don't think we would ever want to store this for a course.
                   5968:     # it seems this will only be used if we don't have a course.
1.620     albertel 5969:     #$namespace=$env{'request.course.id'};
1.168     albertel 5970:     #if (!$namespace) {
1.620     albertel 5971:       $namespace=$env{'request.state'};
1.168     albertel 5972:     #}
                   5973:   }
                   5974:   $namespace=~s/\//\_/g;
                   5975:   $namespace=~s/\W//g;
1.620     albertel 5976:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5977:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5978:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5979:       $stuname=&get_requestor_ip();
1.591     albertel 5980:   }
1.168     albertel 5981:   my $now=time;
                   5982:   my %hash;
1.1117    foxr     5983:   my $path=LONCAPA::tempdir();
1.168     albertel 5984:   if (tie(%hash,'GDBM_File',
                   5985: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5986: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5987:     $hash{"version:$symb"}++;
                   5988:     my $version=$hash{"version:$symb"};
                   5989:     my $allkeys=''; 
                   5990:     foreach my $key (keys(%$storehash)) {
                   5991:       $allkeys.=$key.':';
1.591     albertel 5992:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5993:     }
                   5994:     $hash{"$version:$symb:timestamp"}=$now;
                   5995:     $allkeys.='timestamp';
                   5996:     $hash{"$version:keys:$symb"}=$allkeys;
                   5997:     if (untie(%hash)) {
                   5998:       return 'ok';
                   5999:     } else {
                   6000:       return "error:$!";
                   6001:     }
                   6002:   } else {
                   6003:     return "error:$!";
                   6004:   }
                   6005: }
1.167     albertel 6006: 
1.168     albertel 6007: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6008: 
1.168     albertel 6009: sub tmprestore {
                   6010:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6011: 
1.168     albertel 6012:   if (!$symb) {
                   6013:     $symb=&symbread();
1.620     albertel 6014:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6015:   }
                   6016:   $symb=escape($symb);
                   6017: 
1.620     albertel 6018:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6019: 
1.620     albertel 6020:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6021:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6022:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6023:       $stuname=&get_requestor_ip();
1.591     albertel 6024:   }
1.168     albertel 6025:   my %returnhash;
                   6026:   $namespace=~s/\//\_/g;
                   6027:   $namespace=~s/\W//g;
                   6028:   my %hash;
1.1117    foxr     6029:   my $path=LONCAPA::tempdir();
1.168     albertel 6030:   if (tie(%hash,'GDBM_File',
                   6031: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6032: 	  &GDBM_READER(),0640)) {
1.168     albertel 6033:     my $version=$hash{"version:$symb"};
                   6034:     $returnhash{'version'}=$version;
                   6035:     my $scope;
                   6036:     for ($scope=1;$scope<=$version;$scope++) {
                   6037:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6038:       my @keys=split(/:/,$vkeys);
                   6039:       my $key;
                   6040:       $returnhash{"$scope:keys"}=$vkeys;
                   6041:       foreach $key (@keys) {
1.591     albertel 6042: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6043: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6044:       }
                   6045:     }
1.168     albertel 6046:     if (!(untie(%hash))) {
                   6047:       return "error:$!";
                   6048:     }
                   6049:   } else {
                   6050:     return "error:$!";
                   6051:   }
                   6052:   return %returnhash;
1.167     albertel 6053: }
                   6054: 
1.9       www      6055: # ----------------------------------------------------------------------- Store
                   6056: 
                   6057: sub store {
1.1172.2.64  raeburn  6058:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6059:     my $home='';
                   6060: 
1.168     albertel 6061:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6062: 
1.213     www      6063:     $symb=&symbclean($symb);
1.122     albertel 6064:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6065: 
1.620     albertel 6066:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6067:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6068: 
                   6069:     &devalidate($symb,$stuname,$domain);
1.109     www      6070: 
                   6071:     $symb=escape($symb);
1.187     www      6072:     if (!$namespace) { 
1.620     albertel 6073:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6074:           return ''; 
                   6075:        } 
                   6076:     }
1.620     albertel 6077:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6078: 
1.1172.2.138  raeburn  6079:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6080:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6081: 
1.12      www      6082:     my $namevalue='';
1.800     albertel 6083:     foreach my $key (keys(%$storehash)) {
                   6084:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6085:     }
1.12      www      6086:     $namevalue=~s/\&$//;
1.187     www      6087:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6088:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6089: }
                   6090: 
1.47      www      6091: # -------------------------------------------------------------- Critical Store
                   6092: 
                   6093: sub cstore {
1.1172.2.64  raeburn  6094:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6095:     my $home='';
                   6096: 
1.168     albertel 6097:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6098: 
1.213     www      6099:     $symb=&symbclean($symb);
1.122     albertel 6100:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6101: 
1.620     albertel 6102:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6103:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6104: 
                   6105:     &devalidate($symb,$stuname,$domain);
1.109     www      6106: 
                   6107:     $symb=escape($symb);
1.187     www      6108:     if (!$namespace) { 
1.620     albertel 6109:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6110:           return ''; 
                   6111:        } 
                   6112:     }
1.620     albertel 6113:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6114: 
1.1172.2.138  raeburn  6115:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6116:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6117: 
1.47      www      6118:     my $namevalue='';
1.800     albertel 6119:     foreach my $key (keys(%$storehash)) {
                   6120:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6121:     }
1.47      www      6122:     $namevalue=~s/\&$//;
1.187     www      6123:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6124:     return critical
1.1172.2.64  raeburn  6125:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6126: }
                   6127: 
1.9       www      6128: # --------------------------------------------------------------------- Restore
                   6129: 
                   6130: sub restore {
1.124     www      6131:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6132:     my $home='';
                   6133: 
1.168     albertel 6134:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6135: 
1.122     albertel 6136:     if (!$symb) {
1.1172.2.26  raeburn  6137:         return if ($namespace eq 'courserequests');
                   6138:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6139:     } else {
1.1172.2.26  raeburn  6140:         unless ($namespace eq 'courserequests') {
                   6141:             $symb=&escape(&symbclean($symb));
                   6142:         }
1.122     albertel 6143:     }
1.188     www      6144:     if (!$namespace) { 
1.620     albertel 6145:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6146:           return ''; 
                   6147:        } 
                   6148:     }
1.620     albertel 6149:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6150:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6151:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6152:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6153: 
1.12      www      6154:     my %returnhash=();
1.800     albertel 6155:     foreach my $line (split(/\&/,$answer)) {
                   6156: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6157:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6158:     }
1.75      www      6159:     my $version;
                   6160:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6161:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6162:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6163:        }
1.75      www      6164:     }
1.13      www      6165:     return %returnhash;
1.34      www      6166: }
                   6167: 
                   6168: # ---------------------------------------------------------- Course Description
1.1118    foxr     6169: #
                   6170: #  
1.34      www      6171: 
                   6172: sub coursedescription {
1.731     albertel 6173:     my ($courseid,$args)=@_;
1.34      www      6174:     $courseid=~s/^\///;
1.49      www      6175:     $courseid=~s/\_/\//g;
1.34      www      6176:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6177:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6178:     my $normalid=$cdomain.'_'.$cnum;
                   6179:     # need to always cache even if we get errors otherwise we keep 
                   6180:     # trying and trying and trying to get the course description.
                   6181:     my %envhash=();
                   6182:     my %returnhash=();
1.731     albertel 6183:     
                   6184:     my $expiretime=600;
                   6185:     if ($env{'request.course.id'} eq $normalid) {
                   6186: 	$expiretime=120;
                   6187:     }
                   6188: 
                   6189:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6190:     if (!$args->{'freshen_cache'}
                   6191: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6192: 	foreach my $key (keys(%env)) {
                   6193: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6194: 	    my ($setting) = $1;
                   6195: 	    $returnhash{$setting} = $env{$key};
                   6196: 	}
                   6197: 	return %returnhash;
                   6198:     }
                   6199: 
1.1118    foxr     6200:     # get the data again
                   6201: 
1.731     albertel 6202:     if (!$args->{'one_time'}) {
                   6203: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6204:     }
1.811     albertel 6205: 
1.34      www      6206:     if ($chome ne 'no_host') {
1.302     albertel 6207:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6208:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6209: 	   my $username = $env{'user.name'}; # Defult username
                   6210: 	   if(defined $args->{'user'}) {
                   6211: 	       $username = $args->{'user'};
                   6212: 	   }
1.129     albertel 6213:            $returnhash{'home'}= $chome;
                   6214: 	   $returnhash{'domain'} = $cdomain;
                   6215: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6216:            if (!defined($returnhash{'type'})) {
                   6217:                $returnhash{'type'} = 'Course';
                   6218:            }
1.130     albertel 6219:            while (my ($name,$value) = each %returnhash) {
1.53      www      6220:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6221:            }
1.270     www      6222:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6223:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6224: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6225:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6226:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6227:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6228:        }
                   6229:     }
1.731     albertel 6230:     if (!$args->{'one_time'}) {
1.949     raeburn  6231: 	&appenv(\%envhash);
1.731     albertel 6232:     }
1.302     albertel 6233:     return %returnhash;
1.461     www      6234: }
                   6235: 
1.1080    raeburn  6236: sub update_released_required {
                   6237:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6238:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6239:         $cid = $env{'request.course.id'};
                   6240:         $cdom = $env{'course.'.$cid.'.domain'};
                   6241:         $cnum = $env{'course.'.$cid.'.num'};
                   6242:         $chome = $env{'course.'.$cid.'.home'};
                   6243:     }
                   6244:     if ($needsrelease) {
                   6245:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6246:         my $needsupdate;
                   6247:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6248:             $needsupdate = 1;
                   6249:         } else {
                   6250:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6251:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6252:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6253:                 $needsupdate = 1;
                   6254:             }
                   6255:         }
                   6256:         if ($needsupdate) {
                   6257:             my %needshash = (
                   6258:                              'internal.releaserequired' => $needsrelease,
                   6259:                             );
                   6260:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6261:             if ($putresult eq 'ok') {
                   6262:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6263:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6264:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6265:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6266:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6267:                 }
                   6268:             }
                   6269:         }
                   6270:     }
                   6271:     return;
                   6272: }
                   6273: 
1.461     www      6274: # -------------------------------------------------See if a user is privileged
                   6275: 
                   6276: sub privileged {
1.1172.2.23  raeburn  6277:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6278:     my $now = time;
1.1172.2.23  raeburn  6279:     my $roles;
                   6280:     if (ref($possroles) eq 'ARRAY') {
                   6281:         $roles = $possroles;
                   6282:     } else {
                   6283:         $roles = ['dc','su'];
                   6284:     }
                   6285:     if (ref($possdomains) eq 'ARRAY') {
                   6286:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6287:         foreach my $dom (@{$possdomains}) {
                   6288:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6289:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6290:                 foreach my $role (@{$roles}) {
                   6291:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6292:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6293:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6294:                             return 1 unless (($end && $end < $now) ||
                   6295:                                              ($start && $start > $now));
                   6296:                         }
                   6297:                     }
                   6298:                 }
                   6299:             }
                   6300:         }
                   6301:     } else {
                   6302:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6303:         my $now = time;
1.1170    droeschl 6304: 
1.1172.2.58  raeburn  6305:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6306:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6307:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6308:                 return 1 unless ($tend && $tend < $now)
                   6309:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6310:             }
1.1172.2.23  raeburn  6311:         }
                   6312:     }
1.461     www      6313:     return 0;
1.9       www      6314: }
1.1       albertel 6315: 
1.1172.2.23  raeburn  6316: sub privileged_by_domain {
                   6317:     my ($domains,$roles) = @_;
                   6318:     my %privileged = ();
                   6319:     my $cachetime = 60*60*24;
                   6320:     my $now = time;
                   6321:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6322:         return %privileged;
                   6323:     }
                   6324:     foreach my $dom (@{$domains}) {
                   6325:         next if (ref($privileged{$dom}) eq 'HASH');
                   6326:         my $needroles;
                   6327:         foreach my $role (@{$roles}) {
                   6328:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6329:             if (defined($cached)) {
                   6330:                 if (ref($result) eq 'HASH') {
                   6331:                     $privileged{$dom}{$role} = $result;
                   6332:                 }
                   6333:             } else {
                   6334:                 $needroles = 1;
                   6335:             }
                   6336:         }
                   6337:         if ($needroles) {
                   6338:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6339:             $privileged{$dom} = {};
                   6340:             foreach my $server (keys(%dompersonnel)) {
                   6341:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6342:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6343:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6344:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6345:                         next if ($end && $end < $now);
                   6346:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6347:                             $dompersonnel{$server}{$item};
                   6348:                     }
                   6349:                 }
                   6350:             }
                   6351:             if (ref($privileged{$dom}) eq 'HASH') {
                   6352:                 foreach my $role (@{$roles}) {
                   6353:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6354:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6355:                     } else {
                   6356:                         my %hash = ();
                   6357:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6358:                     }
                   6359:                 }
                   6360:             }
                   6361:         }
                   6362:     }
                   6363:     return %privileged;
                   6364: }
                   6365: 
1.103     harris41 6366: # -------------------------------------------------------- Get user privileges
1.11      www      6367: 
                   6368: sub rolesinit {
1.1169    droeschl 6369:     my ($domain, $username) = @_;
                   6370:     my %userroles = ('user.login.time' => time);
                   6371:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6372: 
                   6373:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6374:     # also, blocking can be triggered by an activating timer
                   6375:     # it's saved in the user's %env.
                   6376:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6377:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6378:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6379:         %timerintchk, %timerintenv);
                   6380: 
1.1162    raeburn  6381:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6382:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6383:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6384:     }
1.1169    droeschl 6385: 
1.1162    raeburn  6386:     foreach my $key (keys(%timerinterval)) {
                   6387:         my ($cid,$rest) = split(/\0/,$key);
                   6388:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6389:     }
1.1169    droeschl 6390: 
1.11      www      6391:     my %allroles=();
1.1162    raeburn  6392:     my %allgroups=();
1.11      www      6393: 
1.1172.2.58  raeburn  6394:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6395:         my $role = $rolesdump{$area};
                   6396:         $area =~ s/\_\w\w$//;
                   6397: 
                   6398:         my ($trole, $tend, $tstart, $group_privs);
                   6399: 
                   6400:         if ($role =~ /^cr/) {
                   6401:         # Custom role, defined by a user 
                   6402:         # e.g., user.role.cr/msu/smith/mynewrole
                   6403:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6404:                 $trole = $1;
                   6405:                 ($tend, $tstart) = split('_', $2);
                   6406:             } else {
                   6407:                 $trole = $role;
                   6408:             }
                   6409:         } elsif ($role =~ m|^gr/|) {
                   6410:         # Role of member in a group, defined within a course/community
                   6411:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6412:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6413:             next if $tstart eq '-1';
                   6414:             ($trole, $group_privs) = split(/\//, $trole);
                   6415:             $group_privs = &unescape($group_privs);
                   6416:         } else {
                   6417:         # Just a normal role, defined in roles.tab
                   6418:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6419:         }
                   6420: 
                   6421:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6422:                  $username);
                   6423:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6424: 
                   6425:         # role expired or not available yet?
                   6426:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6427:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6428: 
                   6429:         next if $area eq '' or $trole eq '';
                   6430: 
                   6431:         my $spec = "$trole.$area";
                   6432:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6433: 
                   6434:         if ($trole =~ /^cr\//) {
                   6435:         # Custom role, defined by a user
                   6436:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6437:         } elsif ($trole eq 'gr') {
                   6438:         # Role of a member in a group, defined within a course/community
                   6439:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6440:             next;
                   6441:         } else {
                   6442:         # Normal role, defined in roles.tab
                   6443:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6444:         }
                   6445: 
                   6446:         my $cid = $tdomain.'_'.$trest;
                   6447:         unless ($firstaccchk{$cid}) {
                   6448:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6449:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6450:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6451:                         $coursetimerstarts{$cid}{$item}; 
                   6452:                 }
                   6453:             }
                   6454:             $firstaccchk{$cid} = 1;
                   6455:         }
                   6456:         unless ($timerintchk{$cid}) {
                   6457:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6458:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6459:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6460:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6461:                 }
1.12      www      6462:             }
1.1169    droeschl 6463:             $timerintchk{$cid} = 1;
1.191     harris41 6464:         }
1.11      www      6465:     }
1.1169    droeschl 6466: 
1.1172.2.91  raeburn  6467:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6468:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6469:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6470:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6471: 
1.1162    raeburn  6472:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6473: }
                   6474: 
1.567     raeburn  6475: sub set_arearole {
1.1172.2.19  raeburn  6476:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6477:     unless ($nolog) {
1.567     raeburn  6478: # log the associated role with the area
1.1172.2.19  raeburn  6479:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6480:     }
1.743     albertel 6481:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6482: }
                   6483: 
                   6484: sub custom_roleprivs {
                   6485:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6486:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6487:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6488:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6489:         my ($rdummy,$roledef)=
                   6490:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6491:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6492:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6493:             if (defined($syspriv)) {
1.1043    raeburn  6494:                 if ($trest =~ /^$match_community$/) {
                   6495:                     $syspriv =~ s/bre\&S//; 
                   6496:                 }
1.567     raeburn  6497:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6498:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6499:             }
                   6500:             if ($tdomain ne '') {
                   6501:                 if (defined($dompriv)) {
                   6502:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6503:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6504:                 }
                   6505:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6506:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6507:                         my $rolename = $1;
                   6508:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6509:                     }
1.567     raeburn  6510:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6511:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6512:                 }
                   6513:             }
                   6514:         }
                   6515:     }
                   6516: }
                   6517: 
1.1172.2.89  raeburn  6518: sub course_adhocrole_privs {
                   6519:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6520:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6521:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6522:         my (%currprivs,%storeprivs);
                   6523:         foreach my $item (split(/:/,$coursepriv)) {
                   6524:             my ($priv,$restrict) = split(/\&/,$item);
                   6525:             $currprivs{$priv} = $restrict;
                   6526:         }
                   6527:         my (%possadd,%possremove,%full);
                   6528:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6529:             my ($priv,$restrict)=split(/\&/,$item);
                   6530:             $full{$priv} = $restrict;
                   6531:         }
                   6532:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6533:              next if ($item eq '');
                   6534:              my ($rule,$rest) = split(/=/,$item);
                   6535:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6536:              foreach my $priv (split(/:/,$rest)) {
                   6537:                  if ($priv ne '') {
                   6538:                      if ($rule eq 'off') {
                   6539:                          $possremove{$priv} = 1;
                   6540:                      } else {
                   6541:                          $possadd{$priv} = 1;
                   6542:                      }
                   6543:                  }
                   6544:              }
                   6545:          }
                   6546:          foreach my $priv (sort(keys(%full))) {
                   6547:              if (exists($currprivs{$priv})) {
                   6548:                  unless (exists($possremove{$priv})) {
                   6549:                      $storeprivs{$priv} = $currprivs{$priv};
                   6550:                  }
                   6551:              } elsif (exists($possadd{$priv})) {
                   6552:                  $storeprivs{$priv} = $full{$priv};
                   6553:              }
                   6554:          }
                   6555:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6556:      }
                   6557:      return $coursepriv;
                   6558: }
                   6559: 
1.678     raeburn  6560: sub group_roleprivs {
                   6561:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6562:     my $access = 1;
                   6563:     my $now = time;
                   6564:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6565:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6566:     if ($access) {
1.811     albertel 6567:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6568:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6569:     }
                   6570: }
1.567     raeburn  6571: 
                   6572: sub standard_roleprivs {
                   6573:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6574:     if (defined($pr{$trole.':s'})) {
                   6575:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6576:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6577:     }
                   6578:     if ($tdomain ne '') {
                   6579:         if (defined($pr{$trole.':d'})) {
                   6580:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6581:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6582:         }
                   6583:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6584:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6585:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6586:         }
                   6587:     }
                   6588: }
                   6589: 
                   6590: sub set_userprivs {
1.1064    raeburn  6591:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6592:     my $author=0;
                   6593:     my $adv=0;
1.1172.2.91  raeburn  6594:     my $rar=0;
1.678     raeburn  6595:     my %grouproles = ();
                   6596:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6597:         my @groupkeys; 
1.1000    raeburn  6598:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6599:             push(@groupkeys,$role);
                   6600:         }
                   6601:         if (ref($groups_roles) eq 'HASH') {
                   6602:             foreach my $key (keys(%{$groups_roles})) {
                   6603:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6604:                     push(@groupkeys,$key);
                   6605:                 }
                   6606:             }
                   6607:         }
                   6608:         if (@groupkeys > 0) {
                   6609:             foreach my $role (@groupkeys) {
                   6610:                 my ($trole,$area,$sec,$extendedarea);
                   6611:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6612:                     $trole = $1;
                   6613:                     $area = $2;
                   6614:                     $sec = $3;
                   6615:                     $extendedarea = $area.$sec;
                   6616:                     if (exists($$allgroups{$area})) {
                   6617:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6618:                             my $spec = $trole.'.'.$extendedarea;
                   6619:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6620:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6621:                         }
1.678     raeburn  6622:                     }
                   6623:                 }
                   6624:             }
                   6625:         }
                   6626:     }
1.800     albertel 6627:     foreach my $group (keys(%grouproles)) {
                   6628:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6629:     }
1.800     albertel 6630:     foreach my $role (keys(%{$allroles})) {
                   6631:         my %thesepriv;
1.941     raeburn  6632:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6633:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6634:             if ($item ne '') {
                   6635:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6636:                 if ($restrictions eq '') {
                   6637:                     $thesepriv{$privilege}='F';
                   6638:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6639:                     $thesepriv{$privilege}.=$restrictions;
                   6640:                 }
                   6641:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6642:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6643:             }
                   6644:         }
                   6645:         my $thesestr='';
1.1104    raeburn  6646:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6647: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6648: 	}
                   6649:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6650:     }
1.1172.2.91  raeburn  6651:     return ($author,$adv,$rar);
1.567     raeburn  6652: }
                   6653: 
1.994     raeburn  6654: sub role_status {
1.1104    raeburn  6655:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6656:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6657:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6658:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6659:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6660:             $$where = '/'.$two;
1.994     raeburn  6661:             $$trolecode=$$role.'.'.$$where;
                   6662:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6663:             $$tstatus='is';
1.1104    raeburn  6664:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6665:                 $$tstatus='future';
1.1034    raeburn  6666:                 if ($$tstart<$now) {
                   6667:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6668:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6669:                             my (%allroles,%allgroups,$group_privs,
                   6670:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6671:                             my %userroles = (
                   6672:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6673:                             );
1.1064    raeburn  6674:                             @rolecodes = ('cm'); 
1.1002    raeburn  6675:                             my $spec=$$role.'.'.$$where;
                   6676:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6677:                             if ($$role =~ /^cr\//) {
                   6678:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6679:                                 push(@rolecodes,'cr');
1.1002    raeburn  6680:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6681:                                 push(@rolecodes,$$role);
1.1002    raeburn  6682:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6683:                                                     $env{'user.name'});
1.1064    raeburn  6684:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6685:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6686:                                 $group_privs = &unescape($group_privs);
                   6687:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6688:                                 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  6689:                                 &get_groups_roles($tdomain,$trest,
                   6690:                                                   \%course_roles,\@rolecodes,
                   6691:                                                   \%groups_roles);
1.1002    raeburn  6692:                             } else {
1.1064    raeburn  6693:                                 push(@rolecodes,$$role);
1.1002    raeburn  6694:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6695:                             }
1.1172.2.91  raeburn  6696:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6697:                                                                    \%groups_roles);
1.1064    raeburn  6698:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6699:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6700:                         }
                   6701:                     }
1.1034    raeburn  6702:                     $$tstatus = 'is';
1.1002    raeburn  6703:                 }
1.994     raeburn  6704:             }
                   6705:             if ($$tend) {
1.1104    raeburn  6706:                 if ($$tend<$update) {
1.994     raeburn  6707:                     $$tstatus='expired';
                   6708:                 } elsif ($$tend<$now) {
                   6709:                     $$tstatus='will_not';
                   6710:                 }
                   6711:             }
                   6712:         }
                   6713:     }
                   6714: }
                   6715: 
1.1104    raeburn  6716: sub get_groups_roles {
                   6717:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6718:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6719:                   (ref($rolecodes) eq 'ARRAY') && 
                   6720:                   (ref($groups_roles) eq 'HASH')); 
                   6721:     if (keys(%{$cdom_courseroles}) > 0) {
                   6722:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6723:         if ($cdom ne '' && $cnum ne '') {
                   6724:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6725:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6726:                     my $crsrole = $1;
                   6727:                     my $crssec = $2;
                   6728:                     if ($crsrole =~ /^cr/) {
                   6729:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6730:                             push(@{$rolecodes},'cr');
                   6731:                         }
                   6732:                     } else {
                   6733:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6734:                             push(@{$rolecodes},$crsrole);
                   6735:                         }
                   6736:                     }
                   6737:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6738:                     if ($crssec ne '') {
                   6739:                         $rolekey .= "/$crssec";
                   6740:                     }
                   6741:                     $rolekey .= './';
                   6742:                     $groups_roles->{$rolekey} = $rolecodes;
                   6743:                 }
                   6744:             }
                   6745:         }
                   6746:     }
                   6747:     return;
                   6748: }
                   6749: 
                   6750: sub delete_env_groupprivs {
                   6751:     my ($where,$courseroles,$possroles) = @_;
                   6752:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6753:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6754:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6755:         %{$courseroles->{$udom}} =
                   6756:             &get_my_roles('','','userroles',['active'],
                   6757:                           $possroles,[$udom],1);
                   6758:     }
                   6759:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6760:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6761:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6762:             my $area = '/'.$cdom.'/'.$cnum;
                   6763:             my $privkey = "user.priv.$crsrole.$area";
                   6764:             if ($crssec ne '') {
                   6765:                 $privkey .= '/'.$crssec;
                   6766:             }
                   6767:             $privkey .= ".$area/$group";
                   6768:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6769:         }
                   6770:     }
                   6771:     return;
                   6772: }
                   6773: 
1.994     raeburn  6774: sub check_adhoc_privs {
1.1172.2.86  raeburn  6775:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6776:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6777:     if ($sec) {
                   6778:         $cckey .= '/'.$sec;
                   6779:     }
1.1172.2.9  raeburn  6780:     my $setprivs;
1.994     raeburn  6781:     if ($env{$cckey}) {
                   6782:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6783:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6784:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6785:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6786:             $setprivs = 1;
1.994     raeburn  6787:         }
                   6788:     } else {
1.1172.2.87  raeburn  6789:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6790:         $setprivs = 1;
1.994     raeburn  6791:     }
1.1172.2.9  raeburn  6792:     return $setprivs;
1.994     raeburn  6793: }
                   6794: 
                   6795: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6796: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6797:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6798:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6799:     if ($sec ne '') {
                   6800:         $area .= '/'.$sec;
                   6801:     }
1.994     raeburn  6802:     my $spec = $role.'.'.$area;
                   6803:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6804:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6805:     my %rolehash = ();
1.1172.2.89  raeburn  6806:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6807:         my $rolename = $1;
1.1172.2.84  raeburn  6808:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6809:         my %domdef = &get_domain_defaults($dcdom);
                   6810:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6811:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6812:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6813:             }
                   6814:         }
1.1172.2.84  raeburn  6815:     } else {
                   6816:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6817:     }
1.1172.2.91  raeburn  6818:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6819:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6820:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6821:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6822:         &appenv( {'request.role'        => $spec,
                   6823:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6824:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6825:                  }
                   6826:                );
                   6827:         my $tadv=0;
                   6828:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6829:         &appenv({'request.role.adv'    => $tadv});
                   6830:     }
1.994     raeburn  6831: }
                   6832: 
1.12      www      6833: # --------------------------------------------------------------- get interface
                   6834: 
                   6835: sub get {
1.131     albertel 6836:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6837:    my $items='';
1.800     albertel 6838:    foreach my $item (@$storearr) {
                   6839:        $items.=&escape($item).'&';
1.191     harris41 6840:    }
1.12      www      6841:    $items=~s/\&$//;
1.620     albertel 6842:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6843:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6844:    my $uhome=&homeserver($uname,$udomain);
                   6845: 
1.133     albertel 6846:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6847:    my @pairs=split(/\&/,$rep);
1.273     albertel 6848:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6849:      return @pairs;
                   6850:    }
1.15      www      6851:    my %returnhash=();
1.42      www      6852:    my $i=0;
1.800     albertel 6853:    foreach my $item (@$storearr) {
                   6854:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6855:       $i++;
1.191     harris41 6856:    }
1.15      www      6857:    return %returnhash;
1.27      www      6858: }
                   6859: 
                   6860: # --------------------------------------------------------------- del interface
                   6861: 
                   6862: sub del {
1.133     albertel 6863:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6864:    my $items='';
1.800     albertel 6865:    foreach my $item (@$storearr) {
                   6866:        $items.=&escape($item).'&';
1.191     harris41 6867:    }
1.984     neumanie 6868: 
1.27      www      6869:    $items=~s/\&$//;
1.620     albertel 6870:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6871:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6872:    my $uhome=&homeserver($uname,$udomain);
                   6873:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6874: }
                   6875: 
                   6876: # -------------------------------------------------------------- dump interface
                   6877: 
1.1172.2.22  raeburn  6878: sub unserialize {
                   6879:     my ($rep, $escapedkeys) = @_;
                   6880: 
                   6881:     return {} if $rep =~ /^error/;
                   6882: 
                   6883:     my %returnhash=();
                   6884:     foreach my $item (split(/\&/,$rep)) {
                   6885:         my ($key, $value) = split(/=/, $item, 2);
                   6886:         $key = unescape($key) unless $escapedkeys;
                   6887:         next if $key =~ /^error: 2 /;
                   6888:         $returnhash{$key} = &thaw_unescape($value);
                   6889:     }
                   6890:     return \%returnhash;
                   6891: }
                   6892: 
                   6893: # see Lond::dump_with_regexp
                   6894: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6895: sub dump {
1.1172.2.22  raeburn  6896:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6897:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6898:     if (!$uname) { $uname=$env{'user.name'}; }
                   6899:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6900: 
1.1172.2.55  raeburn  6901:     if ($regexp) {
                   6902:         $regexp=&escape($regexp);
                   6903:     } else {
                   6904:         $regexp='.';
                   6905:     }
1.1172.2.22  raeburn  6906:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6907:         # user is hosted on this machine
1.1172.2.55  raeburn  6908:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6909:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6910:         return %{&unserialize($reply, $escapedkeys)};
                   6911:     }
1.1166    raeburn  6912:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6913:     my @pairs=split(/\&/,$rep);
                   6914:     my %returnhash=();
1.1098    foxr     6915:     if (!($rep =~ /^error/ )) {
                   6916: 	foreach my $item (@pairs) {
                   6917: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6918:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6919: 	    next if ($key =~ /^error: 2 /);
                   6920: 	    $returnhash{$key}=&thaw_unescape($value);
                   6921: 	}
1.755     albertel 6922:     }
                   6923:     return %returnhash;
1.407     www      6924: }
                   6925: 
1.1098    foxr     6926: 
1.717     albertel 6927: # --------------------------------------------------------- dumpstore interface
                   6928: 
                   6929: sub dumpstore {
                   6930:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6931:    # same as dump but keys must be escaped. They may contain colon separated
                   6932:    # lists of values that may themself contain colons (e.g. symbs).
                   6933:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6934: }
                   6935: 
1.407     www      6936: # -------------------------------------------------------------- keys interface
                   6937: 
                   6938: sub getkeys {
                   6939:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6940:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6941:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6942:    my $uhome=&homeserver($uname,$udomain);
                   6943:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6944:    my @keyarray=();
1.800     albertel 6945:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6946:       next if ($key =~ /^error: 2 /);
1.800     albertel 6947:       push(@keyarray,&unescape($key));
1.407     www      6948:    }
                   6949:    return @keyarray;
1.318     matthew  6950: }
                   6951: 
1.319     matthew  6952: # --------------------------------------------------------------- currentdump
                   6953: sub currentdump {
1.328     matthew  6954:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6955:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6956:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6957:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6958:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6959:    my $rep;
                   6960: 
                   6961:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6962:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6963:                    $courseid)));
                   6964:    } else {
                   6965:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6966:    }
                   6967: 
1.318     matthew  6968:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6969:    #
1.318     matthew  6970:    my %returnhash=();
1.319     matthew  6971:    #
                   6972:    if ($rep eq "unknown_cmd") { 
                   6973:        # an old lond will not know currentdump
                   6974:        # Do a dump and make it look like a currentdump
1.822     albertel 6975:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6976:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6977:        my %hash = @tmp;
                   6978:        @tmp=();
1.424     matthew  6979:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6980:    } else {
                   6981:        my @pairs=split(/\&/,$rep);
1.800     albertel 6982:        foreach my $pair (@pairs) {
                   6983:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6984:            my ($symb,$param) = split(/:/,$key);
                   6985:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6986:                                                         &thaw_unescape($value);
1.319     matthew  6987:        }
1.191     harris41 6988:    }
1.12      www      6989:    return %returnhash;
1.424     matthew  6990: }
                   6991: 
                   6992: sub convert_dump_to_currentdump{
                   6993:     my %hash = %{shift()};
                   6994:     my %returnhash;
                   6995:     # Code ripped from lond, essentially.  The only difference
                   6996:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6997:     # we might run in to problems with parameter names =~ /^v\./
                   6998:     while (my ($key,$value) = each(%hash)) {
                   6999:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7000: 	$symb  = &unescape($symb);
                   7001: 	$param = &unescape($param);
1.424     matthew  7002:         next if ($v eq 'version' || $symb eq 'keys');
                   7003:         next if (exists($returnhash{$symb}) &&
                   7004:                  exists($returnhash{$symb}->{$param}) &&
                   7005:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7006:         $returnhash{$symb}->{$param}=$value;
                   7007:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7008:     }
                   7009:     #
                   7010:     # Remove all of the keys in the hashes which keep track of
                   7011:     # the version of the parameter.
                   7012:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7013:         # use a foreach because we are going to delete from the hash.
                   7014:         foreach my $key (keys(%$param_hash)) {
                   7015:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7016:         }
                   7017:     }
                   7018:     return \%returnhash;
1.12      www      7019: }
                   7020: 
1.627     albertel 7021: # ------------------------------------------------------ critical inc interface
                   7022: 
                   7023: sub cinc {
                   7024:     return &inc(@_,'critical');
                   7025: }
                   7026: 
1.449     matthew  7027: # --------------------------------------------------------------- inc interface
                   7028: 
                   7029: sub inc {
1.627     albertel 7030:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7031:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7032:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7033:     my $uhome=&homeserver($uname,$udomain);
                   7034:     my $items='';
                   7035:     if (! ref($store)) {
                   7036:         # got a single value, so use that instead
                   7037:         $items = &escape($store).'=&';
                   7038:     } elsif (ref($store) eq 'SCALAR') {
                   7039:         $items = &escape($$store).'=&';        
                   7040:     } elsif (ref($store) eq 'ARRAY') {
                   7041:         $items = join('=&',map {&escape($_);} @{$store});
                   7042:     } elsif (ref($store) eq 'HASH') {
                   7043:         while (my($key,$value) = each(%{$store})) {
                   7044:             $items.= &escape($key).'='.&escape($value).'&';
                   7045:         }
                   7046:     }
                   7047:     $items=~s/\&$//;
1.627     albertel 7048:     if ($critical) {
                   7049: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7050:     } else {
                   7051: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7052:     }
1.449     matthew  7053: }
                   7054: 
1.12      www      7055: # --------------------------------------------------------------- put interface
                   7056: 
                   7057: sub put {
1.134     albertel 7058:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7059:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7060:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7061:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7062:    my $items='';
1.800     albertel 7063:    foreach my $item (keys(%$storehash)) {
                   7064:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7065:    }
1.12      www      7066:    $items=~s/\&$//;
1.134     albertel 7067:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7068: }
                   7069: 
1.631     albertel 7070: # ------------------------------------------------------------ newput interface
                   7071: 
                   7072: sub newput {
                   7073:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7074:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7075:    if (!$uname) { $uname=$env{'user.name'}; }
                   7076:    my $uhome=&homeserver($uname,$udomain);
                   7077:    my $items='';
                   7078:    foreach my $key (keys(%$storehash)) {
                   7079:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7080:    }
                   7081:    $items=~s/\&$//;
                   7082:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7083: }
                   7084: 
                   7085: # ---------------------------------------------------------  putstore interface
                   7086: 
1.524     raeburn  7087: sub putstore {
1.1172.2.59  raeburn  7088:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7090:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7091:    my $uhome=&homeserver($uname,$udomain);
                   7092:    my $items='';
1.715     albertel 7093:    foreach my $key (keys(%$storehash)) {
                   7094:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7095:    }
1.715     albertel 7096:    $items=~s/\&$//;
1.716     albertel 7097:    my $esc_symb=&escape($symb);
                   7098:    my $esc_v=&escape($version);
1.715     albertel 7099:    my $reply =
1.716     albertel 7100:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7101: 	      $uhome);
1.1172.2.59  raeburn  7102:    if (($tolog) && ($reply eq 'ok')) {
                   7103:        my $namevalue='';
                   7104:        foreach my $key (keys(%{$storehash})) {
                   7105:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7106:        }
1.1172.2.134  raeburn  7107:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7108:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7109:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7110:                      '&version='.$esc_v.
                   7111:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7112:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7113:    }
1.715     albertel 7114:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7115:        # gfall back to way things use to be done
1.715     albertel 7116:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7117: 			    $uname);
1.524     raeburn  7118:    }
1.715     albertel 7119:    return $reply;
                   7120: }
                   7121: 
                   7122: sub old_putstore {
1.716     albertel 7123:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7124:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7125:     if (!$uname) { $uname=$env{'user.name'}; }
                   7126:     my $uhome=&homeserver($uname,$udomain);
                   7127:     my %newstorehash;
1.800     albertel 7128:     foreach my $item (keys(%$storehash)) {
                   7129: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7130: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7131:     }
                   7132:     my $items='';
                   7133:     my %allitems = ();
1.800     albertel 7134:     foreach my $item (keys(%newstorehash)) {
                   7135: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7136: 	    my $key = $1.':keys:'.$2;
                   7137: 	    $allitems{$key} .= $3.':';
                   7138: 	}
1.800     albertel 7139: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7140:     }
1.800     albertel 7141:     foreach my $item (keys(%allitems)) {
                   7142: 	$allitems{$item} =~ s/\:$//;
                   7143: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7144:     }
                   7145:     $items=~s/\&$//;
                   7146:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7147: }
                   7148: 
1.47      www      7149: # ------------------------------------------------------ critical put interface
                   7150: 
                   7151: sub cput {
1.134     albertel 7152:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7155:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7156:    my $items='';
1.800     albertel 7157:    foreach my $item (keys(%$storehash)) {
                   7158:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7159:    }
1.47      www      7160:    $items=~s/\&$//;
1.134     albertel 7161:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7162: }
                   7163: 
                   7164: # -------------------------------------------------------------- eget interface
                   7165: 
                   7166: sub eget {
1.133     albertel 7167:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7168:    my $items='';
1.800     albertel 7169:    foreach my $item (@$storearr) {
                   7170:        $items.=&escape($item).'&';
1.191     harris41 7171:    }
1.12      www      7172:    $items=~s/\&$//;
1.620     albertel 7173:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7174:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7175:    my $uhome=&homeserver($uname,$udomain);
                   7176:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7177:    my @pairs=split(/\&/,$rep);
                   7178:    my %returnhash=();
1.42      www      7179:    my $i=0;
1.800     albertel 7180:    foreach my $item (@$storearr) {
                   7181:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7182:       $i++;
1.191     harris41 7183:    }
1.12      www      7184:    return %returnhash;
                   7185: }
                   7186: 
1.667     albertel 7187: # ------------------------------------------------------------ tmpput interface
                   7188: sub tmpput {
1.802     raeburn  7189:     my ($storehash,$server,$context)=@_;
1.667     albertel 7190:     my $items='';
1.800     albertel 7191:     foreach my $item (keys(%$storehash)) {
                   7192: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7193:     }
                   7194:     $items=~s/\&$//;
1.802     raeburn  7195:     if (defined($context)) {
                   7196:         $items .= ':'.&escape($context);
                   7197:     }
1.667     albertel 7198:     return &reply("tmpput:$items",$server);
                   7199: }
                   7200: 
                   7201: # ------------------------------------------------------------ tmpget interface
                   7202: sub tmpget {
1.688     albertel 7203:     my ($token,$server)=@_;
                   7204:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7205:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7206:     my %returnhash;
1.1172.2.85  raeburn  7207:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7208:         return %returnhash;
                   7209:     }
1.667     albertel 7210:     foreach my $item (split(/\&/,$rep)) {
                   7211: 	my ($key,$value)=split(/=/,$item);
                   7212: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7213:     }
                   7214:     return %returnhash;
                   7215: }
                   7216: 
1.1113    raeburn  7217: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7218: sub tmpdel {
                   7219:     my ($token,$server)=@_;
                   7220:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7221:     return &reply("tmpdel:$token",$server);
                   7222: }
                   7223: 
1.1172.2.13  raeburn  7224: # ------------------------------------------------------------ get_timebased_id
                   7225: 
                   7226: sub get_timebased_id {
                   7227:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7228:         $maxtries) = @_;
                   7229:     my ($newid,$error,$dellock);
                   7230:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7231:         return ('','ok','invalid call to get suffix');
                   7232:     }
                   7233: 
                   7234: # set defaults for any optional args for which values were not supplied
                   7235:     if ($who eq '') {
                   7236:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7237:     }
                   7238:     if (!$locktries) {
                   7239:         $locktries = 3;
                   7240:     }
                   7241:     if (!$maxtries) {
                   7242:         $maxtries = 10;
                   7243:     }
                   7244: 
                   7245:     if (($cdom eq '') || ($cnum eq '')) {
                   7246:         if ($env{'request.course.id'}) {
                   7247:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7248:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7249:         }
                   7250:         if (($cdom eq '') || ($cnum eq '')) {
                   7251:             return ('','ok','call to get suffix not in course context');
                   7252:         }
                   7253:     }
                   7254: 
                   7255: # construct locking item
                   7256:     my $lockhash = {
                   7257:                       $prefix."\0".'locked_'.$keyid => $who,
                   7258:                    };
                   7259:     my $tries = 0;
                   7260: 
                   7261: # attempt to get lock on nohist_$namespace file
                   7262:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7263:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7264:         $tries ++;
                   7265:         sleep 1;
                   7266:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7267:     }
                   7268: 
                   7269: # attempt to get unique identifier, based on current timestamp
                   7270:     if ($gotlock eq 'ok') {
                   7271:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7272:         my $id = time;
                   7273:         $newid = $id;
1.1172.2.56  raeburn  7274:         if ($idtype eq 'addcode') {
                   7275:             $newid .= &sixnum_code();
                   7276:         }
1.1172.2.13  raeburn  7277:         my $idtries = 0;
                   7278:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7279:             if ($idtype eq 'concat') {
                   7280:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7281:             } elsif ($idtype eq 'addcode') {
                   7282:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7283:             } else {
                   7284:                 $newid ++;
                   7285:             }
                   7286:             $idtries ++;
                   7287:         }
                   7288:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7289:             my %new_item =  (
                   7290:                               $prefix."\0".$newid => $who,
                   7291:                             );
                   7292:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7293:                                                  $cdom,$cnum);
                   7294:             if ($putresult ne 'ok') {
                   7295:                 undef($newid);
                   7296:                 $error = 'error saving new item: '.$putresult;
                   7297:             }
                   7298:         } else {
1.1172.2.56  raeburn  7299:              undef($newid);
1.1172.2.13  raeburn  7300:              $error = ('error: no unique suffix available for the new item ');
                   7301:         }
                   7302: #  remove lock
                   7303:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7304:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7305:     } else {
                   7306:         $error = "error: could not obtain lockfile\n";
                   7307:         $dellock = 'ok';
1.1172.2.58  raeburn  7308:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7309:             $dellock = 'nolock';
                   7310:         }
1.1172.2.13  raeburn  7311:     }
                   7312:     return ($newid,$dellock,$error);
                   7313: }
                   7314: 
1.1172.2.56  raeburn  7315: sub sixnum_code {
                   7316:     my $code;
                   7317:     for (0..6) {
                   7318:         $code .= int( rand(9) );
                   7319:     }
                   7320:     return $code;
                   7321: }
                   7322: 
1.765     albertel 7323: # -------------------------------------------------- portfolio access checking
                   7324: 
                   7325: sub portfolio_access {
1.1172.2.77  raeburn  7326:     my ($requrl,$clientip) = @_;
1.765     albertel 7327:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7328:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7329:     if ($result) {
                   7330:         my %setters;
                   7331:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7332:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7333:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7334:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7335:                 return 'B';
                   7336:             }
                   7337:         } else {
1.1172.2.142  raeburn  7338:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7339:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7340:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7341:                 return 'B';
                   7342:             }
                   7343:         }
                   7344:     }
1.765     albertel 7345:     if ($result eq 'ok') {
1.766     albertel 7346:        return 'F';
1.765     albertel 7347:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7348:        return 'A';
1.765     albertel 7349:     }
1.766     albertel 7350:     return '';
1.765     albertel 7351: }
                   7352: 
                   7353: sub get_portfolio_access {
1.1172.2.77  raeburn  7354:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7355: 
                   7356:     if (!ref($access_hash)) {
                   7357: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7358: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7359: 						   $file_name);
                   7360: 	$access_hash = $access_controls{$file_name};
                   7361:     }
                   7362: 
1.1172.2.77  raeburn  7363:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7364:     my $now = time;
                   7365:     if (ref($access_hash) eq 'HASH') {
                   7366:         foreach my $key (keys(%{$access_hash})) {
                   7367:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7368:             if ($start > $now) {
                   7369:                 next;
                   7370:             }
                   7371:             if ($end && $end<$now) {
                   7372:                 next;
                   7373:             }
                   7374:             if ($scope eq 'public') {
                   7375:                 $public = $key;
                   7376:                 last;
                   7377:             } elsif ($scope eq 'guest') {
                   7378:                 $guest = $key;
                   7379:             } elsif ($scope eq 'domains') {
                   7380:                 push(@domains,$key);
                   7381:             } elsif ($scope eq 'users') {
                   7382:                 push(@users,$key);
                   7383:             } elsif ($scope eq 'course') {
                   7384:                 push(@courses,$key);
                   7385:             } elsif ($scope eq 'group') {
                   7386:                 push(@groups,$key);
1.1172.2.77  raeburn  7387:             } elsif ($scope eq 'ip') {
                   7388:                 push(@ips,$key);
1.765     albertel 7389:             }
                   7390:         }
                   7391:         if ($public) {
                   7392:             return 'ok';
1.1172.2.77  raeburn  7393:         } elsif (@ips > 0) {
                   7394:             my $allowed;
                   7395:             foreach my $ipkey (@ips) {
                   7396:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7397:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7398:                         $allowed = 1;
                   7399:                         last;
                   7400:                     }
                   7401:                 }
                   7402:             }
                   7403:             if ($allowed) {
                   7404:                 return 'ok';
                   7405:             }
1.765     albertel 7406:         }
                   7407:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7408:             if ($guest) {
                   7409:                 return $guest;
                   7410:             }
                   7411:         } else {
                   7412:             if (@domains > 0) {
                   7413:                 foreach my $domkey (@domains) {
                   7414:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7415:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7416:                             return 'ok';
                   7417:                         }
                   7418:                     }
                   7419:                 }
                   7420:             }
                   7421:             if (@users > 0) {
                   7422:                 foreach my $userkey (@users) {
1.865     raeburn  7423:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7424:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7425:                             if (ref($item) eq 'HASH') {
                   7426:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7427:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7428:                                     return 'ok';
                   7429:                                 }
                   7430:                             }
                   7431:                         }
                   7432:                     } 
1.765     albertel 7433:                 }
                   7434:             }
                   7435:             my %roleshash;
                   7436:             my @courses_and_groups = @courses;
                   7437:             push(@courses_and_groups,@groups); 
                   7438:             if (@courses_and_groups > 0) {
                   7439:                 my (%allgroups,%allroles); 
                   7440:                 my ($start,$end,$role,$sec,$group);
                   7441:                 foreach my $envkey (%env) {
1.1060    raeburn  7442:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7443:                         my $cid = $2.'_'.$3; 
                   7444:                         if ($1 eq 'gr') {
                   7445:                             $group = $4;
                   7446:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7447:                         } else {
                   7448:                             if ($4 eq '') {
                   7449:                                 $sec = 'none';
                   7450:                             } else {
                   7451:                                 $sec = $4;
                   7452:                             }
                   7453:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7454:                         }
1.811     albertel 7455:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7456:                         my $cid = $2.'_'.$3;
                   7457:                         if ($4 eq '') {
                   7458:                             $sec = 'none';
                   7459:                         } else {
                   7460:                             $sec = $4;
                   7461:                         }
                   7462:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7463:                     }
                   7464:                 }
                   7465:                 if (keys(%allroles) == 0) {
                   7466:                     return;
                   7467:                 }
                   7468:                 foreach my $key (@courses_and_groups) {
                   7469:                     my %content = %{$$access_hash{$key}};
                   7470:                     my $cnum = $content{'number'};
                   7471:                     my $cdom = $content{'domain'};
                   7472:                     my $cid = $cdom.'_'.$cnum;
                   7473:                     if (!exists($allroles{$cid})) {
                   7474:                         next;
                   7475:                     }    
                   7476:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7477:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7478:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7479:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7480:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7481:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7482:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7483:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7484:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7485:                                         if (grep/^all$/,@sections) {
                   7486:                                             return 'ok';
                   7487:                                         } else {
                   7488:                                             if (grep/^$sec$/,@sections) {
                   7489:                                                 return 'ok';
                   7490:                                             }
                   7491:                                         }
                   7492:                                     }
                   7493:                                 }
                   7494:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7495:                                     if (grep/^none$/,@groups) {
                   7496:                                         return 'ok';
                   7497:                                     }
                   7498:                                 } else {
                   7499:                                     if (grep/^all$/,@groups) {
                   7500:                                         return 'ok';
                   7501:                                     } 
                   7502:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7503:                                         if (grep/^$group$/,@groups) {
                   7504:                                             return 'ok';
                   7505:                                         }
                   7506:                                     }
                   7507:                                 } 
                   7508:                             }
                   7509:                         }
                   7510:                     }
                   7511:                 }
                   7512:             }
                   7513:             if ($guest) {
                   7514:                 return $guest;
                   7515:             }
                   7516:         }
                   7517:     }
                   7518:     return;
                   7519: }
                   7520: 
                   7521: sub course_group_datechecker {
                   7522:     my ($dates,$now,$status) = @_;
                   7523:     my ($start,$end) = split(/\./,$dates);
                   7524:     if (!$start && !$end) {
                   7525:         return 'ok';
                   7526:     }
                   7527:     if (grep/^active$/,@{$status}) {
                   7528:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7529:             return 'ok';
                   7530:         }
                   7531:     }
                   7532:     if (grep/^previous$/,@{$status}) {
                   7533:         if ($end > $now ) {
                   7534:             return 'ok';
                   7535:         }
                   7536:     }
                   7537:     if (grep/^future$/,@{$status}) {
                   7538:         if ($start > $now) {
                   7539:             return 'ok';
                   7540:         }
                   7541:     }
                   7542:     return; 
                   7543: }
                   7544: 
                   7545: sub parse_portfolio_url {
                   7546:     my ($url) = @_;
                   7547: 
                   7548:     my ($type,$udom,$unum,$group,$file_name);
                   7549:     
1.823     albertel 7550:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7551: 	$type = 1;
                   7552:         $udom = $1;
                   7553:         $unum = $2;
                   7554:         $file_name = $3;
1.823     albertel 7555:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7556: 	$type = 2;
                   7557:         $udom = $1;
                   7558:         $unum = $2;
                   7559:         $group = $3;
                   7560:         $file_name = $3.'/'.$4;
                   7561:     }
                   7562:     if (wantarray) {
                   7563: 	return ($type,$udom,$unum,$file_name,$group);
                   7564:     }
                   7565:     return $type;
                   7566: }
                   7567: 
                   7568: sub is_portfolio_url {
                   7569:     my ($url) = @_;
                   7570:     return scalar(&parse_portfolio_url($url));
                   7571: }
                   7572: 
1.798     raeburn  7573: sub is_portfolio_file {
                   7574:     my ($file) = @_;
1.820     raeburn  7575:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7576:         return 1;
                   7577:     }
                   7578:     return;
                   7579: }
                   7580: 
1.976     raeburn  7581: sub usertools_access {
1.1084    raeburn  7582:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7583:     my ($access,%tools);
                   7584:     if ($context eq '') {
                   7585:         $context = 'tools';
                   7586:     }
                   7587:     if ($context eq 'requestcourses') {
                   7588:         %tools = (
                   7589:                       official   => 1,
                   7590:                       unofficial => 1,
1.1006    raeburn  7591:                       community  => 1,
1.1172.2.37  raeburn  7592:                       textbook   => 1,
1.985     raeburn  7593:                  );
1.1172.2.9  raeburn  7594:     } elsif ($context eq 'requestauthor') {
                   7595:         %tools = (
                   7596:                       requestauthor => 1,
                   7597:                  );
1.985     raeburn  7598:     } else {
                   7599:         %tools = (
                   7600:                       aboutme   => 1,
                   7601:                       blog      => 1,
1.1172.2.6  raeburn  7602:                       webdav    => 1,
1.985     raeburn  7603:                       portfolio => 1,
                   7604:                  );
                   7605:     }
1.976     raeburn  7606:     return if (!defined($tools{$tool}));
                   7607: 
1.1172.2.35  raeburn  7608:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7609:         $udom = $env{'user.domain'};
                   7610:         $uname = $env{'user.name'};
                   7611:     }
                   7612: 
1.978     raeburn  7613:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7614:         if ($action ne 'reload') {
1.985     raeburn  7615:             if ($context eq 'requestcourses') {
                   7616:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7617:             } elsif ($context eq 'requestauthor') {
                   7618:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7619:             } else {
                   7620:                 return $env{'environment.availabletools.'.$tool};
                   7621:             }
                   7622:         }
1.976     raeburn  7623:     }
                   7624: 
1.1172.2.9  raeburn  7625:     my ($toolstatus,$inststatus,$envkey);
                   7626:     if ($context eq 'requestauthor') {
                   7627:         $envkey = $context;
                   7628:     } else {
                   7629:         $envkey = $context.'.'.$tool;
                   7630:     }
1.976     raeburn  7631: 
1.985     raeburn  7632:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7633:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7634:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7635:         $inststatus = $env{'environment.inststatus'};
                   7636:     } else {
1.1084    raeburn  7637:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7638:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7639:             $inststatus = $userenvref->{'inststatus'};
                   7640:         } else {
1.1172.2.9  raeburn  7641:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7642:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7643:             $inststatus = $userenv{'inststatus'};
                   7644:         }
1.976     raeburn  7645:     }
                   7646: 
                   7647:     if ($toolstatus ne '') {
                   7648:         if ($toolstatus) {
                   7649:             $access = 1;
                   7650:         } else {
                   7651:             $access = 0;
                   7652:         }
                   7653:         return $access;
                   7654:     }
                   7655: 
1.1084    raeburn  7656:     my ($is_adv,%domdef);
                   7657:     if (ref($is_advref) eq 'HASH') {
                   7658:         $is_adv = $is_advref->{'is_adv'};
                   7659:     } else {
                   7660:         $is_adv = &is_advanced_user($udom,$uname);
                   7661:     }
                   7662:     if (ref($domdefref) eq 'HASH') {
                   7663:         %domdef = %{$domdefref};
                   7664:     } else {
                   7665:         %domdef = &get_domain_defaults($udom);
                   7666:     }
1.976     raeburn  7667:     if (ref($domdef{$tool}) eq 'HASH') {
                   7668:         if ($is_adv) {
                   7669:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7670:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7671:                     $access = 1;
                   7672:                 } else {
                   7673:                     $access = 0;
                   7674:                 }
                   7675:                 return $access;
                   7676:             }
                   7677:         }
                   7678:         if ($inststatus ne '') {
                   7679:             my ($hasaccess,$hasnoaccess);
                   7680:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7681:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7682:                     if ($domdef{$tool}{$affiliation}) {
                   7683:                         $hasaccess = 1;
                   7684:                     } else {
                   7685:                         $hasnoaccess = 1;
                   7686:                     }
                   7687:                 }
                   7688:             }
                   7689:             if ($hasaccess || $hasnoaccess) {
                   7690:                 if ($hasaccess) {
                   7691:                     $access = 1;
                   7692:                 } elsif ($hasnoaccess) {
                   7693:                     $access = 0; 
                   7694:                 }
                   7695:                 return $access;
                   7696:             }
                   7697:         } else {
                   7698:             if ($domdef{$tool}{'default'} ne '') {
                   7699:                 if ($domdef{$tool}{'default'}) {
                   7700:                     $access = 1;
                   7701:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7702:                     $access = 0;
                   7703:                 }
                   7704:                 return $access;
                   7705:             }
                   7706:         }
                   7707:     } else {
1.1172.2.6  raeburn  7708:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7709:             $access = 1;
                   7710:         } else {
                   7711:             $access = 0;
                   7712:         }
1.976     raeburn  7713:         return $access;
                   7714:     }
                   7715: }
                   7716: 
1.1050    raeburn  7717: sub is_course_owner {
                   7718:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7719:     if (($udom eq '') || ($uname eq '')) {
                   7720:         $udom = $env{'user.domain'};
                   7721:         $uname = $env{'user.name'};
                   7722:     }
                   7723:     unless (($udom eq '') || ($uname eq '')) {
                   7724:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7725:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7726:                 return 1;
                   7727:             } else {
                   7728:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7729:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7730:                     return 1;
                   7731:                 }
                   7732:             }
                   7733:         }
                   7734:     }
                   7735:     return;
                   7736: }
                   7737: 
1.976     raeburn  7738: sub is_advanced_user {
                   7739:     my ($udom,$uname) = @_;
1.1085    raeburn  7740:     if ($udom ne '' && $uname ne '') {
                   7741:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7742:             if (wantarray) {
                   7743:                 return ($env{'user.adv'},$env{'user.author'});
                   7744:             } else {
                   7745:                 return $env{'user.adv'};
                   7746:             }
1.1085    raeburn  7747:         }
                   7748:     }
1.976     raeburn  7749:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7750:     my %allroles;
1.1128    raeburn  7751:     my ($is_adv,$is_author);
1.976     raeburn  7752:     foreach my $role (keys(%roleshash)) {
                   7753:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7754:         my $area = '/'.$tdomain.'/'.$trest;
                   7755:         if ($sec ne '') {
                   7756:             $area .= '/'.$sec;
                   7757:         }
                   7758:         if (($area ne '') && ($trole ne '')) {
                   7759:             my $spec=$trole.'.'.$area;
                   7760:             if ($trole =~ /^cr\//) {
                   7761:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7762:             } elsif ($trole ne 'gr') {
                   7763:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7764:             }
1.1128    raeburn  7765:             if ($trole eq 'au') {
                   7766:                 $is_author = 1;
                   7767:             }
1.976     raeburn  7768:         }
                   7769:     }
                   7770:     foreach my $role (keys(%allroles)) {
                   7771:         last if ($is_adv);
                   7772:         foreach my $item (split(/:/,$allroles{$role})) {
                   7773:             if ($item ne '') {
                   7774:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7775:                 if ($privilege eq 'adv') {
                   7776:                     $is_adv = 1;
                   7777:                     last;
                   7778:                 }
                   7779:             }
                   7780:         }
                   7781:     }
1.1128    raeburn  7782:     if (wantarray) {
                   7783:         return ($is_adv,$is_author);
                   7784:     }
1.976     raeburn  7785:     return $is_adv;
                   7786: }
1.798     raeburn  7787: 
1.1035    raeburn  7788: sub check_can_request {
1.1036    raeburn  7789:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7790:     my $canreq = 0;
                   7791:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7792:     my @options = ('approval','validate','autolimit');
                   7793:     my $optregex = join('|',@options);
                   7794:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7795:         foreach my $type (@{$types}) {
                   7796:             if (&usertools_access($env{'user.name'},
                   7797:                                   $env{'user.domain'},
                   7798:                                   $type,undef,'requestcourses')) {
                   7799:                 $canreq ++;
1.1036    raeburn  7800:                 if (ref($request_domains) eq 'HASH') {
                   7801:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7802:                 }
1.1035    raeburn  7803:                 if ($dom eq $env{'user.domain'}) {
                   7804:                     $can_request->{$type} = 1;
                   7805:                 }
                   7806:             }
                   7807:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7808:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7809:                 if (@curr > 0) {
1.1036    raeburn  7810:                     foreach my $item (@curr) {
                   7811:                         if (ref($request_domains) eq 'HASH') {
                   7812:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7813:                             if ($otherdom ne '') {
                   7814:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7815:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7816:                                         push(@{$request_domains->{$type}},$otherdom);
                   7817:                                     }
                   7818:                                 } else {
                   7819:                                     push(@{$request_domains->{$type}},$otherdom);
                   7820:                                 }
                   7821:                             }
                   7822:                         }
                   7823:                     }
                   7824:                     unless($dom eq $env{'user.domain'}) {
                   7825:                         $canreq ++;
1.1035    raeburn  7826:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7827:                             $can_request->{$type} = 1;
                   7828:                         }
                   7829:                     }
                   7830:                 }
                   7831:             }
                   7832:         }
                   7833:     }
                   7834:     return $canreq;
                   7835: }
                   7836: 
1.341     www      7837: # ---------------------------------------------- Custom access rule evaluation
                   7838: 
                   7839: sub customaccess {
                   7840:     my ($priv,$uri)=@_;
1.807     albertel 7841:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7842:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7843:     $udom = &LONCAPA::clean_domain($udom);
                   7844:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7845:     my $access=0;
1.800     albertel 7846:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7847: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7848: 	if ($type eq 'user') {
                   7849: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7850: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7851: 		if ($tdom) {
                   7852: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7853: 		}
1.896     albertel 7854: 		if ($tuname) {
                   7855: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7856: 		}
                   7857: 		$access=($effect eq 'allow');
                   7858: 		last;
                   7859: 	    }
                   7860: 	} else {
                   7861: 	    if ($role) {
                   7862: 		if ($role ne $urole) { next; }
                   7863: 	    }
                   7864: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7865: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7866: 		if ($tdom) {
                   7867: 		    if ($tdom ne $udom) { next; }
                   7868: 		}
                   7869: 		if ($tcrs) {
                   7870: 		    if ($tcrs ne $ucrs) { next; }
                   7871: 		}
                   7872: 		if ($tsec) {
                   7873: 		    if ($tsec ne $usec) { next; }
                   7874: 		}
                   7875: 		$access=($effect eq 'allow');
                   7876: 		last;
                   7877: 	    }
                   7878: 	    if ($realm eq '' && $role eq '') {
                   7879: 		$access=($effect eq 'allow');
                   7880: 	    }
1.402     bowersj2 7881: 	}
1.341     www      7882:     }
                   7883:     return $access;
                   7884: }
                   7885: 
1.103     harris41 7886: # ------------------------------------------------- Check for a user privilege
1.12      www      7887: 
                   7888: sub allowed {
1.1172.2.126  raeburn  7889:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7890:     my $ver_orguri=$uri;
1.439     www      7891:     $uri=&deversion($uri);
1.152     www      7892:     my $orguri=$uri;
1.52      www      7893:     $uri=&declutter($uri);
1.809     raeburn  7894: 
1.810     raeburn  7895:     if ($priv eq 'evb') {
                   7896: # Evade communication block restrictions for specified role in a course
                   7897:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7898:             return $1;
                   7899:         } else {
                   7900:             return;
                   7901:         }
                   7902:     }
                   7903: 
1.620     albertel 7904:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7905: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7906:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7907: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7908: 	&& ($priv eq 'bre')) {
1.14      www      7909: 	return 'F';
1.159     www      7910:     }
                   7911: 
1.545     banghart 7912: # Free bre access to user's own portfolio contents
1.714     raeburn  7913:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7914:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7915: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7916:         my %setters;
1.1172.2.142  raeburn  7917:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   7918:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7919:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7920:             return 'B';
                   7921:         } else {
                   7922:             return 'F';
                   7923:         }
1.545     banghart 7924:     }
                   7925: 
1.762     raeburn  7926: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7927:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7928:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7929:         if (exists($env{'request.course.id'})) {
                   7930:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7931:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7932:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7933:                 my $courseprivid=$env{'request.course.id'};
                   7934:                 $courseprivid=~s/\_/\//;
                   7935:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7936:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7937:                     return $1; 
1.762     raeburn  7938:                 } else {
                   7939:                     if ($env{'request.course.sec'}) {
                   7940:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7941:                     }
                   7942:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7943:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7944:                         return $2;
                   7945:                     }
1.714     raeburn  7946:                 }
                   7947:             }
                   7948:         }
                   7949:     }
                   7950: 
1.159     www      7951: # Free bre to public access
                   7952: 
                   7953:     if ($priv eq 'bre') {
1.238     www      7954:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7955: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7956:            return 'F'; 
                   7957:         }
1.238     www      7958:         if ($copyright eq 'priv') {
                   7959:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7960: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7961: 		return '';
                   7962:             }
                   7963:         }
                   7964:         if ($copyright eq 'domain') {
                   7965:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7966: 	    unless (($env{'user.domain'} eq $1) ||
                   7967:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7968: 		return '';
                   7969:             }
1.262     matthew  7970:         }
1.620     albertel 7971:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7972:             # Library role, so allow browsing of resources in this domain.
                   7973:             return 'F';
1.238     www      7974:         }
1.341     www      7975:         if ($copyright eq 'custom') {
                   7976: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7977:         }
1.14      www      7978:     }
1.264     matthew  7979:     # Domain coordinator is trying to create a course
1.620     albertel 7980:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7981:         # uri is the requested domain in this case.
                   7982:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7983:         # a role of dc for the domain in question.
1.620     albertel 7984:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7985:     }
1.29      www      7986: 
1.52      www      7987:     my $thisallowed='';
                   7988:     my $statecond=0;
                   7989:     my $courseprivid='';
                   7990: 
1.1039    raeburn  7991:     my $ownaccess;
1.1043    raeburn  7992:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7993:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7994:         if ($uri eq '') {
                   7995:             $ownaccess = 1;
                   7996:         } else {
                   7997:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7998:                 my $udom = $env{'user.domain'};
                   7999:                 my $uname = $env{'user.name'};
                   8000:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8001:                     $ownaccess = 1;
1.1040    raeburn  8002:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8003:                     unless ($uri =~ m{\.\./}) {
                   8004:                         $ownaccess = 1;
                   8005:                     }
                   8006:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8007:                     my $now = time;
                   8008:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8009:                         my $adom = $1;
                   8010:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8011:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8012:                                 my ($start,$end) = split(/\./,$env{$key});
                   8013:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8014:                                     $ownaccess = 1;
                   8015:                                     last;
                   8016:                                 }
                   8017:                             }
                   8018:                         }
                   8019:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8020:                         my $adom = $1;
                   8021:                         my $aname = $2;
1.1042    raeburn  8022:                         foreach my $role ('ca','aa') { 
                   8023:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8024:                                 my ($start,$end) =
1.1172.2.142  raeburn  8025:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8026:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8027:                                     $ownaccess = 1;
                   8028:                                     last;
                   8029:                                 }
1.1039    raeburn  8030:                             }
                   8031:                         }
                   8032:                     }
                   8033:                 }
                   8034:             }
                   8035:         }
                   8036:     }
                   8037: 
1.52      www      8038: # Course
                   8039: 
1.620     albertel 8040:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8041:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8042:             $thisallowed.=$1;
                   8043:         }
1.52      www      8044:     }
1.29      www      8045: 
1.52      www      8046: # Domain
                   8047: 
1.620     albertel 8048:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8049:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8050:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8051:             $thisallowed.=$1;
                   8052:         }
1.12      www      8053:     }
1.52      www      8054: 
1.1141    raeburn  8055: # User who is not author or co-author might still be able to edit
                   8056: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8057:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8058:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8059:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8060:             $thisallowed.=$1;
                   8061:         }
                   8062:     }
                   8063: 
1.52      www      8064: # Course: uri itself is a course
1.66      www      8065:     my $courseuri=$uri;
                   8066:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8067:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8068: 
1.620     albertel 8069:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8070:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8071:         if ($priv eq 'mip') {
                   8072:             my $rem = $1;
                   8073:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8074:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8075:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8076:                 if ($cdom ne '') {
                   8077:                     my %passwdconf = &get_passwdconf($cdom);
                   8078:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8079:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8080:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8081:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8082:                                 unless (@inststatuses) {
                   8083:                                     @inststatuses = ('default');
                   8084:                                 }
                   8085:                                 foreach my $status (@inststatuses) {
                   8086:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8087:                                         $thisallowed.=$rem;
                   8088:                                     }
                   8089:                                 }
                   8090:                             }
                   8091:                         }
                   8092:                     }
                   8093:                 }
                   8094:             }
                   8095:         } else {
                   8096:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8097:                 $thisallowed.=$1;
                   8098:             }
1.1039    raeburn  8099:         }
1.12      www      8100:     }
1.29      www      8101: 
1.665     albertel 8102: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8103: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8104:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8105: 	$thisallowed='';
1.671     raeburn  8106:         my ($match)=&is_on_map($uri);
                   8107:         if ($match) {
                   8108:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8109:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8110:                 my $value = $1;
                   8111:                 if ($noblockcheck) {
                   8112:                     $thisallowed.=$value;
1.1162    raeburn  8113:                 } else {
1.1172.2.126  raeburn  8114:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8115:                     if (@blockers > 0) {
                   8116:                         $thisallowed = 'B';
                   8117:                     } else {
                   8118:                         $thisallowed.=$value;
                   8119:                     }
1.1162    raeburn  8120:                 }
1.671     raeburn  8121:             }
                   8122:         } else {
1.705     albertel 8123:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8124:             if ($refuri) {
                   8125:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8126:                     $thisallowed='F';
1.671     raeburn  8127:                 } else {
                   8128:                     $refuri=&declutter($refuri);
                   8129:                     my ($match) = &is_on_map($refuri);
                   8130:                     if ($match) {
1.1172.2.65  raeburn  8131:                         if ($noblockcheck) {
1.1162    raeburn  8132:                             $thisallowed='F';
1.1172.2.65  raeburn  8133:                         } else {
1.1172.2.127  raeburn  8134:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8135:                             if (@blockers > 0) {
                   8136:                                 $thisallowed = 'B';
                   8137:                             } else {
                   8138:                                 $thisallowed='F';
                   8139:                             }
1.1162    raeburn  8140:                         }
1.671     raeburn  8141:                     }
1.669     raeburn  8142:                 }
1.671     raeburn  8143:             }
                   8144:         }
1.314     www      8145:     }
1.492     albertel 8146: 
1.766     albertel 8147:     if ($priv eq 'bre'
                   8148: 	&& $thisallowed ne 'F' 
                   8149: 	&& $thisallowed ne '2'
                   8150: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8151: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8152:     }
                   8153:     
1.52      www      8154: # Full access at system, domain or course-wide level? Exit.
1.29      www      8155:     if ($thisallowed=~/F/) {
                   8156: 	return 'F';
                   8157:     }
                   8158: 
1.52      www      8159: # If this is generating or modifying users, exit with special codes
1.29      www      8160: 
1.643     www      8161:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8162: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8163: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8164: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8165: 	    unless ($auname) { return $thisallowed; }
                   8166: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8167: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8168: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8169: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8170: 	}
1.52      www      8171: 	return $thisallowed;
                   8172:     }
                   8173: #
1.103     harris41 8174: # Gathered so far: system, domain and course wide privileges
1.52      www      8175: #
                   8176: # Course: See if uri or referer is an individual resource that is part of 
                   8177: # the course
                   8178: 
1.620     albertel 8179:     if ($env{'request.course.id'}) {
1.232     www      8180: 
1.1172.2.115  raeburn  8181: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8182: 
                   8183:         if ($priv eq 'mip') {
                   8184:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8185:                 return $thisallowed;
                   8186:             } else {
                   8187:                 return '';
                   8188:             }
                   8189:         }
                   8190: 
1.620     albertel 8191:        $courseprivid=$env{'request.course.id'};
                   8192:        if ($env{'request.course.sec'}) {
                   8193:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8194:        }
                   8195:        $courseprivid=~s/\_/\//;
                   8196:        my $checkreferer=1;
1.232     www      8197:        my ($match,$cond)=&is_on_map($uri);
                   8198:        if ($match) {
                   8199:            $statecond=$cond;
1.620     albertel 8200:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8201:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8202:                my $value = $1;
                   8203:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8204:                    if ($noblockcheck) {
1.1162    raeburn  8205:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8206:                    } else {
1.1172.2.126  raeburn  8207:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8208:                        if (@blockers > 0) {
                   8209:                            $thisallowed = 'B';
                   8210:                        } else {
                   8211:                            $thisallowed.=$value;
                   8212:                        }
1.1162    raeburn  8213:                    }
                   8214:                } else {
                   8215:                    $thisallowed.=$value;
                   8216:                }
1.52      www      8217:                $checkreferer=0;
                   8218:            }
1.29      www      8219:        }
1.1172.2.126  raeburn  8220: 
1.148     www      8221:        if ($checkreferer) {
1.620     albertel 8222: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8223:             unless ($refuri) {
1.800     albertel 8224:                 foreach my $key (keys(%env)) {
                   8225: 		    if ($key=~/^httpref\..*\*/) {
                   8226: 			my $pattern=$key;
1.156     www      8227:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8228:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8229:                         $pattern=~s/\//\\\//g;
1.152     www      8230:                         if ($orguri=~/$pattern/) {
1.800     albertel 8231: 			    $refuri=$env{$key};
1.148     www      8232:                         }
                   8233:                     }
1.191     harris41 8234:                 }
1.148     www      8235:             }
1.232     www      8236: 
1.148     www      8237:          if ($refuri) { 
1.152     www      8238: 	  $refuri=&declutter($refuri);
1.232     www      8239:           my ($match,$cond)=&is_on_map($refuri);
                   8240:             if ($match) {
                   8241:               my $refstatecond=$cond;
1.620     albertel 8242:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8243:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8244:                   my $value = $1;
                   8245:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8246:                       if ($noblockcheck) {
1.1162    raeburn  8247:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8248:                       } else {
1.1172.2.127  raeburn  8249:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8250:                           if (@blockers > 0) {
                   8251:                               $thisallowed = 'B';
                   8252:                           } else {
                   8253:                               $thisallowed.=$value;
                   8254:                           }
1.1162    raeburn  8255:                       }
                   8256:                   } else {
                   8257:                       $thisallowed.=$value;
                   8258:                   }
1.53      www      8259:                   $uri=$refuri;
                   8260:                   $statecond=$refstatecond;
1.52      www      8261:               }
                   8262:           }
1.148     www      8263:         }
1.29      www      8264:        }
1.52      www      8265:    }
1.29      www      8266: 
1.52      www      8267: #
1.103     harris41 8268: # Gathered now: all privileges that could apply, and condition number
1.52      www      8269: # 
                   8270: #
                   8271: # Full or no access?
                   8272: #
1.29      www      8273: 
1.52      www      8274:     if ($thisallowed=~/F/) {
                   8275: 	return 'F';
                   8276:     }
1.29      www      8277: 
1.52      www      8278:     unless ($thisallowed) {
                   8279:         return '';
                   8280:     }
1.29      www      8281: 
1.52      www      8282: # Restrictions exist, deal with them
                   8283: #
                   8284: #   C:according to course preferences
                   8285: #   R:according to resource settings
                   8286: #   L:unless locked
                   8287: #   X:according to user session state
                   8288: #
                   8289: 
                   8290: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8291: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8292: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8293: # courses, and 2 minutes for current course, in which user has st or ta role
                   8294: # which is neither expired nor a future role (unless current course).
1.52      www      8295: 
1.1172.2.142  raeburn  8296:     my ($needlockcheck,$now,$crsonly);
1.52      www      8297:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8298:         $now = time;
                   8299:         if ($priv eq 'bre') {
                   8300:             if ($uri ne '') {
                   8301:                 if ($orguri =~ m{^/+res/}) {
                   8302:                     if ($uri =~ m{^lib/templates/}) {
                   8303:                         if ($env{'request.course.id'}) {
                   8304:                             $crsonly = 1;
                   8305:                             $needlockcheck = 1;
                   8306:                         }
                   8307:                     } else {
                   8308:                         $needlockcheck = 1;
                   8309:                     }
                   8310:                 } elsif ($env{'request.course.id'}) {
                   8311:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8312:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8313:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8314:                         $crsonly = 1;
                   8315:                     }
                   8316:                     $needlockcheck = 1;
                   8317:                 }
                   8318:             }
                   8319:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8320:             $needlockcheck = 1;
                   8321:         }
                   8322:     }
                   8323:     if ($needlockcheck) {
                   8324:         foreach my $envkey (keys(%env)) {
1.54      www      8325:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8326:                my $courseid=$2;
                   8327:                my $roleid=$1.'.'.$2;
1.92      www      8328:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8329:                unless ($env{'request.role'} eq $roleid) {
                   8330:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8331:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8332:                }
1.54      www      8333:                my $expiretime=600;
1.620     albertel 8334:                if ($env{'request.role'} eq $roleid) {
1.54      www      8335: 		  $expiretime=120;
                   8336:                }
                   8337: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8338:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8339:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8340: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8341:                }
1.620     albertel 8342:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8343:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8344: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8345:                        &log($env{'user.domain'},$env{'user.name'},
                   8346:                             $env{'user.home'},
1.57      www      8347:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8348:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8349:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8350: 		       return '';
                   8351:                    }
                   8352:                }
1.620     albertel 8353:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8354:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8355: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8356:                        &log($env{'user.domain'},$env{'user.name'},
                   8357:                             $env{'user.home'},
1.57      www      8358:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8359:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8360:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8361: 		       return '';
                   8362:                    }
                   8363:                }
                   8364: 	   }
1.29      www      8365:        }
1.52      www      8366:     }
1.1172.2.126  raeburn  8367: 
1.52      www      8368: #
                   8369: # Rest of the restrictions depend on selected course
                   8370: #
                   8371: 
1.620     albertel 8372:     unless ($env{'request.course.id'}) {
1.766     albertel 8373: 	if ($thisallowed eq 'A') {
                   8374: 	    return 'A';
1.814     raeburn  8375:         } elsif ($thisallowed eq 'B') {
                   8376:             return 'B';
1.766     albertel 8377: 	} else {
                   8378: 	    return '1';
                   8379: 	}
1.52      www      8380:     }
1.29      www      8381: 
1.52      www      8382: #
                   8383: # Now user is definitely in a course
                   8384: #
1.53      www      8385: 
                   8386: 
                   8387: # Course preferences
                   8388: 
                   8389:    if ($thisallowed=~/C/) {
1.620     albertel 8390:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8391:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8392:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8393: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8394: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8395: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8396: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8397: 			$env{'request.course.id'});
                   8398: 	   }
1.237     www      8399:            return '';
                   8400:        }
                   8401: 
1.620     albertel 8402:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8403: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8404: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8405: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8406: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8407: 			$env{'request.course.id'});
                   8408: 	   }
1.54      www      8409:            return '';
                   8410:        }
1.53      www      8411:    }
                   8412: 
                   8413: # Resource preferences
                   8414: 
                   8415:    if ($thisallowed=~/R/) {
1.620     albertel 8416:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8417:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8418: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8419: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8420: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8421: 	   }
                   8422: 	   return '';
1.54      www      8423:        }
1.53      www      8424:    }
1.30      www      8425: 
1.246     www      8426: # Restricted by state or randomout?
1.30      www      8427: 
1.52      www      8428:    if ($thisallowed=~/X/) {
1.620     albertel 8429:       if ($env{'acc.randomout'}) {
1.579     albertel 8430: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8431:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8432:             return ''; 
                   8433:          }
1.247     www      8434:       }
                   8435:       if (&condval($statecond)) {
1.52      www      8436: 	 return '2';
                   8437:       } else {
                   8438:          return '';
                   8439:       }
                   8440:    }
1.30      www      8441: 
1.766     albertel 8442:     if ($thisallowed eq 'A') {
                   8443: 	return 'A';
1.814     raeburn  8444:     } elsif ($thisallowed eq 'B') {
                   8445:         return 'B';
1.766     albertel 8446:     }
1.52      www      8447:    return 'F';
1.232     www      8448: }
1.1162    raeburn  8449: 
1.1172.2.13  raeburn  8450: # ------------------------------------------- Check construction space access
                   8451: 
                   8452: sub constructaccess {
                   8453:     my ($url,$setpriv)=@_;
                   8454: 
                   8455: # We do not allow editing of previous versions of files
                   8456:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8457: 
                   8458: # Get username and domain from URL
                   8459:     my ($ownername,$ownerdomain,$ownerhome);
                   8460: 
                   8461:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8462:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8463: 
                   8464: # The URL does not really point to any authorspace, forget it
                   8465:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8466: 
                   8467: # Now we need to see if the user has access to the authorspace of
                   8468: # $ownername at $ownerdomain
                   8469: 
                   8470:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8471: # Real author for this?
                   8472:        $ownerhome = $env{'user.home'};
                   8473:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8474:           return ($ownername,$ownerdomain,$ownerhome);
                   8475:        }
                   8476:     } else {
                   8477: # Co-author for this?
                   8478:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8479:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8480:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8481:             return ($ownername,$ownerdomain,$ownerhome);
                   8482:         }
                   8483:     }
                   8484: 
                   8485: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8486: # we might as well leave
                   8487:    unless ($setpriv) { return ''; }
                   8488: 
                   8489: # Backdoor access?
                   8490:     my $allowed=&allowed('eco',$ownerdomain);
                   8491: # Nope
                   8492:     unless ($allowed) { return ''; }
                   8493: # Looks like we may have access, but could be locked by the owner of the construction space
                   8494:     if ($allowed eq 'U') {
                   8495:         my %blocked=&get('environment',['domcoord.author'],
                   8496:                          $ownerdomain,$ownername);
                   8497: # Is blocked by owner
                   8498:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8499:     }
                   8500:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8501: # Grant temporary access
                   8502:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8503:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8504:         if (!$update) { $update = $then; }
                   8505:         my $refresh=$env{'user.refresh.time'};
                   8506:         if (!$refresh) { $refresh = $update; }
                   8507:         my $now = time;
                   8508:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8509:                            $now,'ca','constructaccess');
                   8510:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8511:         return($ownername,$ownerdomain,$ownerhome);
                   8512:     }
                   8513: # No business here
                   8514:     return '';
                   8515: }
                   8516: 
1.1172.2.66  raeburn  8517: # ----------------------------------------------------------- Content Blocking
                   8518: 
                   8519: {
                   8520: # Caches for faster Course Contents display where content blocking
                   8521: # is in operation (i.e., interval param set) for timed quiz.
                   8522: #
                   8523: # User for whom data are being temporarily cached.
                   8524: my $cacheduser='';
1.1172.2.126  raeburn  8525: # Course for which data are being temporarily cached.
                   8526: my $cachedcid='';
1.1172.2.66  raeburn  8527: # Cached blockers for this user (a hash of blocking items).
                   8528: my %cachedblockers=();
                   8529: # When the data were last cached.
                   8530: my $cachedlast='';
                   8531: 
                   8532: sub load_all_blockers {
1.1172.2.128  raeburn  8533:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8534:     if (($uname ne '') && ($udom ne '')) {
                   8535:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8536:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8537:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8538:             return;
                   8539:         }
                   8540:     }
                   8541:     $cachedlast=time;
                   8542:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8543:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8544:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8545:     return;
1.1172.2.66  raeburn  8546: }
                   8547: 
1.1162    raeburn  8548: sub get_comm_blocks {
                   8549:     my ($cdom,$cnum) = @_;
                   8550:     if ($cdom eq '' || $cnum eq '') {
                   8551:         return unless ($env{'request.course.id'});
                   8552:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8553:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8554:     }
                   8555:     my %commblocks;
                   8556:     my $hashid=$cdom.'_'.$cnum;
                   8557:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8558:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8559:         %commblocks = %{$blocksref};
                   8560:     } else {
                   8561:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8562:         my $cachetime = 600;
                   8563:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8564:     }
                   8565:     return %commblocks;
                   8566: }
                   8567: 
1.1172.2.66  raeburn  8568: sub get_commblock_resources {
                   8569:     my ($blocks) = @_;
                   8570:     my %blockers = ();
                   8571:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8572:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8573:     if ($env{'request.course.sec'}) {
                   8574:         $courseurl .= '/'.$env{'request.course.sec'};
                   8575:     }
                   8576:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8577:     my %commblocks;
                   8578:     if (ref($blocks) eq 'HASH') {
                   8579:         %commblocks = %{$blocks};
                   8580:     } else {
                   8581:         %commblocks = &get_comm_blocks();
                   8582:     }
1.1172.2.66  raeburn  8583:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8584:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8585:     return %blockers unless (ref($navmap));
                   8586:     my $now = time;
1.1162    raeburn  8587:     foreach my $block (keys(%commblocks)) {
                   8588:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8589:             my ($start,$end) = ($1,$2);
                   8590:             if ($start <= $now && $end >= $now) {
                   8591:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8592:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8593:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8594:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8595:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8596:                             }
                   8597:                         }
                   8598:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8599:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8600:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8601:                             }
                   8602:                         }
                   8603:                     }
                   8604:                 }
                   8605:             }
                   8606:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8607:             my $item = $1;
                   8608:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8609:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8610:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8611:                     my $type = 'map';
                   8612:                     if ($item eq 'course') {
                   8613:                         $type = 'course';
                   8614:                         @interval=&EXT("resource.0.interval");
                   8615:                     } else {
                   8616:                         if ($item =~ /___\d+___/) {
                   8617:                             $type = 'resource';
                   8618:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8619:                         } else {
1.1172.2.142  raeburn  8620:                             $mapname = &deversion($item);
                   8621:                             if (ref($navmap)) {
                   8622:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8623:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8624:                             }
                   8625:                         }
1.1172.2.66  raeburn  8626:                     }
                   8627:                     if ($interval[0] =~ /^\d+$/) {
                   8628:                         my $first_access;
                   8629:                         if ($type eq 'resource') {
                   8630:                             $first_access=&get_first_access($interval[1],$item);
                   8631:                         } elsif ($type eq 'map') {
                   8632:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8633:                         } else {
                   8634:                             $first_access=&get_first_access($interval[1]);
                   8635:                         }
                   8636:                         if ($first_access) {
                   8637:                             my $timesup = $first_access+$interval[0];
                   8638:                             if ($timesup > $now) {
                   8639:                                 my $activeblock;
1.1172.2.142  raeburn  8640:                                 if ($type eq 'resource') {
                   8641:                                     if (ref($navmap)) {
                   8642:                                         my $res = $navmap->getBySymb($item);
                   8643:                                         if ($res->answerable()) {
                   8644:                                             $activeblock = 1;
                   8645:                                         }
                   8646:                                     }
                   8647:                                 } elsif ($type eq 'map') {
                   8648:                                     my $mapsymb = &symbread($mapname,1);
                   8649:                                     if (($mapsymb) && (ref($navmap))) {
                   8650:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8651:                                         if (ref($mapres)) {
                   8652:                                             my $first = $mapres->map_start();
                   8653:                                             my $finish = $mapres->map_finish();
                   8654:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8655:                                             if (ref($it)) {
                   8656:                                                 my $res;
                   8657:                                                 while ($res = $it->next(undef,1)) {
                   8658:                                                     next unless (ref($res));
                   8659:                                                     my $symb = $res->symb();
                   8660:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8661:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8662:                                                     if ($interval[1] eq 'map') {
                   8663:                                                         if ($res->answerable()) {
                   8664:                                                             $activeblock = 1;
                   8665:                                                             last;
                   8666:                                                         }
                   8667:                                                     }
                   8668:                                                 }
                   8669:                                             }
                   8670:                                         }
1.1172.2.66  raeburn  8671:                                     }
                   8672:                                 }
                   8673:                                 if ($activeblock) {
                   8674:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8675:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8676:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8677:                                          }
                   8678:                                     }
                   8679:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8680:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8681:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8682:                                         }
1.1162    raeburn  8683:                                     }
                   8684:                                 }
                   8685:                             }
                   8686:                         }
                   8687:                     }
                   8688:                 }
                   8689:             }
                   8690:         }
                   8691:     }
1.1172.2.66  raeburn  8692:     return %blockers;
1.1162    raeburn  8693: }
                   8694: 
1.1172.2.66  raeburn  8695: sub has_comm_blocking {
1.1172.2.128  raeburn  8696:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8697:     my @blockers;
                   8698:     return unless ($env{'request.course.id'});
                   8699:     return unless ($priv eq 'bre');
                   8700:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8701:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8702:     if ($env{'request.course.sec'}) {
                   8703:         $courseurl .= '/'.$env{'request.course.sec'};
                   8704:     }
                   8705:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8706:     my %blockinfo;
                   8707:     if (ref($blocks) eq 'HASH') {
                   8708:         %blockinfo = &get_commblock_resources($blocks);
                   8709:     } else {
                   8710:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8711:         %blockinfo = %cachedblockers;
                   8712:     }
                   8713:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8714:     my (%possibles,@symbs);
                   8715:     if (!$symb) {
1.1172.2.128  raeburn  8716:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8717:     }
1.1172.2.66  raeburn  8718:     if ($symb) {
                   8719:         @symbs = ($symb);
                   8720:     } elsif (keys(%possibles)) {
                   8721:         @symbs = keys(%possibles);
                   8722:     }
                   8723:     my $noblock;
                   8724:     foreach my $symb (@symbs) {
                   8725:         last if ($noblock);
                   8726:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8727:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8728:             if ($block =~ /^firstaccess____(.+)$/) {
                   8729:                 my $item = $1;
1.1172.2.126  raeburn  8730:                 unless ($blocked) {
                   8731:                     if (($item eq $map) || ($item eq $symb)) {
                   8732:                         $noblock = 1;
                   8733:                         last;
                   8734:                     }
1.1172.2.66  raeburn  8735:                 }
1.1162    raeburn  8736:             }
1.1172.2.128  raeburn  8737:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8738:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8739:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8740:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8741:                             push(@blockers,$block);
                   8742:                         }
                   8743:                     }
                   8744:                 }
1.1172.2.128  raeburn  8745:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8746:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8747:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8748:                             push(@blockers,$block);
                   8749:                         }
1.1172.2.66  raeburn  8750:                     }
                   8751:                 }
1.1162    raeburn  8752:             }
                   8753:         }
                   8754:     }
1.1172.2.126  raeburn  8755:     unless ($noblock) {
                   8756:         return @blockers;
                   8757:     }
                   8758:     return;
1.1172.2.66  raeburn  8759: }
1.1162    raeburn  8760: }
                   8761: 
1.1172.2.66  raeburn  8762: # -------------------------------- Deversion and split uri into path an filename
                   8763: 
1.1133    foxr     8764: #
1.1172.2.66  raeburn  8765: #   Removes the version from a URI and
1.1133    foxr     8766: #   splits it in to its filename and path to the filename.
                   8767: #   Seems like File::Basename could have done this more clearly.
                   8768: #   Parameters:
                   8769: #      $uri   - input URI
                   8770: #   Returns:
                   8771: #     Two element list consisting of 
                   8772: #     $pathname  - the URI up to and excluding the trailing /
                   8773: #     $filename  - The part of the URI following the last /
                   8774: #  NOTE:
                   8775: #    Another realization of this is simply:
                   8776: #    use File::Basename;
                   8777: #    ...
                   8778: #    $uri = shift;
                   8779: #    $filename = basename($uri);
                   8780: #    $path     = dirname($uri);
                   8781: #    return ($filename, $path);
                   8782: #
                   8783: #     The implementation below is probably faster however.
                   8784: #
1.710     albertel 8785: sub split_uri_for_cond {
                   8786:     my $uri=&deversion(&declutter(shift));
                   8787:     my @uriparts=split(/\//,$uri);
                   8788:     my $filename=pop(@uriparts);
                   8789:     my $pathname=join('/',@uriparts);
                   8790:     return ($pathname,$filename);
                   8791: }
1.232     www      8792: # --------------------------------------------------- Is a resource on the map?
                   8793: 
                   8794: sub is_on_map {
1.710     albertel 8795:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8796:     #Trying to find the conditional for the file
1.620     albertel 8797:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8798: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8799:     if ($match) {
1.289     bowersj2 8800: 	return (1,$1);
                   8801:     } else {
1.434     www      8802: 	return (0,0);
1.289     bowersj2 8803:     }
1.12      www      8804: }
                   8805: 
1.427     www      8806: # --------------------------------------------------------- Get symb from alias
                   8807: 
                   8808: sub get_symb_from_alias {
                   8809:     my $symb=shift;
                   8810:     my ($map,$resid,$url)=&decode_symb($symb);
                   8811: # Already is a symb
                   8812:     if ($url) { return $symb; }
                   8813: # Must be an alias
                   8814:     my $aliassymb='';
                   8815:     my %bighash;
1.620     albertel 8816:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8817:                             &GDBM_READER(),0640)) {
                   8818:         my $rid=$bighash{'mapalias_'.$symb};
                   8819: 	if ($rid) {
                   8820: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8821: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8822: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8823: 	}
                   8824:         untie %bighash;
                   8825:     }
                   8826:     return $aliassymb;
                   8827: }
                   8828: 
1.12      www      8829: # ----------------------------------------------------------------- Define Role
                   8830: 
                   8831: sub definerole {
                   8832:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8833:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8834:     foreach my $role (split(':',$sysrole)) {
                   8835: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8836:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8837:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8838: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8839:                return "refused:s:$crole&$cqual"; 
                   8840:             }
                   8841:         }
1.191     harris41 8842:     }
1.800     albertel 8843:     foreach my $role (split(':',$domrole)) {
                   8844: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8845:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8846:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8847: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8848:                return "refused:d:$crole&$cqual"; 
                   8849:             }
                   8850:         }
1.191     harris41 8851:     }
1.800     albertel 8852:     foreach my $role (split(':',$courole)) {
                   8853: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8854:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8855:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8856: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8857:                return "refused:c:$crole&$cqual"; 
                   8858:             }
                   8859:         }
1.191     harris41 8860:     }
1.1172.2.84  raeburn  8861:     my $uhome;
                   8862:     if (($uname ne '') && ($udom ne '')) {
                   8863:         $uhome = &homeserver($uname,$udom);
                   8864:         return $uhome if ($uhome eq 'no_host');
                   8865:     } else {
                   8866:         $uname = $env{'user.name'};
                   8867:         $udom = $env{'user.domain'};
                   8868:         $uhome = $env{'user.home'};
                   8869:     }
1.620     albertel 8870:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8871:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8872:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8873:     return reply($command,$uhome);
1.12      www      8874:   } else {
                   8875:     return 'refused';
                   8876:   }
1.105     harris41 8877: }
                   8878: 
                   8879: # ---------------- Make a metadata query against the network of library servers
                   8880: 
                   8881: sub metadata_query {
1.1172.2.33  raeburn  8882:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8883:     my %rhash;
1.845     albertel 8884:     my %libserv = &all_library();
1.244     matthew  8885:     my @server_list = (defined($server_array) ? @$server_array
                   8886:                                               : keys(%libserv) );
                   8887:     for my $server (@server_list) {
1.1172.2.33  raeburn  8888:         my $domains = '';
                   8889:         if (ref($domains_hash) eq 'HASH') {
                   8890:             $domains = $domains_hash->{$server};    
                   8891:         }
1.118     harris41 8892: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8893: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8894: 	    $rhash{$server}=$reply;
                   8895: 	}
                   8896: 	else {
                   8897: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8898: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8899: 			     $server);
                   8900: 	    $rhash{$server}=$reply;
                   8901: 	}
1.112     harris41 8902:     }
1.118     harris41 8903:     return \%rhash;
1.240     www      8904: }
                   8905: 
                   8906: # ----------------------------------------- Send log queries and wait for reply
                   8907: 
                   8908: sub log_query {
                   8909:     my ($uname,$udom,$query,%filters)=@_;
                   8910:     my $uhome=&homeserver($uname,$udom);
                   8911:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8912:     my $uhost=&hostname($uhome);
1.800     albertel 8913:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8914:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8915:                        $uhome);
1.479     albertel 8916:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8917:     return get_query_reply($queryid);
                   8918: }
                   8919: 
1.818     raeburn  8920: # -------------------------- Update MySQL table for portfolio file
                   8921: 
                   8922: sub update_portfolio_table {
1.821     raeburn  8923:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8924:     if ($group ne '') {
                   8925:         $file_name =~s /^\Q$group\E//;
                   8926:     }
1.818     raeburn  8927:     my $homeserver = &homeserver($uname,$udom);
                   8928:     my $queryid=
1.821     raeburn  8929:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8930:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8931:     my $reply = &get_query_reply($queryid);
                   8932:     return $reply;
                   8933: }
                   8934: 
1.899     raeburn  8935: # -------------------------- Update MySQL allusers table
                   8936: 
                   8937: sub update_allusers_table {
                   8938:     my ($uname,$udom,$names) = @_;
                   8939:     my $homeserver = &homeserver($uname,$udom);
                   8940:     my $queryid=
                   8941:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8942:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8943:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8944:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8945:                'generation='.&escape($names->{'generation'}).'%%'.
                   8946:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8947:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8948:     return;
1.899     raeburn  8949: }
                   8950: 
1.508     raeburn  8951: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8952: 
                   8953: sub fetch_enrollment_query {
1.511     raeburn  8954:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8955:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8956:     my $maxtries = 1;
1.508     raeburn  8957:     if ($context eq 'automated') {
                   8958:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8959:         $sleep = 2;
                   8960:         $loopmax = 100;
1.547     raeburn  8961:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8962:     } else {
                   8963:         $homeserver = &homeserver($cnum,$dom);
                   8964:     }
1.838     albertel 8965:     my $host=&hostname($homeserver);
1.506     raeburn  8966:     my $cmd = '';
1.1000    raeburn  8967:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8968:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8969:     }
                   8970:     $cmd =~ s/%%$//;
                   8971:     $cmd = &escape($cmd);
                   8972:     my $query = 'fetchenrollment';
1.620     albertel 8973:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8974:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8975:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8976:         return 'error: '.$queryid;
                   8977:     }
1.1172.2.93  raeburn  8978:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8979:     my $tries = 1;
                   8980:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8981:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8982:         $tries ++;
                   8983:     }
1.526     raeburn  8984:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8985:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8986:     } else {
1.901     albertel 8987:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8988:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8989:             foreach my $line (@responses) {
                   8990:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8991:                 $$replyref{$key} = $value;
                   8992:             }
                   8993:         } else {
1.1117    foxr     8994:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8995:             foreach my $line (@responses) {
                   8996:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8997:                 $$replyref{$key} = $value;
                   8998:                 if ($value > 0) {
1.800     albertel 8999:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9000:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9001:                         my $destname = $pathname.'/'.$filename;
                   9002:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9003:                         if ($xml_classlist =~ /^error/) {
                   9004:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9005:                         } else {
1.1172.2.96  raeburn  9006:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9007:                                 print FILE &unescape($xml_classlist);
                   9008:                                 close(FILE);
1.526     raeburn  9009:                             } else {
                   9010:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9011:                             }
                   9012:                         }
                   9013:                     }
                   9014:                 }
                   9015:             }
                   9016:         }
                   9017:         return 'ok';
                   9018:     }
                   9019:     return 'error';
                   9020: }
                   9021: 
1.242     www      9022: sub get_query_reply {
1.1172.2.79  raeburn  9023:     my ($queryid,$sleep,$loopmax) = @_;
                   9024:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9025:         $sleep = 0.2;
                   9026:     }
                   9027:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9028:         $loopmax = 100;
                   9029:     }
1.1117    foxr     9030:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9031:     my $reply='';
1.1172.2.79  raeburn  9032:     for (1..$loopmax) {
                   9033: 	sleep($sleep);
1.240     www      9034:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9035: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9036: 		$reply = join('',<$fh>);
                   9037: 		close($fh);
1.240     www      9038: 	   } else { return 'error: reply_file_error'; }
1.242     www      9039:            return &unescape($reply);
                   9040: 	}
1.240     www      9041:     }
1.242     www      9042:     return 'timeout:'.$queryid;
1.240     www      9043: }
                   9044: 
                   9045: sub courselog_query {
1.241     www      9046: #
                   9047: # possible filters:
                   9048: # url: url or symb
                   9049: # username
                   9050: # domain
                   9051: # action: view, submit, grade
                   9052: # start: timestamp
                   9053: # end: timestamp
                   9054: #
1.240     www      9055:     my (%filters)=@_;
1.620     albertel 9056:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9057:     if ($filters{'url'}) {
                   9058: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9059:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9060:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9061:     }
1.620     albertel 9062:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9064:     return &log_query($cname,$cdom,'courselog',%filters);
                   9065: }
                   9066: 
                   9067: sub userlog_query {
1.858     raeburn  9068: #
                   9069: # possible filters:
                   9070: # action: log check role
                   9071: # start: timestamp
                   9072: # end: timestamp
                   9073: #
1.240     www      9074:     my ($uname,$udom,%filters)=@_;
                   9075:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9076: }
                   9077: 
1.506     raeburn  9078: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9079: 
                   9080: sub auto_run {
1.508     raeburn  9081:     my ($cnum,$cdom) = @_;
1.876     raeburn  9082:     my $response = 0;
                   9083:     my $settings;
                   9084:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9085:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9086:         $settings = $domconfig{'autoenroll'};
                   9087:         if ($settings->{'run'} eq '1') {
                   9088:             $response = 1;
                   9089:         }
                   9090:     } else {
1.934     raeburn  9091:         my $homeserver;
                   9092:         if (&is_course($cdom,$cnum)) {
                   9093:             $homeserver = &homeserver($cnum,$cdom);
                   9094:         } else {
                   9095:             $homeserver = &domain($cdom,'primary');
                   9096:         }
                   9097:         if ($homeserver ne 'no_host') {
                   9098:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9099:         }
1.876     raeburn  9100:     }
1.506     raeburn  9101:     return $response;
                   9102: }
1.776     albertel 9103: 
1.506     raeburn  9104: sub auto_get_sections {
1.508     raeburn  9105:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9106:     my $homeserver;
                   9107:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9108:         $homeserver = &homeserver($cnum,$cdom);
                   9109:     }
                   9110:     if (!defined($homeserver)) { 
                   9111:         if ($cdom =~ /^$match_domain$/) {
                   9112:             $homeserver = &domain($cdom,'primary');
                   9113:         }
                   9114:     }
                   9115:     my @secs;
                   9116:     if (defined($homeserver)) {
                   9117:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9118:         unless ($response eq 'refused') {
                   9119:             @secs = split(/:/,$response);
                   9120:         }
1.506     raeburn  9121:     }
                   9122:     return @secs;
                   9123: }
1.776     albertel 9124: 
1.506     raeburn  9125: sub auto_new_course {
1.1099    raeburn  9126:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9127:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9128:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9129:     return $response;
                   9130: }
1.776     albertel 9131: 
1.506     raeburn  9132: sub auto_validate_courseID {
1.508     raeburn  9133:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9134:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9135:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9136:     return $response;
                   9137: }
1.776     albertel 9138: 
1.1007    raeburn  9139: sub auto_validate_instcode {
1.1020    raeburn  9140:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9141:     my ($homeserver,$response);
                   9142:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9143:         $homeserver = &homeserver($cnum,$cdom);
                   9144:     }
                   9145:     if (!defined($homeserver)) {
                   9146:         if ($cdom =~ /^$match_domain$/) {
                   9147:             $homeserver = &domain($cdom,'primary');
                   9148:         }
                   9149:     }
1.1065    raeburn  9150:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9151:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9152:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9153:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9154: }
                   9155: 
1.1172.2.141  raeburn  9156: sub auto_validate_inst_crosslist {
                   9157:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9158:     my ($homeserver,$response);
                   9159:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9160:         $homeserver = &homeserver($cnum,$cdom);
                   9161:     }
                   9162:     if (!defined($homeserver)) {
                   9163:         if ($cdom =~ /^$match_domain$/) {
                   9164:             $homeserver = &domain($cdom,'primary');
                   9165:         }
                   9166:     }
                   9167:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9168:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9169:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9170:                          &escape($coowner),$homeserver);
                   9171:     }
                   9172:     return $response;
                   9173: }
                   9174: 
1.506     raeburn  9175: sub auto_create_password {
1.873     raeburn  9176:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9177:     my ($homeserver,$response);
1.506     raeburn  9178:     my $create_passwd = 0;
                   9179:     my $authchk = '';
1.873     raeburn  9180:     if ($udom =~ /^$match_domain$/) {
                   9181:         $homeserver = &domain($udom,'primary');
                   9182:     }
                   9183:     if ($homeserver eq '') {
                   9184:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9185:             $homeserver = &homeserver($cnum,$cdom);
                   9186:         }
                   9187:     }
                   9188:     if ($homeserver eq '') {
                   9189:         $authchk = 'nodomain';
1.506     raeburn  9190:     } else {
1.873     raeburn  9191:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9192:         if ($response eq 'refused') {
                   9193:             $authchk = 'refused';
                   9194:         } else {
1.901     albertel 9195:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9196:         }
1.506     raeburn  9197:     }
                   9198:     return ($authparam,$create_passwd,$authchk);
                   9199: }
                   9200: 
1.706     raeburn  9201: sub auto_photo_permission {
                   9202:     my ($cnum,$cdom,$students) = @_;
                   9203:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9204:     my ($outcome,$perm_reqd,$conditions) = 
                   9205: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9206:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9207: 	return (undef,undef);
                   9208:     }
1.706     raeburn  9209:     return ($outcome,$perm_reqd,$conditions);
                   9210: }
                   9211: 
                   9212: sub auto_checkphotos {
                   9213:     my ($uname,$udom,$pid) = @_;
                   9214:     my $homeserver = &homeserver($uname,$udom);
                   9215:     my ($result,$resulttype);
                   9216:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9217: 				   &escape($uname).':'.&escape($pid),
                   9218: 				   $homeserver));
1.709     albertel 9219:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9220: 	return (undef,undef);
                   9221:     }
1.706     raeburn  9222:     if ($outcome) {
                   9223:         ($result,$resulttype) = split(/:/,$outcome);
                   9224:     } 
                   9225:     return ($result,$resulttype);
                   9226: }
                   9227: 
                   9228: sub auto_photochoice {
                   9229:     my ($cnum,$cdom) = @_;
                   9230:     my $homeserver = &homeserver($cnum,$cdom);
                   9231:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9232: 						       &escape($cdom),
                   9233: 						       $homeserver)));
1.709     albertel 9234:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9235: 	return (undef,undef);
                   9236:     }
1.706     raeburn  9237:     return ($update,$comment);
                   9238: }
                   9239: 
                   9240: sub auto_photoupdate {
                   9241:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9242:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9243:     my $host=&hostname($homeserver);
1.706     raeburn  9244:     my $cmd = '';
                   9245:     my $maxtries = 1;
1.800     albertel 9246:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9247:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9248:     }
                   9249:     $cmd =~ s/%%$//;
                   9250:     $cmd = &escape($cmd);
                   9251:     my $query = 'institutionalphotos';
                   9252:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9253:     unless ($queryid=~/^\Q$host\E\_/) {
                   9254:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9255:         return 'error: '.$queryid;
                   9256:     }
                   9257:     my $reply = &get_query_reply($queryid);
                   9258:     my $tries = 1;
                   9259:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9260:         $reply = &get_query_reply($queryid);
                   9261:         $tries ++;
                   9262:     }
                   9263:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9264:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9265:     } else {
                   9266:         my @responses = split(/:/,$reply);
                   9267:         my $outcome = shift(@responses); 
                   9268:         foreach my $item (@responses) {
                   9269:             my ($key,$value) = split(/=/,$item);
                   9270:             $$photo{$key} = $value;
                   9271:         }
                   9272:         return $outcome;
                   9273:     }
                   9274:     return 'error';
                   9275: }
                   9276: 
1.521     raeburn  9277: sub auto_instcode_format {
1.793     albertel 9278:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9279: 	$cat_order) = @_;
1.521     raeburn  9280:     my $courses = '';
1.772     raeburn  9281:     my @homeservers;
1.521     raeburn  9282:     if ($caller eq 'global') {
1.841     albertel 9283: 	my %servers = &get_servers($codedom,'library');
                   9284: 	foreach my $tryserver (keys(%servers)) {
                   9285: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9286: 		push(@homeservers,$tryserver);
                   9287: 	    }
1.584     raeburn  9288:         }
1.1022    raeburn  9289:     } elsif ($caller eq 'requests') {
                   9290:         if ($codedom =~ /^$match_domain$/) {
                   9291:             my $chome = &domain($codedom,'primary');
                   9292:             unless ($chome eq 'no_host') {
                   9293:                 push(@homeservers,$chome);
                   9294:             }
                   9295:         }
1.521     raeburn  9296:     } else {
1.772     raeburn  9297:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9298:     }
1.793     albertel 9299:     foreach my $code (keys(%{$instcodes})) {
                   9300:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9301:     }
                   9302:     chop($courses);
1.772     raeburn  9303:     my $ok_response = 0;
                   9304:     my $response;
                   9305:     while (@homeservers > 0 && $ok_response == 0) {
                   9306:         my $server = shift(@homeservers); 
                   9307:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9308:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9309:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9310: 		split(/:/,$response);
1.772     raeburn  9311:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9312:             push(@{$codetitles},&str2array($codetitles_str));
                   9313:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9314:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9315:             $ok_response = 1;
                   9316:         }
                   9317:     }
                   9318:     if ($ok_response) {
1.521     raeburn  9319:         return 'ok';
1.772     raeburn  9320:     } else {
                   9321:         return $response;
1.521     raeburn  9322:     }
                   9323: }
                   9324: 
1.792     raeburn  9325: sub auto_instcode_defaults {
                   9326:     my ($domain,$returnhash,$code_order) = @_;
                   9327:     my @homeservers;
1.841     albertel 9328: 
                   9329:     my %servers = &get_servers($domain,'library');
                   9330:     foreach my $tryserver (keys(%servers)) {
                   9331: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9332: 	    push(@homeservers,$tryserver);
                   9333: 	}
1.792     raeburn  9334:     }
1.841     albertel 9335: 
1.792     raeburn  9336:     my $response;
1.841     albertel 9337:     foreach my $server (@homeservers) {
1.792     raeburn  9338:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9339:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9340: 	
                   9341: 	foreach my $pair (split(/\&/,$response)) {
                   9342: 	    my ($name,$value)=split(/\=/,$pair);
                   9343: 	    if ($name eq 'code_order') {
                   9344: 		@{$code_order} = split(/\&/,&unescape($value));
                   9345: 	    } else {
                   9346: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9347: 	    }
                   9348: 	}
                   9349: 	return 'ok';
1.792     raeburn  9350:     }
1.841     albertel 9351: 
                   9352:     return $response;
1.1003    raeburn  9353: }
                   9354: 
                   9355: sub auto_possible_instcodes {
1.1007    raeburn  9356:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9357:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9358:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9359:         return;
                   9360:     }
1.1003    raeburn  9361:     my (@homeservers,$uhome);
                   9362:     if (defined(&domain($domain,'primary'))) {
                   9363:         $uhome=&domain($domain,'primary');
                   9364:         push(@homeservers,&domain($domain,'primary'));
                   9365:     } else {
                   9366:         my %servers = &get_servers($domain,'library');
                   9367:         foreach my $tryserver (keys(%servers)) {
                   9368:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9369:                 push(@homeservers,$tryserver);
                   9370:             }
                   9371:         }
                   9372:     }
                   9373:     my $response;
                   9374:     foreach my $server (@homeservers) {
                   9375:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9376:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9377:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9378:             split(':',$response);
                   9379:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9380:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9381:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9382:             my ($name,$value)=split('=',$item);
                   9383:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9384:         }
                   9385:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9386:             my ($name,$value)=split('=',$item);
                   9387:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9388:         }
                   9389:         return 'ok';
                   9390:     }
                   9391:     return $response;
                   9392: }
1.792     raeburn  9393: 
1.1010    raeburn  9394: sub auto_courserequest_checks {
                   9395:     my ($dom) = @_;
1.1020    raeburn  9396:     my ($homeserver,%validations);
                   9397:     if ($dom =~ /^$match_domain$/) {
                   9398:         $homeserver = &domain($dom,'primary');
                   9399:     }
                   9400:     unless ($homeserver eq 'no_host') {
                   9401:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9402:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9403:             my @items = split(/&/,$response);
                   9404:             foreach my $item (@items) {
                   9405:                 my ($key,$value) = split('=',$item);
                   9406:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9407:             }
                   9408:         }
                   9409:     }
1.1010    raeburn  9410:     return %validations; 
                   9411: }
                   9412: 
1.1020    raeburn  9413: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9414:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9415:     my ($homeserver,$response);
                   9416:     if ($dom =~ /^$match_domain$/) {
                   9417:         $homeserver = &domain($dom,'primary');
                   9418:     }
1.1172.2.43  raeburn  9419:     unless ($homeserver eq 'no_host') {
                   9420:         my $customdata;
                   9421:         if (ref($custominfo) eq 'HASH') {
                   9422:             $customdata = &freeze_escape($custominfo);
                   9423:         }
1.1020    raeburn  9424:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9425:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9426:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9427:                                     $customdata,$homeserver));
1.1020    raeburn  9428:     }
                   9429:     return $response;
                   9430: }
                   9431: 
1.777     albertel 9432: sub auto_validate_class_sec {
1.918     raeburn  9433:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9434:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9435:     my $ownerlist;
                   9436:     if (ref($owners) eq 'ARRAY') {
                   9437:         $ownerlist = join(',',@{$owners});
                   9438:     } else {
                   9439:         $ownerlist = $owners;
                   9440:     }
1.773     raeburn  9441:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9442:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9443:     return $response;
                   9444: }
                   9445: 
1.1172.2.141  raeburn  9446: sub auto_instsec_reformat {
                   9447:     my ($cdom,$action,$instsecref) = @_;
                   9448:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9449:     my @homeservers;
                   9450:     if (defined(&domain($cdom,'primary'))) {
                   9451:         push(@homeservers,&domain($cdom,'primary'));
                   9452:     } else {
                   9453:         my %servers = &get_servers($cdom,'library');
                   9454:         foreach my $tryserver (keys(%servers)) {
                   9455:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9456:                 push(@homeservers,$tryserver);
                   9457:             }
                   9458:         }
                   9459:     }
                   9460:     my $response;
                   9461:     my %reformatted = %{$instsecref};
                   9462:     foreach my $server (@homeservers) {
                   9463:         if (ref($instsecref) eq 'HASH') {
                   9464:             my $info = &freeze_escape($instsecref);
                   9465:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9466:                                 $action.':'.$info,$server);
                   9467:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9468:             my @items = split(/&/,$response);
                   9469:             foreach my $item (@items) {
                   9470:                 my ($key,$value) = split(/=/,$item);
                   9471:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9472:             }
                   9473:         }
                   9474:     }
                   9475:     return %reformatted;
                   9476: }
                   9477: 
1.1172.2.94  raeburn  9478: sub auto_validate_instclasses {
                   9479:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9480:     my ($homeserver,%validations);
                   9481:     $homeserver = &homeserver($cnum,$cdom);
                   9482:     unless ($homeserver eq 'no_host') {
                   9483:         my $ownerlist;
                   9484:         if (ref($owners) eq 'ARRAY') {
                   9485:             $ownerlist = join(',',@{$owners});
                   9486:         } else {
                   9487:             $ownerlist = $owners;
                   9488:         }
                   9489:         if (ref($classesref) eq 'HASH') {
                   9490:             my $classes = &freeze_escape($classesref);
                   9491:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9492:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9493:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9494:                 my @items = split(/&/,$response);
                   9495:                 foreach my $item (@items) {
                   9496:                     my ($key,$value) = split('=',$item);
                   9497:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9498:                 }
                   9499:             }
                   9500:         }
                   9501:     }
                   9502:     return %validations;
                   9503: }
                   9504: 
1.1172.2.38  raeburn  9505: sub auto_crsreq_update {
                   9506:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9507:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9508:     my ($homeserver,%crsreqresponse);
                   9509:     if ($cdom =~ /^$match_domain$/) {
                   9510:         $homeserver = &domain($cdom,'primary');
                   9511:     }
                   9512:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9513:         my $info;
                   9514:         if (ref($inbound) eq 'HASH') {
                   9515:             $info = &freeze_escape($inbound);
                   9516:         }
                   9517:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9518:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9519:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9520:                             &escape($title).':'.&escape($code).':'.
                   9521:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9522:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9523:             my @items = split(/&/,$response);
                   9524:             foreach my $item (@items) {
                   9525:                 my ($key,$value) = split('=',$item);
                   9526:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9527:             }
                   9528:         }
                   9529:     }
                   9530:     return \%crsreqresponse;
                   9531: }
                   9532: 
1.1172.2.78  raeburn  9533: sub auto_export_grades {
                   9534:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9535:     my ($homeserver,%exportresponse);
                   9536:     if ($cdom =~ /^$match_domain$/) {
                   9537:         $homeserver = &domain($cdom,'primary');
                   9538:     }
                   9539:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9540:         my $info;
                   9541:         if (ref($inforef) eq 'HASH') {
                   9542:             $info = &freeze_escape($inforef);
                   9543:         }
                   9544:         if (ref($gradesref) eq 'HASH') {
                   9545:             my $grades = &freeze_escape($gradesref);
                   9546:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9547:                                 $info.':'.$grades,$homeserver);
                   9548:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9549:                 my @items = split(/&/,$response);
                   9550:                 foreach my $item (@items) {
                   9551:                     my ($key,$value) = split('=',$item);
                   9552:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9553:                 }
                   9554:             }
                   9555:         }
                   9556:     }
                   9557:     return \%exportresponse;
                   9558: }
                   9559: 
1.1172.2.68  raeburn  9560: sub check_instcode_cloning {
                   9561:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9562:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9563:         return;
                   9564:     }
                   9565:     my $canclone;
                   9566:     if (@{$code_order} > 0) {
                   9567:         my $instcoderegexp ='^';
                   9568:         my @clonecodes = split(/\&/,$cloner);
                   9569:         foreach my $item (@{$code_order}) {
                   9570:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9571:                 foreach my $pair (@clonecodes) {
                   9572:                     my ($key,$val) = split(/\=/,$pair,2);
                   9573:                     $val = &unescape($val);
                   9574:                     if ($key eq $item) {
                   9575:                         $instcoderegexp .= '('.$val.')';
                   9576:                         last;
                   9577:                     }
                   9578:                 }
                   9579:             } else {
                   9580:                 $instcoderegexp .= $codedefaults->{$item};
                   9581:             }
                   9582:         }
                   9583:         $instcoderegexp .= '$';
                   9584:         my (@from,@to);
                   9585:         eval {
                   9586:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9587:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9588:         };
                   9589:         if ((@from > 0) && (@to > 0)) {
                   9590:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9591:             if (!@diffs) {
                   9592:                 $canclone = 1;
                   9593:             }
                   9594:         }
                   9595:     }
                   9596:     return $canclone;
                   9597: }
                   9598: 
                   9599: sub default_instcode_cloning {
                   9600:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9601:     my (%codedefaults,@code_order,$canclone);
                   9602:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9603:         %codedefaults = %{$codedefaultsref};
                   9604:         @code_order = @{$codeorderref};
                   9605:     } elsif ($clonedom) {
                   9606:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9607:     }
                   9608:     if (($domdefclone) && (@code_order)) {
                   9609:         my @clonecodes = split(/\+/,$domdefclone);
                   9610:         my $instcoderegexp ='^';
                   9611:         foreach my $item (@code_order) {
                   9612:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9613:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9614:             } else {
                   9615:                 $instcoderegexp .= $codedefaults{$item};
                   9616:             }
                   9617:         }
                   9618:         $instcoderegexp .= '$';
                   9619:         my (@from,@to);
                   9620:         eval {
                   9621:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9622:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9623:         };
                   9624:         if ((@from > 0) && (@to > 0)) {
                   9625:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9626:             if (!@diffs) {
                   9627:                 $canclone = 1;
                   9628:             }
                   9629:         }
                   9630:     }
                   9631:     return $canclone;
                   9632: }
                   9633: 
1.679     raeburn  9634: # ------------------------------------------------------- Course Group routines
                   9635: 
                   9636: sub get_coursegroups {
1.809     raeburn  9637:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9638:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9639: }
                   9640: 
1.679     raeburn  9641: sub modify_coursegroup {
                   9642:     my ($cdom,$cnum,$groupsettings) = @_;
                   9643:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9644: }
                   9645: 
1.809     raeburn  9646: sub toggle_coursegroup_status {
                   9647:     my ($cdom,$cnum,$group,$action) = @_;
                   9648:     my ($from_namespace,$to_namespace);
                   9649:     if ($action eq 'delete') {
                   9650:         $from_namespace = 'coursegroups';
                   9651:         $to_namespace = 'deleted_groups';
                   9652:     } else {
                   9653:         $from_namespace = 'deleted_groups';
                   9654:         $to_namespace = 'coursegroups';
                   9655:     }
                   9656:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9657:     if (my $tmp = &error(%curr_group)) {
                   9658:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9659:         return ('read error',$tmp);
                   9660:     } else {
                   9661:         my %savedsettings = %curr_group; 
1.809     raeburn  9662:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9663:         my $deloutcome;
                   9664:         if ($result eq 'ok') {
1.809     raeburn  9665:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9666:         } else {
                   9667:             return ('write error',$result);
                   9668:         }
                   9669:         if ($deloutcome eq 'ok') {
                   9670:             return 'ok';
                   9671:         } else {
                   9672:             return ('delete error',$deloutcome);
                   9673:         }
                   9674:     }
                   9675: }
                   9676: 
1.679     raeburn  9677: sub modify_group_roles {
1.957     raeburn  9678:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9679:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9680:     my $role = 'gr/'.&escape($userprivs);
                   9681:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9682:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9683:     if ($result eq 'ok') {
                   9684:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9685:     }
1.679     raeburn  9686:     return $result;
                   9687: }
                   9688: 
                   9689: sub modify_coursegroup_membership {
                   9690:     my ($cdom,$cnum,$membership) = @_;
                   9691:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9692:     return $result;
                   9693: }
                   9694: 
1.682     raeburn  9695: sub get_active_groups {
                   9696:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9697:     my $now = time;
                   9698:     my %groups = ();
                   9699:     foreach my $key (keys(%env)) {
1.811     albertel 9700:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9701:             my ($start,$end) = split(/\./,$env{$key});
                   9702:             if (($end!=0) && ($end<$now)) { next; }
                   9703:             if (($start!=0) && ($start>$now)) { next; }
                   9704:             if ($1 eq $cdom && $2 eq $cnum) {
                   9705:                 $groups{$3} = $env{$key} ;
                   9706:             }
                   9707:         }
                   9708:     }
                   9709:     return %groups;
                   9710: }
                   9711: 
1.683     raeburn  9712: sub get_group_membership {
                   9713:     my ($cdom,$cnum,$group) = @_;
                   9714:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9715: }
                   9716: 
                   9717: sub get_users_groups {
                   9718:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9719:     my @usersgroups;
1.683     raeburn  9720:     my $cachetime=1800;
                   9721: 
                   9722:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9723:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9724:     if (defined($cached)) {
1.734     albertel 9725:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9726:     } else {  
                   9727:         $grouplist = '';
1.816     raeburn  9728:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9729:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9730:         my $access_end = $env{'course.'.$courseid.
                   9731:                               '.default_enrollment_end_date'};
                   9732:         my $now = time;
                   9733:         foreach my $key (keys(%roleshash)) {
                   9734:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9735:                 my $group = $1;
                   9736:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9737:                     my $start = $2;
                   9738:                     my $end = $1;
                   9739:                     if ($start == -1) { next; } # deleted from group
                   9740:                     if (($start!=0) && ($start>$now)) { next; }
                   9741:                     if (($end!=0) && ($end<$now)) {
                   9742:                         if ($access_end && $access_end < $now) {
                   9743:                             if ($access_end - $end < 86400) {
                   9744:                                 push(@usersgroups,$group);
1.733     raeburn  9745:                             }
                   9746:                         }
1.817     raeburn  9747:                         next;
1.733     raeburn  9748:                     }
1.817     raeburn  9749:                     push(@usersgroups,$group);
1.683     raeburn  9750:                 }
                   9751:             }
                   9752:         }
1.817     raeburn  9753:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9754:         $grouplist = join(':',@usersgroups);
                   9755:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9756:     }
1.733     raeburn  9757:     return @usersgroups;
1.683     raeburn  9758: }
                   9759: 
                   9760: sub devalidate_getgroups_cache {
                   9761:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9762:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9763: 
1.683     raeburn  9764:     my $hashid="$udom:$uname:$courseid";
                   9765:     &devalidate_cache_new('getgroups',$hashid);
                   9766: }
                   9767: 
1.12      www      9768: # ------------------------------------------------------------------ Plain Text
                   9769: 
                   9770: sub plaintext {
1.988     raeburn  9771:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9772:     if ($short =~ m{^cr/}) {
1.758     albertel 9773: 	return (split('/',$short))[-1];
                   9774:     }
1.742     raeburn  9775:     if (!defined($cid)) {
                   9776:         $cid = $env{'request.course.id'};
                   9777:     }
                   9778:     my %rolenames = (
1.1008    raeburn  9779:                       Course    => 'std',
                   9780:                       Community => 'alt1',
1.742     raeburn  9781:                     );
1.1037    raeburn  9782:     if ($cid ne '') {
                   9783:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9784:             unless ($forcedefault) {
                   9785:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9786:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9787:                 return &Apache::lonlocal::mt($roletext);
                   9788:             }
                   9789:         }
                   9790:     }
                   9791:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9792:         (defined($rolenames{$type})) && 
                   9793:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9794:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9795:     } elsif ($cid ne '') {
                   9796:         my $crstype = $env{'course.'.$cid.'.type'};
                   9797:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9798:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9799:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9800:         }
1.742     raeburn  9801:     }
1.1037    raeburn  9802:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9803: }
                   9804: 
                   9805: # ----------------------------------------------------------------- Assign Role
                   9806: 
                   9807: sub assignrole {
1.957     raeburn  9808:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9809:         $context)=@_;
1.21      www      9810:     my $mrole;
                   9811:     if ($role =~ /^cr\//) {
1.393     www      9812:         my $cwosec=$url;
1.811     albertel 9813:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9814: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9815:            my $refused = 1;
                   9816:            if ($context eq 'requestcourses') {
                   9817:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9818:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9819:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9820:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9821:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9822:                            if ($crsenv{'internal.courseowner'} eq
                   9823:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9824:                                $refused = '';
                   9825:                            }
                   9826:                        }
                   9827:                    }
                   9828:                }
                   9829:            }
                   9830:            if ($refused) {
                   9831:                &logthis('Refused custom assignrole: '.
                   9832:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9833:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9834:                return 'refused';
                   9835:            }
1.104     www      9836:         }
1.21      www      9837:         $mrole='cr';
1.678     raeburn  9838:     } elsif ($role =~ /^gr\//) {
                   9839:         my $cwogrp=$url;
1.811     albertel 9840:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9841:         unless (&allowed('mdg',$cwogrp)) {
                   9842:             &logthis('Refused group assignrole: '.
                   9843:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9844:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9845:             return 'refused';
                   9846:         }
                   9847:         $mrole='gr';
1.21      www      9848:     } else {
1.82      www      9849:         my $cwosec=$url;
1.811     albertel 9850:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9851:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9852:             my $refused;
                   9853:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9854:                 if (!(&allowed('c'.$role,$url))) {
                   9855:                     $refused = 1;
                   9856:                 }
                   9857:             } else {
                   9858:                 $refused = 1;
                   9859:             }
1.947     raeburn  9860:             if ($refused) {
1.1045    raeburn  9861:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9862:                 if (!$selfenroll && $context eq 'course') {
                   9863:                     my %crsenv;
                   9864:                     if ($role eq 'cc' || $role eq 'co') {
                   9865:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9866:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9867:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9868:                                 if ($crsenv{'internal.courseowner'} eq 
                   9869:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9870:                                     $refused = '';
                   9871:                                 }
                   9872:                             }
                   9873:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9874:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9875:                                 if ($crsenv{'internal.courseowner'} eq 
                   9876:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9877:                                     $refused = '';
                   9878:                                 }
                   9879:                             }
                   9880:                         }
                   9881:                     }
                   9882:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9883:                     $refused = '';
1.1017    raeburn  9884:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9885:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9886:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9887:                         my $wrongcc;
                   9888:                         if ($cnum =~ /^$match_community$/) {
                   9889:                             $wrongcc = 1 if ($role eq 'cc');
                   9890:                         } else {
                   9891:                             $wrongcc = 1 if ($role eq 'co');
                   9892:                         }
                   9893:                         unless ($wrongcc) {
                   9894:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9895:                             if ($crsenv{'internal.courseowner'} eq 
                   9896:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9897:                                 $refused = '';
                   9898:                             }
1.1017    raeburn  9899:                         }
                   9900:                     }
1.1172.2.9  raeburn  9901:                 } elsif ($context eq 'requestauthor') {
                   9902:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9903:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9904:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9905:                             $refused = '';
                   9906:                         } else {
                   9907:                             my %domdefaults = &get_domain_defaults($udom);
                   9908:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9909:                                 my $checkbystatus;
                   9910:                                 if ($env{'user.adv'}) {
                   9911:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9912:                                     if ($disposition eq 'automatic') {
                   9913:                                         $refused = '';
                   9914:                                     } elsif ($disposition eq '') {
                   9915:                                         $checkbystatus = 1;
                   9916:                                     }
                   9917:                                 } else {
                   9918:                                     $checkbystatus = 1;
                   9919:                                 }
                   9920:                                 if ($checkbystatus) {
                   9921:                                     if ($env{'environment.inststatus'}) {
                   9922:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9923:                                         foreach my $type (@inststatuses) {
                   9924:                                             if (($type ne '') &&
                   9925:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9926:                                                 $refused = '';
                   9927:                                             }
                   9928:                                         }
                   9929:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9930:                                         $refused = '';
                   9931:                                     }
                   9932:                                 }
                   9933:                             }
                   9934:                         }
                   9935:                     }
1.1017    raeburn  9936:                 }
                   9937:                 if ($refused) {
1.947     raeburn  9938:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9939:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9940: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9941:                     return 'refused';
                   9942:                 }
1.932     raeburn  9943:             }
1.1131    raeburn  9944:         } elsif ($role eq 'au') {
                   9945:             if ($url ne '/'.$udom.'/') {
                   9946:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9947:                          ' to assign author role for '.$uname.':'.$udom.
                   9948:                          ' in domain: '.$url.' refused (wrong domain).');
                   9949:                 return 'refused';
                   9950:             }
1.104     www      9951:         }
1.21      www      9952:         $mrole=$role;
                   9953:     }
1.620     albertel 9954:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9955:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9956:     if ($end) { $command.='_'.$end; }
1.21      www      9957:     if ($start) {
                   9958: 	if ($end) { 
1.81      www      9959:            $command.='_'.$start; 
1.21      www      9960:         } else {
1.81      www      9961:            $command.='_0_'.$start;
1.21      www      9962:         }
                   9963:     }
1.739     raeburn  9964:     my $origstart = $start;
                   9965:     my $origend = $end;
1.957     raeburn  9966:     my $delflag;
1.357     www      9967: # actually delete
                   9968:     if ($deleteflag) {
1.373     www      9969: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9970: # modify command to delete the role
1.620     albertel 9971:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9972:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9973: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9974: # set start and finish to negative values for userrolelog
                   9975:            $start=-1;
                   9976:            $end=-1;
1.957     raeburn  9977:            $delflag = 1;
1.357     www      9978:         }
                   9979:     }
                   9980: # send command
1.349     www      9981:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9982: # log new user role if status is ok
1.349     www      9983:     if ($answer eq 'ok') {
1.663     raeburn  9984: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9985:         if (($role eq 'cc') || ($role eq 'in') ||
                   9986:             ($role eq 'ep') || ($role eq 'ad') ||
                   9987:             ($role eq 'ta') || ($role eq 'st') ||
                   9988:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9989:             ($role eq 'co')) {
1.1172.2.13  raeburn  9990: # for course roles, perform group memberships changes triggered by role change.
                   9991:             unless ($role =~ /^gr/) {
                   9992:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9993:                                                  $origstart,$selfenroll,$context);
                   9994:             }
1.1172.2.9  raeburn  9995:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9996:                            $selfenroll,$context);
                   9997:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9998:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9999:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10000:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10001:                            $context);
                   10002:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10003:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10004:                              $context);
                   10005:         }
1.1053    raeburn  10006:         if ($role eq 'cc') {
                   10007:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10008:         }
1.349     www      10009:     }
                   10010:     return $answer;
1.169     harris41 10011: }
                   10012: 
1.1053    raeburn  10013: sub autoupdate_coowners {
                   10014:     my ($url,$end,$start,$uname,$udom) = @_;
                   10015:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10016:     if (($cdom ne '') && ($cnum ne '')) {
                   10017:         my $now = time;
                   10018:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10019:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10020:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10021:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10022:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10023:             if ($instcode ne '') {
1.1056    raeburn  10024:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10025:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10026:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10027:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10028:                         unless ($result eq 'valid') {
                   10029:                             if ($xlists ne '') {
                   10030:                                 foreach my $xlist (split(',',$xlists)) {
                   10031:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10032:                                     $result =
                   10033:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10034:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10035:                                     last if ($result eq 'valid');
                   10036:                                 }
                   10037:                             }
                   10038:                         }
1.1056    raeburn  10039:                         if ($result eq 'valid') {
                   10040:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10041:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10042:                                     push(@newcoowners,$coowner);
                   10043:                                 }
                   10044:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10045:                                     push(@newcoowners,$uname.':'.$udom);
                   10046:                                 }
                   10047:                                 @newcoowners = sort(@newcoowners);
                   10048:                             } else {
                   10049:                                 push(@newcoowners,$uname.':'.$udom);
                   10050:                             }
1.1172.2.141  raeburn  10051:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10052:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10053:                                 unless ($coowner eq $uname.':'.$udom) {
                   10054:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10055:                                 }
                   10056:                             }
1.1172.2.141  raeburn  10057:                             unless (@newcoowners > 0) {
                   10058:                                 $delcoowners = 1;
                   10059:                                 $coowners = '';
                   10060:                             }
1.1053    raeburn  10061:                         }
                   10062:                         if (@newcoowners || $delcoowners) {
                   10063:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10064:                                             $delcoowners,@newcoowners);
                   10065:                         }
                   10066:                     }
                   10067:                 }
                   10068:             }
                   10069:         }
                   10070:     }
                   10071: }
                   10072: 
                   10073: sub store_coowners {
                   10074:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10075:     my $cid = $cdom.'_'.$cnum;
                   10076:     my ($coowners,$delresult,$putresult);
                   10077:     if (@newcoowners) {
                   10078:         $coowners = join(',',@newcoowners);
                   10079:         my %coownershash = (
                   10080:                             'internal.co-owners' => $coowners,
                   10081:                            );
                   10082:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10083:         if ($putresult eq 'ok') {
                   10084:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10085:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10086:             }
                   10087:         }
                   10088:     }
                   10089:     if ($delcoowners) {
                   10090:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10091:         if ($delresult eq 'ok') {
                   10092:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10093:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10094:             }
                   10095:         }
                   10096:     }
                   10097:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10098:         my %crsinfo =
                   10099:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10100:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10101:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10102:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10103:         }
                   10104:     }
                   10105: }
                   10106: 
1.169     harris41 10107: # -------------------------------------------------- Modify user authentication
1.197     www      10108: # Overrides without validation
                   10109: 
1.169     harris41 10110: sub modifyuserauth {
                   10111:     my ($udom,$uname,$umode,$upass)=@_;
                   10112:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10113:     my $allowed;
                   10114:     if (&allowed('mau',$udom)) {
                   10115:         $allowed = 1;
                   10116:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10117:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10118:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10119:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10120:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10121:         if (($cdom ne '') && ($cnum ne '')) {
                   10122:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10123:             if ($is_owner) {
                   10124:                 $allowed = 1;
                   10125:             }
                   10126:         }
                   10127:     }
                   10128:     unless ($allowed) { return 'refused'; }
1.197     www      10129:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10130:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10131:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10132:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10133: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10134:     my $ip = &get_requestor_ip();
1.620     albertel 10135:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10136:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10137:          '(Remote '.$ip.'): '.$reply);
1.197     www      10138:     &log($udom,,$uname,$uhome,
1.620     albertel 10139:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10140:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10141:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10142:     unless ($reply eq 'ok') {
1.197     www      10143:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10144: 	return 'error: '.$reply;
                   10145:     }   
1.170     harris41 10146:     return 'ok';
1.80      www      10147: }
                   10148: 
1.81      www      10149: # --------------------------------------------------------------- Modify a user
1.80      www      10150: 
1.81      www      10151: sub modifyuser {
1.206     matthew  10152:     my ($udom,    $uname, $uid,
                   10153:         $umode,   $upass, $first,
                   10154:         $middle,  $last,  $gene,
1.1058    raeburn  10155:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10156:     $udom= &LONCAPA::clean_domain($udom);
                   10157:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10158:     my $showcandelete = 'none';
                   10159:     if (ref($candelete) eq 'ARRAY') {
                   10160:         if (@{$candelete} > 0) {
                   10161:             $showcandelete = join(', ',@{$candelete});
                   10162:         }
                   10163:     }
1.81      www      10164:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10165:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10166: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10167:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10168:                                      ' desiredhome not specified'). 
1.620     albertel 10169:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10170:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10171:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10172:     my $newuser;
                   10173:     if ($uhome eq 'no_host') {
                   10174:         $newuser = 1;
                   10175:     }
1.80      www      10176: # ----------------------------------------------------------------- Create User
1.406     albertel 10177:     if (($uhome eq 'no_host') && 
                   10178: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10179:         my $unhome='';
1.844     albertel 10180:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10181:             $unhome = $desiredhome;
1.620     albertel 10182: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10183: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10184:         } else { # load balancing routine for determining $unhome
1.81      www      10185:             my $loadm=10000000;
1.841     albertel 10186: 	    my %servers = &get_servers($udom,'library');
                   10187: 	    foreach my $tryserver (keys(%servers)) {
                   10188: 		my $answer=reply('load',$tryserver);
                   10189: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10190: 		    $loadm=$answer;
                   10191: 		    $unhome=$tryserver;
                   10192: 		}
1.80      www      10193: 	    }
                   10194:         }
                   10195:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10196: 	    return 'error: unable to find a home server for '.$uname.
                   10197:                    ' in domain '.$udom;
1.80      www      10198:         }
                   10199:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10200:                          &escape($upass),$unhome);
                   10201: 	unless ($reply eq 'ok') {
                   10202:             return 'error: '.$reply;
                   10203:         }   
1.230     stredwic 10204:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10205:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10206: 	    return 'error: unable verify users home machine.';
1.80      www      10207:         }
1.209     matthew  10208:     }   # End of creation of new user
1.80      www      10209: # ---------------------------------------------------------------------- Add ID
                   10210:     if ($uid) {
                   10211:        $uid=~tr/A-Z/a-z/;
                   10212:        my %uidhash=&idrget($udom,$uname);
1.196     www      10213:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10214:          && (!$forceid)) {
1.80      www      10215: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10216: 	      return 'error: user id "'.$uid.'" does not match '.
                   10217:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10218:           }
                   10219:        } else {
                   10220: 	  &idput($udom,($uname => $uid));
                   10221:        }
                   10222:     }
                   10223: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10224:     my @tmp=&get('environment',
1.899     raeburn  10225: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10226:                     'permanentemail','inststatus'],
1.134     albertel 10227: 		   $udom,$uname);
1.1075    raeburn  10228:     my (%names,%oldnames);
1.313     matthew  10229:     if ($tmp[0] =~ m/^error:.*/) { 
                   10230:         %names=(); 
                   10231:     } else {
                   10232:         %names = @tmp;
1.1075    raeburn  10233:         %oldnames = %names;
1.313     matthew  10234:     }
1.388     www      10235: #
1.1058    raeburn  10236: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10237: # of users did not contain them), do not overwrite existing values
                   10238: # unless field is in $candelete array ref.  
                   10239: #
                   10240: 
                   10241:     my @fields = ('firstname','middlename','lastname','generation',
                   10242:                   'permanentemail','id');
                   10243:     my %newvalues;
                   10244:     if (ref($candelete) eq 'ARRAY') {
                   10245:         foreach my $field (@fields) {
                   10246:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10247:                 if ($field eq 'firstname') {
                   10248:                     $names{$field} = $first;
                   10249:                 } elsif ($field eq 'middlename') {
                   10250:                     $names{$field} = $middle;
                   10251:                 } elsif ($field eq 'lastname') {
                   10252:                     $names{$field} = $last;
                   10253:                 } elsif ($field eq 'generation') { 
                   10254:                     $names{$field} = $gene;
                   10255:                 } elsif ($field eq 'permanentemail') {
                   10256:                     $names{$field} = $email;
                   10257:                 } elsif ($field eq 'id') {
                   10258:                     $names{$field}  = $uid;
                   10259:                 }
                   10260:             }
                   10261:         }
                   10262:     }
1.388     www      10263:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10264:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10265:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10266:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10267:     if ($email) {
                   10268:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10269:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10270:     }
1.899     raeburn  10271:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10272:     if (defined($inststatus)) {
                   10273:         $names{'inststatus'} = '';
                   10274:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10275:         if (ref($usertypes) eq 'HASH') {
                   10276:             my @okstatuses; 
                   10277:             foreach my $item (split(/:/,$inststatus)) {
                   10278:                 if (defined($usertypes->{$item})) {
                   10279:                     push(@okstatuses,$item);  
                   10280:                 }
                   10281:             }
                   10282:             if (@okstatuses) {
                   10283:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10284:             }
                   10285:         }
                   10286:     }
1.1075    raeburn  10287:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10288:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10289:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10290:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10291:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10292:     } else {
                   10293:         $logmsg .= ' during self creation';
                   10294:     }
1.1075    raeburn  10295:     my $changed;
                   10296:     if ($newuser) {
                   10297:         $changed = 1;
                   10298:     } else {
                   10299:         foreach my $field (@fields) {
                   10300:             if ($names{$field} ne $oldnames{$field}) {
                   10301:                 $changed = 1;
                   10302:                 last;
                   10303:             }
                   10304:         }
                   10305:     }
                   10306:     unless ($changed) {
                   10307:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10308:         &logthis($logmsg);
                   10309:         return 'ok';
                   10310:     }
                   10311:     my $reply = &put('environment', \%names, $udom,$uname);
                   10312:     if ($reply ne 'ok') { 
                   10313:         return 'error: '.$reply;
                   10314:     }
1.1087    raeburn  10315:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10316:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10317:     }
1.1075    raeburn  10318:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10319:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10320:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10321:     &logthis($logmsg);
1.134     albertel 10322:     return 'ok';
1.80      www      10323: }
                   10324: 
1.81      www      10325: # -------------------------------------------------------------- Modify student
1.80      www      10326: 
1.81      www      10327: sub modifystudent {
                   10328:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10329:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10330:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10331:     if (!$cid) {
1.620     albertel 10332: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10333: 	    return 'not_in_class';
                   10334: 	}
1.80      www      10335:     }
                   10336: # --------------------------------------------------------------- Make the user
1.81      www      10337:     my $reply=&modifyuser
1.209     matthew  10338: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10339:          $desiredhome,$email,$inststatus);
1.80      www      10340:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10341:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10342:     # student's environment
1.297     matthew  10343:     $uid = undef if (!$forceid);
1.455     albertel 10344:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10345: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10346:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10347:     return $reply;
                   10348: }
                   10349: 
                   10350: sub modify_student_enrollment {
1.1172.2.23  raeburn  10351:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10352:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10353:     my ($cdom,$cnum,$chome);
                   10354:     if (!$cid) {
1.620     albertel 10355: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10356: 	    return 'not_in_class';
                   10357: 	}
1.620     albertel 10358: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10359: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10360:     } else {
                   10361: 	($cdom,$cnum)=split(/_/,$cid);
                   10362:     }
1.620     albertel 10363:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10364:     if (!$chome) {
1.457     raeburn  10365: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10366:     }
1.455     albertel 10367:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10368:     # Make sure the user exists
1.81      www      10369:     my $uhome=&homeserver($uname,$udom);
                   10370:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10371: 	return 'error: no such user';
                   10372:     }
1.297     matthew  10373:     # Get student data if we were not given enough information
                   10374:     if (!defined($first)  || $first  eq '' || 
                   10375:         !defined($last)   || $last   eq '' || 
                   10376:         !defined($uid)    || $uid    eq '' || 
                   10377:         !defined($middle) || $middle eq '' || 
                   10378:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10379:         # They did not supply us with enough data to enroll the student, so
                   10380:         # we need to pick up more information.
1.297     matthew  10381:         my %tmp = &get('environment',
1.294     matthew  10382:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10383:                        ,$udom,$uname);
                   10384: 
1.800     albertel 10385:         #foreach my $key (keys(%tmp)) {
                   10386:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10387:         #}
1.294     matthew  10388:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10389:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10390:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10391:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10392:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10393:     }
1.556     albertel 10394:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10395:     my $user = "$uname:$udom";
                   10396:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10397:     my $reply=cput('classlist',
1.1148    raeburn  10398: 		   {$user => 
1.1172.2.76  raeburn  10399: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10400: 		   $cdom,$cnum);
1.1148    raeburn  10401:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10402:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10403:     } else { 
1.81      www      10404: 	return 'error: '.$reply;
                   10405:     }
1.297     matthew  10406:     # Add student role to user
1.83      www      10407:     my $uurl='/'.$cid;
1.81      www      10408:     $uurl=~s/\_/\//g;
                   10409:     if ($usec) {
                   10410: 	$uurl.='/'.$usec;
                   10411:     }
1.1148    raeburn  10412:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10413:                              $selfenroll,$context);
                   10414:     if ($result ne 'ok') {
                   10415:         if ($old_entry{$user} ne '') {
                   10416:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10417:         } else {
                   10418:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10419:         }
                   10420:     }
                   10421:     return $result; 
1.21      www      10422: }
                   10423: 
1.556     albertel 10424: sub format_name {
                   10425:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10426:     my $name;
                   10427:     if ($first ne 'lastname') {
                   10428: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10429:     } else {
                   10430: 	if ($lastname=~/\S/) {
                   10431: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10432: 	    $name=~s/\s+,/,/;
                   10433: 	} else {
                   10434: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10435: 	}
                   10436:     }
                   10437:     $name=~s/^\s+//;
                   10438:     $name=~s/\s+$//;
                   10439:     $name=~s/\s+/ /g;
                   10440:     return $name;
                   10441: }
                   10442: 
1.84      www      10443: # ------------------------------------------------- Write to course preferences
                   10444: 
                   10445: sub writecoursepref {
                   10446:     my ($courseid,%prefs)=@_;
                   10447:     $courseid=~s/^\///;
                   10448:     $courseid=~s/\_/\//g;
                   10449:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10450:     my $chome=homeserver($cnum,$cdomain);
                   10451:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10452: 	return 'error: no such course';
                   10453:     }
                   10454:     my $cstring='';
1.800     albertel 10455:     foreach my $pref (keys(%prefs)) {
                   10456: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10457:     }
1.84      www      10458:     $cstring=~s/\&$//;
                   10459:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10460: }
                   10461: 
                   10462: # ---------------------------------------------------------- Make/modify course
                   10463: 
                   10464: sub createcourse {
1.741     raeburn  10465:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10466:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10467:     $url=&declutter($url);
                   10468:     my $cid='';
1.1028    raeburn  10469:     if ($context eq 'requestcourses') {
                   10470:         my $can_create = 0;
                   10471:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10472:         if ($udom eq $ownerdom) {
                   10473:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10474:                                   $context)) {
                   10475:                 $can_create = 1;
                   10476:             }
                   10477:         } else {
                   10478:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10479:                                            $category);
                   10480:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10481:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10482:                 if (@curr > 0) {
                   10483:                     my @options = qw(approval validate autolimit);
                   10484:                     my $optregex = join('|',@options);
                   10485:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10486:                         $can_create = 1;
                   10487:                     }
                   10488:                 }
                   10489:             }
                   10490:         }
                   10491:         if ($can_create) {
                   10492:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10493:                 unless (&allowed('ccc',$udom)) {
                   10494:                     return 'refused'; 
                   10495:                 }
1.1017    raeburn  10496:             }
                   10497:         } else {
                   10498:             return 'refused';
                   10499:         }
1.1028    raeburn  10500:     } elsif (!&allowed('ccc',$udom)) {
                   10501:         return 'refused';
1.84      www      10502:     }
1.1011    raeburn  10503: # --------------------------------------------------------------- Get Unique ID
                   10504:     my $uname;
                   10505:     if ($cnum =~ /^$match_courseid$/) {
                   10506:         my $chome=&homeserver($cnum,$udom,'true');
                   10507:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10508:             $uname = $cnum;
                   10509:         } else {
1.1038    raeburn  10510:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10511:         }
                   10512:     } else {
1.1038    raeburn  10513:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10514:     }
                   10515:     return $uname if ($uname =~ /^error/);
                   10516: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10517:     if (!defined($course_server)) {
                   10518:         if (defined(&domain($udom,'primary'))) {
                   10519:             $course_server = &domain($udom,'primary');
                   10520:         } else {
                   10521:             $course_server = $env{'user.home'}; 
                   10522:         }
                   10523:     }
                   10524:     my %host_servers =
                   10525:         &Apache::lonnet::get_servers($udom,'library');
                   10526:     unless ($host_servers{$course_server}) {
                   10527:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10528:     }
1.84      www      10529: # ------------------------------------------------------------- Make the course
                   10530:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10531:                       $course_server);
1.84      www      10532:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10533:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10534:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10535: 	return 'error: no such course';
                   10536:     }
1.271     www      10537: # ----------------------------------------------------------------- Course made
1.516     raeburn  10538: # log existence
1.1029    raeburn  10539:     my $now = time;
1.918     raeburn  10540:     my $newcourse = {
                   10541:                     $udom.'_'.$uname => {
1.921     raeburn  10542:                                      description => $description,
                   10543:                                      inst_code   => $inst_code,
                   10544:                                      owner       => $course_owner,
                   10545:                                      type        => $crstype,
1.1029    raeburn  10546:                                      creator     => $env{'user.name'}.':'.
                   10547:                                                     $env{'user.domain'},
                   10548:                                      created     => $now,
                   10549:                                      context     => $context,
1.918     raeburn  10550:                                                 },
                   10551:                     };
1.921     raeburn  10552:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10553: # set toplevel url
1.271     www      10554:     my $topurl=$url;
                   10555:     unless ($nonstandard) {
                   10556: # ------------------------------------------ For standard courses, make top url
                   10557:         my $mapurl=&clutter($url);
1.278     www      10558:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10559:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10560: <map>
                   10561: <resource id="1" type="start"></resource>
                   10562: <resource id="2" src="$mapurl"></resource>
                   10563: <resource id="3" type="finish"></resource>
                   10564: <link index="1" from="1" to="2"></link>
                   10565: <link index="2" from="2" to="3"></link>
                   10566: </map>
                   10567: ENDINITMAP
                   10568:         $topurl=&declutter(
1.638     albertel 10569:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10570:                           );
                   10571:     }
                   10572: # ----------------------------------------------------------- Write preferences
1.84      www      10573:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10574:                      ('description'              => $description,
                   10575:                       'url'                      => $topurl,
                   10576:                       'internal.creator'         => $env{'user.name'}.':'.
                   10577:                                                     $env{'user.domain'},
                   10578:                       'internal.created'         => $now,
                   10579:                       'internal.creationcontext' => $context)
                   10580:                     );
1.84      www      10581:     return '/'.$udom.'/'.$uname;
                   10582: }
                   10583: 
1.1011    raeburn  10584: # ------------------------------------------------------------------- Create ID
                   10585: sub generate_coursenum {
1.1038    raeburn  10586:     my ($udom,$crstype) = @_;
1.1011    raeburn  10587:     my $domdesc = &domain($udom);
                   10588:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10589:     my $first;
                   10590:     if ($crstype eq 'Community') {
                   10591:         $first = '0';
                   10592:     } else {
                   10593:         $first = int(1+rand(9)); 
                   10594:     } 
                   10595:     my $uname=$first.
1.1011    raeburn  10596:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10597:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10598:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10599: # ----------------------------------------------- Make sure that does not exist
                   10600:     my $uhome=&homeserver($uname,$udom,'true');
                   10601:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10602:         if ($crstype eq 'Community') {
                   10603:             $first = '0';
                   10604:         } else {
                   10605:             $first = int(1+rand(9));
                   10606:         }
                   10607:         $uname=$first.
1.1011    raeburn  10608:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10609:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10610:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10611:         $uhome=&homeserver($uname,$udom,'true');
                   10612:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10613:             return 'error: unable to generate unique course-ID';
                   10614:         }
                   10615:     }
                   10616:     return $uname;
                   10617: }
                   10618: 
1.813     albertel 10619: sub is_course {
1.1167    droeschl 10620:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10621:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10622:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10623:     my $uhome=&homeserver($cnum,$cdom);
                   10624:     my $iscourse;
                   10625:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10626:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10627:     } else {
                   10628:         my $hashid = $cdom.':'.$cnum;
                   10629:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10630:         unless (defined($cached)) {
                   10631:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10632:                                         $cnum,undef,undef,'.');
                   10633:             $iscourse = 0;
                   10634:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10635:                 $iscourse = 1;
                   10636:             }
                   10637:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10638:         }
                   10639:     }
                   10640:     return unless($iscourse);
1.1167    droeschl 10641:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10642: }
                   10643: 
1.1015    raeburn  10644: sub store_userdata {
                   10645:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10646:     my $result;
1.1016    raeburn  10647:     if ($datakey ne '') {
1.1013    raeburn  10648:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10649:             if ($udom eq '' || $uname eq '') {
                   10650:                 $udom = $env{'user.domain'};
                   10651:                 $uname = $env{'user.name'};
                   10652:             }
                   10653:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10654:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10655:                 $result = 'error: no_host';
                   10656:             } else {
1.1172.2.138  raeburn  10657:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10658:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10659: 
                   10660:                 my $namevalue='';
                   10661:                 foreach my $key (keys(%{$storehash})) {
                   10662:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10663:                 }
                   10664:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10665:                 unless ($namespace eq 'courserequests') {
                   10666:                     $datakey = &escape($datakey);
                   10667:                 }
1.1105    raeburn  10668:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10669:                                   $namevalue,$uhome);
1.1013    raeburn  10670:             }
                   10671:         } else {
                   10672:             $result = 'error: data to store was not a hash reference'; 
                   10673:         }
                   10674:     } else {
                   10675:         $result= 'error: invalid requestkey'; 
                   10676:     }
                   10677:     return $result;
                   10678: }
                   10679: 
1.21      www      10680: # ---------------------------------------------------------- Assign Custom Role
                   10681: 
                   10682: sub assigncustomrole {
1.957     raeburn  10683:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10684:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10685:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10686: }
                   10687: 
                   10688: # ----------------------------------------------------------------- Revoke Role
                   10689: 
                   10690: sub revokerole {
1.957     raeburn  10691:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10692:     my $now=time;
1.965     raeburn  10693:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10694: }
                   10695: 
                   10696: # ---------------------------------------------------------- Revoke Custom Role
                   10697: 
                   10698: sub revokecustomrole {
1.957     raeburn  10699:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10700:     my $now=time;
1.357     www      10701:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10702:            $deleteflag,$selfenroll,$context);
1.17      www      10703: }
                   10704: 
1.533     banghart 10705: # ------------------------------------------------------------ Disk usage
1.535     albertel 10706: sub diskusage {
1.955     raeburn  10707:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10708:     $directorypath =~ s/\/$//;
                   10709:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10710:                        .&escape($getpropath).':'.&escape($uname).':'
                   10711:                        .&escape($udom),homeserver($uname,$udom));
                   10712:     if ($listing eq 'unknown_cmd') {
                   10713:         if ($getpropath) {
                   10714:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10715:         }
                   10716:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10717:     }
1.514     albertel 10718:     return $listing;
1.512     banghart 10719: }
                   10720: 
1.566     banghart 10721: sub is_locked {
1.1096    raeburn  10722:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10723:     my @check;
                   10724:     my $is_locked;
1.1093    raeburn  10725:     push (@check,$file_name);
1.613     albertel 10726:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10727: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10728:     my ($tmp)=keys(%locked);
                   10729:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10730:     
1.566     banghart 10731:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10732:         $is_locked = 'false';
                   10733:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10734:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10735:                $is_locked = 'true';
1.1096    raeburn  10736:                if (ref($which) eq 'ARRAY') {
                   10737:                    push(@{$which},$entry);
                   10738:                } else {
                   10739:                    last;
                   10740:                }
1.745     raeburn  10741:            }
                   10742:        }
1.566     banghart 10743:     } else {
                   10744:         $is_locked = 'false';
                   10745:     }
1.1093    raeburn  10746:     return $is_locked;
1.566     banghart 10747: }
                   10748: 
1.759     albertel 10749: sub declutter_portfile {
                   10750:     my ($file) = @_;
1.833     albertel 10751:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10752:     return $file;
                   10753: }
                   10754: 
1.559     banghart 10755: # ------------------------------------------------------------- Mark as Read Only
                   10756: 
                   10757: sub mark_as_readonly {
                   10758:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10759:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10760:     my ($tmp)=keys(%current_permissions);
                   10761:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10762:     foreach my $file (@{$files}) {
1.759     albertel 10763: 	$file = &declutter_portfile($file);
1.561     banghart 10764:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10765:     }
1.613     albertel 10766:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10767:     return;
                   10768: }
                   10769: 
1.572     banghart 10770: # ------------------------------------------------------------Save Selected Files
                   10771: 
                   10772: sub save_selected_files {
                   10773:     my ($user, $path, @files) = @_;
                   10774:     my $filename = $user."savedfiles";
1.573     banghart 10775:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10776:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10777:     foreach my $file (@files) {
1.620     albertel 10778:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10779:     }
                   10780:     foreach my $file (@other_files) {
1.574     banghart 10781:         print (OUT $file."\n");
1.572     banghart 10782:     }
1.574     banghart 10783:     close (OUT);
1.572     banghart 10784:     return 'ok';
                   10785: }
                   10786: 
1.574     banghart 10787: sub clear_selected_files {
                   10788:     my ($user) = @_;
                   10789:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10790:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10791:     print (OUT undef);
                   10792:     close (OUT);
                   10793:     return ("ok");    
                   10794: }
                   10795: 
1.572     banghart 10796: sub files_in_path {
                   10797:     my ($user, $path) = @_;
                   10798:     my $filename = $user."savedfiles";
                   10799:     my %return_files;
1.1172.2.96  raeburn  10800:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10801:     while (my $line_in = <IN>) {
1.574     banghart 10802:         chomp ($line_in);
                   10803:         my @paths_and_file = split (m!/!, $line_in);
                   10804:         my $file_part = pop (@paths_and_file);
                   10805:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10806:         $path_part.='/';
                   10807:         my $path_and_file = $path_part.$file_part;
                   10808:         if ($path_part eq $path) {
                   10809:             $return_files{$file_part}= 'selected';
                   10810:         }
                   10811:     }
1.574     banghart 10812:     close (IN);
                   10813:     return (\%return_files);
1.572     banghart 10814: }
                   10815: 
                   10816: # called in portfolio select mode, to show files selected NOT in current directory
                   10817: sub files_not_in_path {
                   10818:     my ($user, $path) = @_;
                   10819:     my $filename = $user."savedfiles";
                   10820:     my @return_files;
                   10821:     my $path_part;
1.1172.2.96  raeburn  10822:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10823:     while (my $line = <IN>) {
1.572     banghart 10824:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10825:         my @paths_and_file = split(m|/|, $line);
                   10826:         my $file_part = pop(@paths_and_file);
                   10827:         chomp($file_part);
                   10828:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10829:         $path_part .= '/';
                   10830:         my $path_and_file = $path_part.$file_part;
                   10831:         if ($path_part ne $path) {
1.800     albertel 10832:             push(@return_files, ($path_and_file));
1.572     banghart 10833:         }
                   10834:     }
1.800     albertel 10835:     close(OUT);
1.574     banghart 10836:     return (@return_files);
1.572     banghart 10837: }
                   10838: 
1.745     raeburn  10839: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10840: 
1.745     raeburn  10841: sub get_portfile_permissions {
                   10842:     my ($domain,$user) = @_;
1.613     albertel 10843:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10844:     my ($tmp)=keys(%current_permissions);
                   10845:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10846:     return \%current_permissions;
                   10847: }
                   10848: 
                   10849: #---------------------------------------------Get portfolio file access controls
                   10850: 
1.749     raeburn  10851: sub get_access_controls {
1.745     raeburn  10852:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10853:     my %access;
                   10854:     my $real_file = $file;
                   10855:     $file =~ s/\.meta$//;
1.745     raeburn  10856:     if (defined($file)) {
1.749     raeburn  10857:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10858:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10859:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10860:             }
                   10861:         }
1.745     raeburn  10862:     } else {
1.749     raeburn  10863:         foreach my $key (keys(%{$current_permissions})) {
                   10864:             if ($key =~ /\0accesscontrol$/) {
                   10865:                 if (defined($group)) {
                   10866:                     if ($key !~ m-^\Q$group\E/-) {
                   10867:                         next;
                   10868:                     }
                   10869:                 }
                   10870:                 my ($fullpath) = split(/\0/,$key);
                   10871:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10872:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10873:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10874:                     }
                   10875:                 }
                   10876:             }
                   10877:         }
                   10878:     }
                   10879:     return %access;
                   10880: }
                   10881: 
                   10882: sub modify_access_controls {
                   10883:     my ($file_name,$changes,$domain,$user)=@_;
                   10884:     my ($outcome,$deloutcome);
                   10885:     my %store_permissions;
                   10886:     my %new_values;
                   10887:     my %new_control;
                   10888:     my %translation;
                   10889:     my @deletions = ();
                   10890:     my $now = time;
                   10891:     if (exists($$changes{'activate'})) {
                   10892:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10893:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10894:             my $numnew = scalar(@newitems);
                   10895:             for (my $i=0; $i<$numnew; $i++) {
                   10896:                 my $newkey = $newitems[$i];
                   10897:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10898:                 if ($newkey =~ /^\d+:/) { 
                   10899:                     $newkey =~ s/^(\d+)/$newid/;
                   10900:                     $translation{$1} = $newid;
                   10901:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10902:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10903:                     $translation{$1} = $newid;
                   10904:                 }
1.749     raeburn  10905:                 $new_values{$file_name."\0".$newkey} = 
                   10906:                                           $$changes{'activate'}{$newitems[$i]};
                   10907:                 $new_control{$newkey} = $now;
                   10908:             }
                   10909:         }
                   10910:     }
                   10911:     my %todelete;
                   10912:     my %changed_items;
                   10913:     foreach my $action ('delete','update') {
                   10914:         if (exists($$changes{$action})) {
                   10915:             if (ref($$changes{$action}) eq 'HASH') {
                   10916:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10917:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10918:                     if ($action eq 'delete') { 
                   10919:                         $todelete{$itemnum} = 1;
                   10920:                     } else {
                   10921:                         $changed_items{$itemnum} = $key;
                   10922:                     }
                   10923:                 }
1.745     raeburn  10924:             }
                   10925:         }
1.749     raeburn  10926:     }
                   10927:     # get lock on access controls for file.
                   10928:     my $lockhash = {
                   10929:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10930:                                                        ':'.$env{'user.domain'},
                   10931:                    }; 
                   10932:     my $tries = 0;
                   10933:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10934:    
1.1172.2.79  raeburn  10935:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10936:         $tries ++;
1.1172.2.79  raeburn  10937:         sleep(0.1);
1.749     raeburn  10938:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10939:     }
                   10940:     if ($gotlock eq 'ok') {
                   10941:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10942:         my ($tmp)=keys(%curr_permissions);
                   10943:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10944:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10945:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10946:             if (ref($curr_controls) eq 'HASH') {
                   10947:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10948:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10949:                     if (defined($todelete{$itemnum})) {
                   10950:                         push(@deletions,$file_name."\0".$control_item);
                   10951:                     } else {
                   10952:                         if (defined($changed_items{$itemnum})) {
                   10953:                             $new_control{$changed_items{$itemnum}} = $now;
                   10954:                             push(@deletions,$file_name."\0".$control_item);
                   10955:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10956:                         } else {
                   10957:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10958:                         }
                   10959:                     }
1.745     raeburn  10960:                 }
                   10961:             }
                   10962:         }
1.970     raeburn  10963:         my ($group);
                   10964:         if (&is_course($domain,$user)) {
                   10965:             ($group,my $file) = split(/\//,$file_name,2);
                   10966:         }
1.749     raeburn  10967:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10968:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10969:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10970:         #  remove lock
                   10971:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10972:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10973:         my $sqlresult =
1.970     raeburn  10974:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10975:                                     $group);
1.749     raeburn  10976:     } else {
                   10977:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10978:     }
1.749     raeburn  10979:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10980: }
                   10981: 
1.827     raeburn  10982: sub make_public_indefinitely {
                   10983:     my ($requrl) = @_;
                   10984:     my $now = time;
                   10985:     my $action = 'activate';
                   10986:     my $aclnum = 0;
                   10987:     if (&is_portfolio_url($requrl)) {
                   10988:         my (undef,$udom,$unum,$file_name,$group) =
                   10989:             &parse_portfolio_url($requrl);
                   10990:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10991:         my %access_controls = &get_access_controls($current_perms,
                   10992:                                                    $group,$file_name);
                   10993:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10994:             my ($num,$scope,$end,$start) = 
                   10995:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10996:             if ($scope eq 'public') {
                   10997:                 if ($start <= $now && $end == 0) {
                   10998:                     $action = 'none';
                   10999:                 } else {
                   11000:                     $action = 'update';
                   11001:                     $aclnum = $num;
                   11002:                 }
                   11003:                 last;
                   11004:             }
                   11005:         }
                   11006:         if ($action eq 'none') {
                   11007:              return 'ok';
                   11008:         } else {
                   11009:             my %changes;
                   11010:             my $newend = 0;
                   11011:             my $newstart = $now;
                   11012:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11013:             $changes{$action}{$newkey} = {
                   11014:                 type => 'public',
                   11015:                 time => {
                   11016:                     start => $newstart,
                   11017:                     end   => $newend,
                   11018:                 },
                   11019:             };
                   11020:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11021:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11022:             return $outcome;
                   11023:         }
                   11024:     } else {
                   11025:         return 'invalid';
                   11026:     }
                   11027: }
                   11028: 
1.745     raeburn  11029: #------------------------------------------------------Get Marked as Read Only
                   11030: 
                   11031: sub get_marked_as_readonly {
                   11032:     my ($domain,$user,$what,$group) = @_;
                   11033:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11034:     my @readonly_files;
1.629     banghart 11035:     my $cmp1=$what;
                   11036:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11037:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11038:         if (defined($group)) {
                   11039:             if ($file_name !~ m-^\Q$group\E/-) {
                   11040:                 next;
                   11041:             }
                   11042:         }
1.561     banghart 11043:         if (ref($value) eq "ARRAY"){
                   11044:             foreach my $stored_what (@{$value}) {
1.629     banghart 11045:                 my $cmp2=$stored_what;
1.759     albertel 11046:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11047:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11048:                 }
1.629     banghart 11049:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11050:                     push(@readonly_files, $file_name);
1.745     raeburn  11051:                     last;
1.563     banghart 11052:                 } elsif (!defined($what)) {
                   11053:                     push(@readonly_files, $file_name);
1.745     raeburn  11054:                     last;
1.561     banghart 11055:                 }
                   11056:             }
1.745     raeburn  11057:         }
1.561     banghart 11058:     }
                   11059:     return @readonly_files;
                   11060: }
1.577     banghart 11061: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11062: 
1.577     banghart 11063: sub get_marked_as_readonly_hash {
1.745     raeburn  11064:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11065:     my %readonly_files;
1.745     raeburn  11066:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11067:         if (defined($group)) {
                   11068:             if ($file_name !~ m-^\Q$group\E/-) {
                   11069:                 next;
                   11070:             }
                   11071:         }
1.577     banghart 11072:         if (ref($value) eq "ARRAY"){
                   11073:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11074:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11075:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11076:                         if ($lock_descriptor eq 'graded') {
                   11077:                             $readonly_files{$file_name} = 'graded';
                   11078:                         } elsif ($lock_descriptor eq 'handback') {
                   11079:                             $readonly_files{$file_name} = 'handback';
                   11080:                         } else {
                   11081:                             if (!exists($readonly_files{$file_name})) {
                   11082:                                 $readonly_files{$file_name} = 'locked';
                   11083:                             }
                   11084:                         }
1.745     raeburn  11085:                     }
1.750     banghart 11086:                 } 
1.577     banghart 11087:             }
                   11088:         } 
                   11089:     }
                   11090:     return %readonly_files;
                   11091: }
1.559     banghart 11092: # ------------------------------------------------------------ Unmark as Read Only
                   11093: 
                   11094: sub unmark_as_readonly {
1.629     banghart 11095:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11096:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11097:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11098:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11099:     my $symb_crs = $what;
                   11100:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11101:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11102:     my ($tmp)=keys(%current_permissions);
                   11103:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11104:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11105:     foreach my $file (@readonly_files) {
1.759     albertel 11106: 	my $clean_file = &declutter_portfile($file);
                   11107: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11108: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11109:         my @new_locks;
                   11110:         my @del_keys;
                   11111:         if (ref($current_locks) eq "ARRAY"){
                   11112:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11113:                 my $compare=$locker;
1.749     raeburn  11114:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11115:                     $compare=join('',@{$locker});
1.746     raeburn  11116:                     if ($compare ne $symb_crs) {
                   11117:                         push(@new_locks, $locker);
                   11118:                     }
1.563     banghart 11119:                 }
                   11120:             }
1.650     albertel 11121:             if (scalar(@new_locks) > 0) {
1.563     banghart 11122:                 $current_permissions{$file} = \@new_locks;
                   11123:             } else {
                   11124:                 push(@del_keys, $file);
1.613     albertel 11125:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11126:                 delete($current_permissions{$file});
1.563     banghart 11127:             }
                   11128:         }
1.561     banghart 11129:     }
1.613     albertel 11130:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11131:     return;
                   11132: }
1.512     banghart 11133: 
1.17      www      11134: # ------------------------------------------------------------ Directory lister
                   11135: 
                   11136: sub dirlist {
1.955     raeburn  11137:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11138:     $uri=~s/^\///;
                   11139:     $uri=~s/\/$//;
1.253     stredwic 11140:     my ($udom, $uname);
1.955     raeburn  11141:     if ($getuserdir) {
1.253     stredwic 11142:         $udom = $userdomain;
                   11143:         $uname = $username;
1.955     raeburn  11144:     } else {
                   11145:         (undef,$udom,$uname)=split(/\//,$uri);
                   11146:         if(defined($userdomain)) {
                   11147:             $udom = $userdomain;
                   11148:         }
                   11149:         if(defined($username)) {
                   11150:             $uname = $username;
                   11151:         }
1.253     stredwic 11152:     }
1.955     raeburn  11153:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11154: 
1.955     raeburn  11155:     $dirRoot = $perlvar{'lonDocRoot'};
                   11156:     if (defined($getpropath)) {
                   11157:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11158:         $dirRoot =~ s/\/$//;
1.955     raeburn  11159:     } elsif (defined($getuserdir)) {
                   11160:         my $subdir=$uname.'__';
                   11161:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11162:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11163:                    ."/$udom/$subdir/$uname";
                   11164:     } elsif (defined($alternateRoot)) {
                   11165:         $dirRoot = $alternateRoot;
1.751     banghart 11166:     }
1.253     stredwic 11167: 
                   11168:     if($udom) {
                   11169:         if($uname) {
1.1135    raeburn  11170:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11171:             if ($uhome eq 'no_host') {
                   11172:                 return ([],'no_host');
                   11173:             }
1.955     raeburn  11174:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11175:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11176:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11177:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11178:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11179:             } else {
                   11180:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11181:             }
1.605     matthew  11182:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11183:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11184:                 @listing_results = split(/:/,$listing);
                   11185:             } else {
                   11186:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11187:             }
1.1135    raeburn  11188:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11189:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11190:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11191:                 return ([],$listing);
                   11192:             } else {
                   11193:                 return (\@listing_results);
1.1135    raeburn  11194:             }
1.955     raeburn  11195:         } elsif(!$alternateRoot) {
1.1136    raeburn  11196:             my (%allusers,%listerror);
1.841     albertel 11197: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11198:  	    foreach my $tryserver (keys(%servers)) {
                   11199:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11200:                                   &escape($udom),$tryserver);
                   11201:                 if ($listing eq 'unknown_cmd') {
                   11202: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11203: 				      $udom, $tryserver);
                   11204:                 } else {
                   11205:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11206:                 }
1.841     albertel 11207: 		if ($listing eq 'unknown_cmd') {
                   11208: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11209: 				      $udom, $tryserver);
                   11210: 		    @listing_results = split(/:/,$listing);
                   11211: 		} else {
                   11212: 		    @listing_results =
                   11213: 			map { &unescape($_); } split(/:/,$listing);
                   11214: 		}
1.1136    raeburn  11215:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11216:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11217:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11218:                     $listerror{$tryserver} = $listing;
                   11219:                 } else {
1.841     albertel 11220: 		    foreach my $line (@listing_results) {
                   11221: 			my ($entry) = split(/&/,$line,2);
                   11222: 			$allusers{$entry} = 1;
                   11223: 		    }
                   11224: 		}
1.253     stredwic 11225:             }
1.1136    raeburn  11226:             my @alluserslist=();
1.800     albertel 11227:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11228:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11229:             }
1.1172.2.80  raeburn  11230:             if (!%listerror) {
                   11231:                 # no errors
                   11232:                 return (\@alluserslist);
                   11233:             } elsif (scalar(keys(%servers)) == 1) {
                   11234:                 # one library server, one error
                   11235:                 my ($key) = keys(%listerror);
                   11236:                 return (\@alluserslist, $listerror{$key});
                   11237:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11238:                 # con_lost indicates that we might miss data from at least one
                   11239:                 # library server
                   11240:                 return (\@alluserslist, 'con_lost');
                   11241:             } else {
                   11242:                 # multiple library servers and no con_lost -> data should be
                   11243:                 # complete.
                   11244:                 return (\@alluserslist);
                   11245:             }
                   11246: 
1.253     stredwic 11247:         } else {
1.1136    raeburn  11248:             return ([],'missing username');
1.253     stredwic 11249:         }
1.955     raeburn  11250:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11251:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11252:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11253:         return (\@all_domains);
1.955     raeburn  11254:     } else {
1.1136    raeburn  11255:         return ([],'missing domain');
1.275     stredwic 11256:     }
                   11257: }
                   11258: 
                   11259: # --------------------------------------------- GetFileTimestamp
                   11260: # This function utilizes dirlist and returns the date stamp for
                   11261: # when it was last modified.  It will also return an error of -1
                   11262: # if an error occurs
                   11263: 
                   11264: sub GetFileTimestamp {
1.955     raeburn  11265:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11266:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11267:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11268:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11269:                                     undef,$getuserdir);
                   11270:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11271:         return -1;
                   11272:     }
                   11273:     if (ref($fileref) eq 'ARRAY') {
                   11274:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11275:         # @stats contains first the filename, then the stat output
                   11276:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11277:     } else {
                   11278:         return -1;
1.253     stredwic 11279:     }
1.26      www      11280: }
                   11281: 
1.712     albertel 11282: sub stat_file {
                   11283:     my ($uri) = @_;
1.787     albertel 11284:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11285: 
1.955     raeburn  11286:     my ($udom,$uname,$file);
1.712     albertel 11287:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11288: 	($udom,$uname,$file) =
1.811     albertel 11289: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11290: 	$file = 'userfiles/'.$file;
                   11291:     }
                   11292:     if ($uri =~ m-^/res/-) {
                   11293: 	($udom,$uname) = 
1.807     albertel 11294: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11295: 	$file = $uri;
                   11296:     }
                   11297: 
                   11298:     if (!$udom || !$uname || !$file) {
                   11299: 	# unable to handle the uri
                   11300: 	return ();
                   11301:     }
1.956     raeburn  11302:     my $getpropath;
                   11303:     if ($file =~ /^userfiles\//) {
                   11304:         $getpropath = 1;
                   11305:     }
1.1136    raeburn  11306:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11307:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11308:         return ();
                   11309:     } else {
                   11310:         if (ref($listref) eq 'ARRAY') {
                   11311:             my @stats = split('&',$listref->[0]);
                   11312: 	    shift(@stats); #filename is first
                   11313: 	    return @stats;
                   11314:         }
1.712     albertel 11315:     }
                   11316:     return ();
                   11317: }
                   11318: 
1.26      www      11319: # -------------------------------------------------------- Value of a Condition
                   11320: 
1.713     albertel 11321: # gets the value of a specific preevaluated condition
                   11322: #    stored in the string  $env{user.state.<cid>}
                   11323: # or looks up a condition reference in the bighash and if if hasn't
                   11324: # already been evaluated recurses into docondval to get the value of
                   11325: # the condition, then memoizing it to 
                   11326: #   $env{user.state.<cid>.<condition>}
1.40      www      11327: sub directcondval {
                   11328:     my $number=shift;
1.620     albertel 11329:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11330: 	&Apache::lonuserstate::evalstate();
                   11331:     }
1.713     albertel 11332:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11333: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11334:     } elsif ($number =~ /^_/) {
                   11335: 	my $sub_condition;
                   11336: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11337: 		&GDBM_READER(),0640)) {
                   11338: 	    $sub_condition=$bighash{'conditions'.$number};
                   11339: 	    untie(%bighash);
                   11340: 	}
                   11341: 	my $value = &docondval($sub_condition);
1.949     raeburn  11342: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11343: 	return $value;
                   11344:     }
1.620     albertel 11345:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11346:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11347:     } else {
                   11348:        return 2;
                   11349:     }
                   11350: }
                   11351: 
1.713     albertel 11352: # get the collection of conditions for this resource
1.26      www      11353: sub condval {
                   11354:     my $condidx=shift;
1.54      www      11355:     my $allpathcond='';
1.713     albertel 11356:     foreach my $cond (split(/\|/,$condidx)) {
                   11357: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11358: 	    $allpathcond.=
                   11359: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11360: 	}
1.191     harris41 11361:     }
1.54      www      11362:     $allpathcond=~s/\|$//;
1.713     albertel 11363:     return &docondval($allpathcond);
                   11364: }
                   11365: 
                   11366: #evaluates an expression of conditions
                   11367: sub docondval {
                   11368:     my ($allpathcond) = @_;
                   11369:     my $result=0;
                   11370:     if ($env{'request.course.id'}
                   11371: 	&& defined($allpathcond)) {
                   11372: 	my $operand='|';
                   11373: 	my @stack;
                   11374: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11375: 	    if ($chunk eq '(') {
                   11376: 		push @stack,($operand,$result);
                   11377: 	    } elsif ($chunk eq ')') {
                   11378: 		my $before=pop @stack;
                   11379: 		if (pop @stack eq '&') {
                   11380: 		    $result=$result>$before?$before:$result;
                   11381: 		} else {
                   11382: 		    $result=$result>$before?$result:$before;
                   11383: 		}
                   11384: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11385: 		$operand=$chunk;
                   11386: 	    } else {
                   11387: 		my $new=directcondval($chunk);
                   11388: 		if ($operand eq '&') {
                   11389: 		    $result=$result>$new?$new:$result;
                   11390: 		} else {
                   11391: 		    $result=$result>$new?$result:$new;
                   11392: 		}
                   11393: 	    }
                   11394: 	}
1.26      www      11395:     }
                   11396:     return $result;
1.421     albertel 11397: }
                   11398: 
                   11399: # ---------------------------------------------------- Devalidate courseresdata
                   11400: 
                   11401: sub devalidatecourseresdata {
                   11402:     my ($coursenum,$coursedomain)=@_;
                   11403:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11404:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11405: }
                   11406: 
1.763     www      11407: 
1.200     www      11408: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11409: #
                   11410: #  Parameters:
                   11411: #      $coursenum    - Number of the course.
                   11412: #      $coursedomain - Domain at which the course was created.
                   11413: #  Returns:
                   11414: #     A hash of the course parameters along (I think) with timestamps
                   11415: #     and version info.
1.877     foxr     11416: 
1.624     albertel 11417: sub get_courseresdata {
                   11418:     my ($coursenum,$coursedomain)=@_;
1.200     www      11419:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11420:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11421:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11422:     my %dumpreply;
1.417     albertel 11423:     unless (defined($cached)) {
1.624     albertel 11424: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11425: 	$result=\%dumpreply;
1.251     albertel 11426: 	my ($tmp) = keys(%dumpreply);
                   11427: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11428: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11429: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11430: 	    return $tmp;
1.416     albertel 11431: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11432: 	    $result=undef;
1.599     albertel 11433: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11434: 	}
                   11435:     }
1.624     albertel 11436:     return $result;
                   11437: }
                   11438: 
1.633     albertel 11439: sub devalidateuserresdata {
                   11440:     my ($uname,$udom)=@_;
                   11441:     my $hashid="$udom:$uname";
                   11442:     &devalidate_cache_new('userres',$hashid);
                   11443: }
                   11444: 
1.624     albertel 11445: sub get_userresdata {
                   11446:     my ($uname,$udom)=@_;
                   11447:     #most student don\'t have any data set, check if there is some data
                   11448:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11449: 
                   11450:     my $hashid="$udom:$uname";
                   11451:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11452:     if (!defined($cached)) {
                   11453: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11454: 	$result=\%resourcedata;
                   11455: 	&do_cache_new('userres',$hashid,$result,600);
                   11456:     }
                   11457:     my ($tmp)=keys(%$result);
                   11458:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11459: 	return $result;
                   11460:     }
                   11461:     #error 2 occurs when the .db doesn't exist
                   11462:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11463:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11464: 	    &logthis("<font color=\"blue\">WARNING:".
                   11465: 		     " Trying to get resource data for ".
                   11466: 		     $uname." at ".$udom.": ".
                   11467: 		     $tmp."</font>");
                   11468:         }
1.624     albertel 11469:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11470: 	#&EXT_cache_set($udom,$uname);
                   11471: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11472: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11473:     }
                   11474:     return $tmp;
                   11475: }
1.879     foxr     11476: #----------------------------------------------- resdata - return resource data
                   11477: #  Purpose:
                   11478: #    Return resource data for either users or for a course.
                   11479: #  Parameters:
                   11480: #     $name      - Course/user name.
                   11481: #     $domain    - Name of the domain the user/course is registered on.
                   11482: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11483: #     @which     - Array of names of resources desired.
                   11484: #  Returns:
                   11485: #     The value of the first reasource in @which that is found in the
                   11486: #     resource hash.
                   11487: #  Exceptional Conditions:
                   11488: #     If the $type passed in is not valid (not the string 'course' or 
                   11489: #     'user', an undefined  reference is returned.
                   11490: #     If none of the resources are found, an undef is returned
1.624     albertel 11491: sub resdata {
                   11492:     my ($name,$domain,$type,@which)=@_;
                   11493:     my $result;
                   11494:     if ($type eq 'course') {
                   11495: 	$result=&get_courseresdata($name,$domain);
                   11496:     } elsif ($type eq 'user') {
                   11497: 	$result=&get_userresdata($name,$domain);
                   11498:     }
                   11499:     if (!ref($result)) { return $result; }    
1.251     albertel 11500:     foreach my $item (@which) {
1.927     albertel 11501: 	if (defined($result->{$item->[0]})) {
                   11502: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11503: 	}
1.250     albertel 11504:     }
1.291     albertel 11505:     return undef;
1.200     www      11506: }
                   11507: 
1.1172.2.31  raeburn  11508: sub get_numsuppfiles {
                   11509:     my ($cnum,$cdom,$ignorecache)=@_;
                   11510:     my $hashid=$cnum.':'.$cdom;
                   11511:     my ($suppcount,$cached);
                   11512:     unless ($ignorecache) {
                   11513:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11514:     }
                   11515:     unless (defined($cached)) {
                   11516:         my $chome=&homeserver($cnum,$cdom);
                   11517:         unless ($chome eq 'no_host') {
                   11518:             ($suppcount,my $errors) = (0,0);
                   11519:             my $suppmap = 'supplemental.sequence';
                   11520:             ($suppcount,$errors) =
                   11521:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11522:         }
                   11523:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11524:     }
                   11525:     return $suppcount;
                   11526: }
                   11527: 
1.379     matthew  11528: #
                   11529: # EXT resource caching routines
                   11530: #
                   11531: 
                   11532: sub clear_EXT_cache_status {
1.383     albertel 11533:     &delenv('cache.EXT.');
1.379     matthew  11534: }
                   11535: 
                   11536: sub EXT_cache_status {
                   11537:     my ($target_domain,$target_user) = @_;
1.383     albertel 11538:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11539:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11540:         # We know already the user has no data
                   11541:         return 1;
                   11542:     } else {
                   11543:         return 0;
                   11544:     }
                   11545: }
                   11546: 
                   11547: sub EXT_cache_set {
                   11548:     my ($target_domain,$target_user) = @_;
1.383     albertel 11549:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11550:     #&appenv({$cachename => time});
1.379     matthew  11551: }
                   11552: 
1.28      www      11553: # --------------------------------------------------------- Value of a Variable
1.58      www      11554: sub EXT {
1.715     albertel 11555: 
1.1172.2.28  raeburn  11556:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11557:     unless ($varname) { return ''; }
1.218     albertel 11558:     #get real user name/domain, courseid and symb
                   11559:     my $courseid;
1.359     albertel 11560:     my $publicuser;
1.427     www      11561:     if ($symbparm) {
                   11562: 	$symbparm=&get_symb_from_alias($symbparm);
                   11563:     }
1.218     albertel 11564:     if (!($uname && $udom)) {
1.790     albertel 11565:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11566:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11567:     } else {
1.620     albertel 11568: 	$courseid=$env{'request.course.id'};
1.218     albertel 11569:     }
1.48      www      11570:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11571:     my $rest;
1.320     albertel 11572:     if (defined($therest[0])) {
1.48      www      11573:        $rest=join('.',@therest);
                   11574:     } else {
                   11575:        $rest='';
                   11576:     }
1.320     albertel 11577: 
1.57      www      11578:     my $qualifierrest=$qualifier;
                   11579:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11580:     my $spacequalifierrest=$space;
                   11581:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11582:     if ($realm eq 'user') {
1.48      www      11583: # --------------------------------------------------------------- user.resource
                   11584: 	if ($space eq 'resource') {
1.651     albertel 11585: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11586: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11587: 		 &&
1.1172.2.142  raeburn  11588: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11589: 		# if we are in the middle of processing the resource the
                   11590: 		# get the value we are planning on committing
                   11591:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11592:                     return $Apache::lonhomework::results{$qualifierrest};
                   11593:                 } else {
                   11594:                     return $Apache::lonhomework::history{$qualifierrest};
                   11595:                 }
1.335     albertel 11596: 	    } else {
1.359     albertel 11597: 		my %restored;
1.620     albertel 11598: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11599: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11600: 		} else {
                   11601: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11602: 		}
1.335     albertel 11603: 		return $restored{$qualifierrest};
                   11604: 	    }
1.48      www      11605: # ----------------------------------------------------------------- user.access
                   11606:         } elsif ($space eq 'access') {
1.218     albertel 11607: 	    # FIXME - not supporting calls for a specific user
1.48      www      11608:             return &allowed($qualifier,$rest);
                   11609: # ------------------------------------------ user.preferences, user.environment
                   11610:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11611: 	    if (($uname eq $env{'user.name'}) &&
                   11612: 		($udom eq $env{'user.domain'})) {
                   11613: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11614: 	    } else {
1.359     albertel 11615: 		my %returnhash;
                   11616: 		if (!$publicuser) {
                   11617: 		    %returnhash=&userenvironment($udom,$uname,
                   11618: 						 $qualifierrest);
                   11619: 		}
1.218     albertel 11620: 		return $returnhash{$qualifierrest};
                   11621: 	    }
1.48      www      11622: # ----------------------------------------------------------------- user.course
                   11623:         } elsif ($space eq 'course') {
1.218     albertel 11624: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11625:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11626: # ------------------------------------------------------------------- user.role
                   11627:         } elsif ($space eq 'role') {
1.218     albertel 11628: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11629:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11630:             if ($qualifier eq 'value') {
                   11631: 		return $role;
                   11632:             } elsif ($qualifier eq 'extent') {
                   11633:                 return $where;
                   11634:             }
                   11635: # ----------------------------------------------------------------- user.domain
                   11636:         } elsif ($space eq 'domain') {
1.218     albertel 11637:             return $udom;
1.48      www      11638: # ------------------------------------------------------------------- user.name
                   11639:         } elsif ($space eq 'name') {
1.218     albertel 11640:             return $uname;
1.48      www      11641: # ---------------------------------------------------- Any other user namespace
1.29      www      11642:         } else {
1.359     albertel 11643: 	    my %reply;
                   11644: 	    if (!$publicuser) {
                   11645: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11646: 	    }
                   11647: 	    return $reply{$qualifierrest};
1.48      www      11648:         }
1.236     www      11649:     } elsif ($realm eq 'query') {
                   11650: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11651:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11652: 						[$spacequalifierrest]);
1.620     albertel 11653: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11654:    } elsif ($realm eq 'request') {
1.48      www      11655: # ------------------------------------------------------------- request.browser
                   11656:         if ($space eq 'browser') {
1.1145    bisitz   11657:             return $env{'browser.'.$qualifier};
1.57      www      11658: # ------------------------------------------------------------ request.filename
                   11659:         } else {
1.620     albertel 11660:             return $env{'request.'.$spacequalifierrest};
1.29      www      11661:         }
1.28      www      11662:     } elsif ($realm eq 'course') {
1.48      www      11663: # ---------------------------------------------------------- course.description
1.620     albertel 11664:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11665:     } elsif ($realm eq 'resource') {
1.165     www      11666: 
1.620     albertel 11667: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11668: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11669: 	}
1.693     albertel 11670: 
1.1172.2.30  raeburn  11671:         if ($qualifier eq '') {
                   11672: 	    if ($space eq 'title') {
                   11673: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11674: 	        return &gettitle($symbparm);
                   11675: 	    }
1.693     albertel 11676: 	
1.1172.2.30  raeburn  11677: 	    if ($space eq 'map') {
                   11678: 	        my ($map) = &decode_symb($symbparm);
                   11679: 	        return &symbread($map);
                   11680: 	    }
                   11681:             if ($space eq 'maptitle') {
                   11682:                 my ($map) = &decode_symb($symbparm);
                   11683:                 return &gettitle($map);
                   11684:             }
                   11685: 	    if ($space eq 'filename') {
                   11686: 	        if ($symbparm) {
                   11687: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11688: 	        }
                   11689: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11690: 	    }
1.1172.2.30  raeburn  11691: 
                   11692:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11693:                 if ($space eq 'visibleparts') {
                   11694:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11695:                     my $item;
                   11696:                     if (ref($navmap)) {
                   11697:                         my $res = $navmap->getBySymb($symbparm);
                   11698:                         my $parts = $res->parts();
                   11699:                         if (ref($parts) eq 'ARRAY') {
                   11700:                             $item = join(',',@{$parts});
                   11701:                         }
                   11702:                         undef($navmap);
                   11703:                     }
                   11704:                     return $item;
                   11705:                 }
                   11706:             }
                   11707:         }
1.693     albertel 11708: 
                   11709: 	my ($section, $group, @groups);
1.593     albertel 11710: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11711:         if (($courseid eq '') && ($cid)) {
                   11712:             $courseid = $cid;
                   11713:         }
                   11714: 	if (($symbparm && $courseid) && 
                   11715: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11716: 
1.218     albertel 11717: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11718: 
1.60      www      11719: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11720: 	    my $symbp=$symbparm;
1.735     albertel 11721: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11722: 
                   11723: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11724: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11725: 
1.620     albertel 11726: 	    if (($env{'user.name'} eq $uname) &&
                   11727: 		($env{'user.domain'} eq $udom)) {
                   11728: 		$section=$env{'request.course.sec'};
1.733     raeburn  11729:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11730:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11731: 	    } else {
1.539     albertel 11732: 		if (! defined($usection)) {
1.551     albertel 11733: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11734: 		} else {
                   11735: 		    $section = $usection;
                   11736: 		}
1.733     raeburn  11737:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11738: 	    }
                   11739: 
                   11740: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11741: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11742: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11743: 
1.593     albertel 11744: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11745: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11746: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11747: 
1.60      www      11748: # ----------------------------------------------------------- first, check user
1.624     albertel 11749: 
                   11750: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11751: 				       ([$courselevelr,'resource'],
                   11752: 					[$courselevelm,'map'     ],
                   11753: 					[$courselevel, 'course'  ]));
1.931     albertel 11754: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11755: 
1.594     albertel 11756: # ------------------------------------------------ second, check some of course
1.684     raeburn  11757:             my $coursereply;
1.691     raeburn  11758:             if (@groups > 0) {
                   11759:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11760:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11761:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11762:             }
1.96      www      11763: 
1.684     raeburn  11764: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11765: 				  $env{'course.'.$courseid.'.domain'},
                   11766: 				  'course',
                   11767: 				  ([$seclevelr,   'resource'],
                   11768: 				   [$seclevelm,   'map'     ],
                   11769: 				   [$seclevel,    'course'  ],
                   11770: 				   [$courselevelr,'resource']));
                   11771: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11772: 
1.60      www      11773: # ------------------------------------------------------ third, check map parms
1.218     albertel 11774: 	    my %parmhash=();
                   11775: 	    my $thisparm='';
                   11776: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11777: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11778: 		    &GDBM_READER(),0640)) {
1.218     albertel 11779: 		$thisparm=$parmhash{$symbparm};
                   11780: 		untie(%parmhash);
                   11781: 	    }
1.927     albertel 11782: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11783: 	}
1.594     albertel 11784: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11785: 
1.218     albertel 11786: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11787: 	my $filename;
                   11788: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11789: 	if ($symbparm) {
1.409     www      11790: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11791: 	} else {
1.620     albertel 11792: 	    $filename=$env{'request.filename'};
1.282     albertel 11793: 	}
                   11794: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11795: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11796: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11797: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11798: 
1.927     albertel 11799: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11800: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11801: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11802: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11803: 				     $env{'course.'.$courseid.'.domain'},
                   11804: 				     'course',
1.927     albertel 11805: 				     ([$courselevelm,'map'   ],
                   11806: 				      [$courselevel, 'course']));
                   11807: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11808: 	}
1.145     www      11809: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11810: 	unless ($space eq '0') {
1.336     albertel 11811: 	    my @parts=split(/_/,$space);
                   11812: 	    my $id=pop(@parts);
                   11813: 	    my $part=join('_',@parts);
                   11814: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11815: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11816: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11817: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11818: 	}
1.395     albertel 11819: 	if ($recurse) { return undef; }
                   11820: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11821: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11822: # ---------------------------------------------------- Any other user namespace
                   11823:     } elsif ($realm eq 'environment') {
                   11824: # ----------------------------------------------------------------- environment
1.620     albertel 11825: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11826: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11827: 	} else {
1.770     albertel 11828: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11829: 		return '';
                   11830: 	    }
1.219     albertel 11831: 	    my %returnhash=&userenvironment($udom,$uname,
                   11832: 					    $spacequalifierrest);
                   11833: 	    return $returnhash{$spacequalifierrest};
                   11834: 	}
1.28      www      11835:     } elsif ($realm eq 'system') {
1.48      www      11836: # ----------------------------------------------------------------- system.time
                   11837: 	if ($space eq 'time') {
                   11838: 	    return time;
                   11839:         }
1.696     albertel 11840:     } elsif ($realm eq 'server') {
                   11841: # ----------------------------------------------------------------- system.time
                   11842: 	if ($space eq 'name') {
                   11843: 	    return $ENV{'SERVER_NAME'};
                   11844:         }
1.28      www      11845:     }
1.48      www      11846:     return '';
1.61      www      11847: }
                   11848: 
1.927     albertel 11849: sub get_reply {
                   11850:     my ($reply_value) = @_;
1.940     raeburn  11851:     if (ref($reply_value) eq 'ARRAY') {
                   11852:         if (wantarray) {
                   11853: 	    return @$reply_value;
                   11854:         }
                   11855:         return $reply_value->[0];
                   11856:     } else {
                   11857:         return $reply_value;
1.927     albertel 11858:     }
                   11859: }
                   11860: 
1.691     raeburn  11861: sub check_group_parms {
                   11862:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11863:     my @groupitems = ();
                   11864:     my $resultitem;
1.927     albertel 11865:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11866:     foreach my $group (@{$groups}) {
                   11867:         foreach my $level (@levels) {
1.927     albertel 11868:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11869:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11870:         }
                   11871:     }
                   11872:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11873:                             $env{'course.'.$courseid.'.domain'},
                   11874:                                      'course',@groupitems);
                   11875:     return $coursereply;
                   11876: }
                   11877: 
                   11878: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11879:     my ($courseid,@groups) = @_;
                   11880:     @groups = sort(@groups);
1.691     raeburn  11881:     return @groups;
                   11882: }
                   11883: 
1.395     albertel 11884: sub packages_tab_default {
                   11885:     my ($uri,$varname)=@_;
                   11886:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11887: 
                   11888:     my (@extension,@specifics,$do_default);
                   11889:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11890: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11891: 	if ($pack_type eq 'default') {
                   11892: 	    $do_default=1;
                   11893: 	} elsif ($pack_type eq 'extension') {
                   11894: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11895: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11896: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11897: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11898: 	}
                   11899:     }
                   11900:     # first look for a package that matches the requested part id
                   11901:     foreach my $package (@specifics) {
                   11902: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11903: 	next if ($pack_part ne $part);
                   11904: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11905: 	    return $packagetab{"$pack_type&$name&default"};
                   11906: 	}
                   11907:     }
                   11908:     # look for any possible matching non extension_ package
                   11909:     foreach my $package (@specifics) {
                   11910: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11911: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11912: 	    return $packagetab{"$pack_type&$name&default"};
                   11913: 	}
1.585     albertel 11914: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11915: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11916: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11917: 	}
                   11918:     }
1.738     albertel 11919:     # look for any posible extension_ match
                   11920:     foreach my $package (@extension) {
                   11921: 	my ($package,$pack_type)=@{$package};
                   11922: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11923: 	    return $packagetab{"$pack_type&$name&default"};
                   11924: 	}
                   11925: 	if (defined($packagetab{$package."&$name&default"})) {
                   11926: 	    return $packagetab{$package."&$name&default"};
                   11927: 	}
                   11928:     }
                   11929:     # look for a global default setting
                   11930:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11931: 	return $packagetab{"default&$name&default"};
                   11932:     }
1.395     albertel 11933:     return undef;
                   11934: }
                   11935: 
1.334     albertel 11936: sub add_prefix_and_part {
                   11937:     my ($prefix,$part)=@_;
                   11938:     my $keyroot;
                   11939:     if (defined($prefix) && $prefix !~ /^__/) {
                   11940: 	# prefix that has a part already
                   11941: 	$keyroot=$prefix;
                   11942:     } elsif (defined($prefix)) {
                   11943: 	# prefix that is missing a part
                   11944: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11945:     } else {
                   11946: 	# no prefix at all
                   11947: 	if (defined($part)) { $keyroot='_'.$part; }
                   11948:     }
                   11949:     return $keyroot;
                   11950: }
                   11951: 
1.71      www      11952: # ---------------------------------------------------------------- Get metadata
                   11953: 
1.599     albertel 11954: my %metaentry;
1.1070    www      11955: my %importedpartids;
1.1172.2.99  raeburn  11956: my %importedrespids;
1.71      www      11957: sub metadata {
1.176     www      11958:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11959:     $uri=&declutter($uri);
1.288     albertel 11960:     # if it is a non metadata possible uri return quickly
1.529     albertel 11961:     if (($uri eq '') || 
                   11962: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11963: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11964:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11965: 	return undef;
                   11966:     }
1.1172.2.49  raeburn  11967:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11968: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11969: 	return undef;
1.288     albertel 11970:     }
1.73      www      11971:     my $filename=$uri;
                   11972:     $uri=~s/\.meta$//;
1.172     www      11973: #
                   11974: # Is the metadata already cached?
1.177     www      11975: # Look at timestamp of caching
1.172     www      11976: # Everything is cached by the main uri, libraries are never directly cached
                   11977: #
1.428     albertel 11978:     if (!defined($liburi)) {
1.599     albertel 11979: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11980: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11981:     }
                   11982:     {
1.1069    www      11983: # Imported parts would go here
1.1172.2.99  raeburn  11984:         my @origfiletagids=();
1.1069    www      11985:         my $importedparts=0;
1.1172.2.99  raeburn  11986: 
                   11987: # Imported responseids would go here
                   11988:         my $importedresponses=0;
1.172     www      11989: #
                   11990: # Is this a recursive call for a library?
                   11991: #
1.599     albertel 11992: #	if (! exists($metacache{$uri})) {
                   11993: #	    $metacache{$uri}={};
                   11994: #	}
1.924     albertel 11995: 	my $cachetime = 60*60;
1.171     www      11996:         if ($liburi) {
                   11997: 	    $liburi=&declutter($liburi);
                   11998:             $filename=$liburi;
1.401     bowersj2 11999:         } else {
1.599     albertel 12000: 	    &devalidate_cache_new('meta',$uri);
                   12001: 	    undef(%metaentry);
1.401     bowersj2 12002: 	}
1.140     www      12003:         my %metathesekeys=();
1.73      www      12004:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12005: 	my $metastring;
1.1140    www      12006: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12007: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12008: 	    $metastring = 
1.929     albertel 12009: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12010: 					  ('grade_target' => 'meta'));
                   12011: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12012: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12013:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12014: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12015: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12016: 	    $metastring=&getfile($file);
1.489     albertel 12017: 	}
1.208     albertel 12018:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12019:         my $token;
1.140     www      12020:         undef %metathesekeys;
1.71      www      12021:         while ($token=$parser->get_token) {
1.339     albertel 12022: 	    if ($token->[0] eq 'S') {
                   12023: 		if (defined($token->[2]->{'package'})) {
1.172     www      12024: #
                   12025: # This is a package - get package info
                   12026: #
1.339     albertel 12027: 		    my $package=$token->[2]->{'package'};
                   12028: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12029: 		    if (defined($token->[2]->{'id'})) { 
                   12030: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12031: 		    }
1.599     albertel 12032: 		    if ($metaentry{':packages'}) {
                   12033: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12034: 		    } else {
1.599     albertel 12035: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12036: 		    }
1.736     albertel 12037: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12038: 			my $part=$keyroot;
                   12039: 			$part=~s/^\_//;
1.736     albertel 12040: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12041: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12042: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12043: 			    # ignore package.tab specified default values
                   12044:                             # here &package_tab_default() will fetch those
                   12045: 			    if ($subp eq 'default') { next; }
1.736     albertel 12046: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12047: 			    my $unikey;
                   12048: 			    if ($pack =~ /_0$/) {
                   12049: 				$unikey='parameter_0_'.$name;
                   12050: 				$part=0;
                   12051: 			    } else {
                   12052: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12053: 			    }
1.339     albertel 12054: 			    if ($subp eq 'display') {
                   12055: 				$value.=' [Part: '.$part.']';
                   12056: 			    }
1.599     albertel 12057: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12058: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12059: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12060: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12061: 			    }
1.599     albertel 12062: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12063: 				$metaentry{':'.$unikey}=
                   12064: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12065: 			    }
1.339     albertel 12066: 			}
                   12067: 		    }
                   12068: 		} else {
1.172     www      12069: #
                   12070: # This is not a package - some other kind of start tag
1.339     albertel 12071: #
                   12072: 		    my $entry=$token->[1];
1.1068    www      12073: 		    my $unikey='';
1.175     www      12074: 
1.339     albertel 12075: 		    if ($entry eq 'import') {
1.175     www      12076: #
                   12077: # Importing a library here
1.339     albertel 12078: #
1.1067    www      12079:                         my $location=$parser->get_text('/import');
                   12080:                         my $dir=$filename;
                   12081:                         $dir=~s|[^/]*$||;
                   12082:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12083: 
                   12084:                         my $importid=$token->[2]->{'id'};
1.1068    www      12085:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12086: #
                   12087: # Check metadata for imported file to
                   12088: # see if it contained response items
                   12089: #
                   12090:                         my %currmetaentry = %metaentry;
                   12091:                         my $libresponseorder = &metadata($location,'responseorder');
                   12092:                         my $origfile;
                   12093:                         if ($libresponseorder ne '') {
                   12094:                             if ($#origfiletagids<0) {
                   12095:                                 undef(%importedrespids);
                   12096:                                 undef(%importedpartids);
                   12097:                             }
                   12098:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12099:                             if (@{$importedrespids{$importid}} > 0) {
                   12100:                                 $importedresponses = 1;
                   12101: # We need to get the original file and the imported file to get the response order correct
                   12102: # Load and inspect original file
                   12103:                                 if ($#origfiletagids<0) {
                   12104:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12105:                                     $origfile=&getfile($origfilelocation);
                   12106:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12107:                                 }
                   12108:                             }
                   12109:                         }
                   12110: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12111: # hash populated for imported library file
                   12112:                         %metaentry = %currmetaentry;
                   12113:                         undef(%currmetaentry);
1.1068    www      12114:                         if ($importmode eq 'problem') {
1.1069    www      12115: # Import as problem/response
1.1068    www      12116:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12117:                         } elsif ($importmode eq 'part') {
                   12118: # Import as part(s)
1.1069    www      12119:                            $importedparts=1;
                   12120: # We need to get the original file and the imported file to get the part order correct
                   12121: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12122: # Load and inspect original file if we didn't do that already
                   12123:                            if ($#origfiletagids<0) {
                   12124:                                undef(%importedrespids);
                   12125:                                undef(%importedpartids);
                   12126:                                if ($origfile eq '') {
                   12127:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12128:                                    $origfile=&getfile($origfilelocation);
                   12129:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12130:                                }
1.1070    www      12131:                            }
                   12132: 
1.1069    www      12133: # Load and inspect imported file
                   12134:                            my $impfile=&getfile($location);
                   12135:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12136:                            if ($#impfilepartids>=0) {
                   12137: # This problem had parts
1.1070    www      12138:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12139:                            } else {
                   12140: # Importing by turning a single problem into a problem part
                   12141: # It gets the import-tags ID as part-ID
                   12142:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12143:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12144:                            }
1.1068    www      12145:                         } else {
                   12146: # Normal import
                   12147:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12148:                            if (defined($token->[2]->{'id'})) {
                   12149:                               $unikey.='_'.$token->[2]->{'id'};
                   12150:                            }
1.1067    www      12151:                         }
                   12152: 
1.339     albertel 12153: 			if ($depthcount<20) {
1.736     albertel 12154: 			    my $metadata = 
                   12155: 				&metadata($uri,'keys', $location,$unikey,
                   12156: 					  $depthcount+1);
                   12157: 			    foreach my $meta (split(',',$metadata)) {
                   12158: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12159: 				$metathesekeys{$meta}=1;
1.339     albertel 12160: 			    }
1.1068    www      12161: 			
                   12162:                         }
1.1067    www      12163: 		    } else {
                   12164: #
                   12165: # Not importing, some other kind of non-package, non-library start tag
                   12166: # 
                   12167:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12168:                         if (defined($token->[2]->{'id'})) {
                   12169:                             $unikey.='_'.$token->[2]->{'id'};
                   12170:                         }
1.339     albertel 12171: 			if (defined($token->[2]->{'name'})) { 
                   12172: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12173: 			}
                   12174: 			$metathesekeys{$unikey}=1;
1.736     albertel 12175: 			foreach my $param (@{$token->[3]}) {
                   12176: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12177: 				$token->[2]->{$param};
1.339     albertel 12178: 			}
                   12179: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12180: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12181: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12182: 		 # only ws inside the tag, and not in default, so use default
                   12183: 		 # as value
1.599     albertel 12184: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12185: 			} elsif ( $internaltext =~ /\S/ ) {
                   12186: 		  # something interesting inside the tag
                   12187: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12188: 			} else {
1.908     albertel 12189: 		  # no interesting values, don't set a default
1.339     albertel 12190: 			}
1.172     www      12191: # end of not-a-package not-a-library import
1.339     albertel 12192: 		    }
1.172     www      12193: # end of not-a-package start tag
1.339     albertel 12194: 		}
1.172     www      12195: # the next is the end of "start tag"
1.339     albertel 12196: 	    }
                   12197: 	}
1.483     albertel 12198: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12199: 	$extension = lc($extension);
                   12200: 	if ($extension eq 'htm') { $extension='html'; }
                   12201: 
1.737     albertel 12202: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12203: 	    #no specific packages #how's our extension
                   12204: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12205: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12206: 					 \%metathesekeys);
                   12207: 	}
1.883     albertel 12208: 
                   12209: 	if (!exists($metaentry{':packages'})
                   12210: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12211: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12212: 		#no specific packages well let's get default then
                   12213: 		if ($key!~/^default&/) { next; }
1.488     albertel 12214: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12215: 					     \%metathesekeys);
                   12216: 	    }
                   12217: 	}
1.338     www      12218: # are there custom rights to evaluate
1.599     albertel 12219: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12220: 
1.338     www      12221:     #
                   12222:     # Importing a rights file here
1.339     albertel 12223:     #
                   12224: 	    unless ($depthcount) {
1.599     albertel 12225: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12226: 		my $dir=$filename;
                   12227: 		$dir=~s|[^/]*$||;
                   12228: 		$location=&filelocation($dir,$location);
1.736     albertel 12229: 		my $rights_metadata =
                   12230: 		    &metadata($uri,'keys',$location,'_rights',
                   12231: 			      $depthcount+1);
                   12232: 		foreach my $rights (split(',',$rights_metadata)) {
                   12233: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12234: 		    $metathesekeys{$rights}=1;
1.339     albertel 12235: 		}
                   12236: 	    }
                   12237: 	}
1.737     albertel 12238: 	# uniqifiy package listing
                   12239: 	my %seen;
                   12240: 	my @uniq_packages =
                   12241: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12242: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12243: 
1.1172.2.99  raeburn  12244:         if (($importedresponses) || ($importedparts)) {
                   12245:             if ($importedparts) {
1.1070    www      12246: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12247:                 $metaentry{':partorder'}='';
                   12248:                 $metathesekeys{'partorder'}=1;
                   12249:             }
                   12250:             if ($importedresponses) {
                   12251: # We had imported responses and need to rebuild responseorder
                   12252:                 $metaentry{':responseorder'}='';
                   12253:                 $metathesekeys{'responseorder'}=1;
                   12254:             }
                   12255:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12256:                 my $origid = $origfiletagids[$index+1];
                   12257:                 if ($origfiletagids[$index] eq 'part') {
                   12258: # Original part, part of the problem
                   12259:                     if ($importedparts) {
                   12260:                         $metaentry{':partorder'}.=','.$origid;
                   12261:                     }
                   12262:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12263:                     if ($importedparts) {
                   12264: # We have imported parts at this position
                   12265:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12266:                     }
                   12267:                     if ($importedresponses) {
                   12268: # We have imported responses at this position
                   12269:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12270:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12271:                         }
                   12272:                     }
                   12273:                 } else {
                   12274: # Original response item, part of the problem
                   12275:                     if ($importedresponses) {
                   12276:                         $metaentry{':responseorder'}.=','.$origid;
                   12277:                     }
                   12278:                 }
                   12279:             }
                   12280:             if ($importedparts) {
                   12281:                 $metaentry{':partorder'}=~s/^\,//;
                   12282:             }
                   12283:             if ($importedresponses) {
                   12284:                 $metaentry{':responseorder'}=~s/^\,//;
                   12285:             }
1.1070    www      12286:         }
                   12287: 
1.737     albertel 12288: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12289: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12290: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12291: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12292: # this is the end of "was not already recently cached
1.71      www      12293:     }
1.599     albertel 12294:     return $metaentry{':'.$what};
1.261     albertel 12295: }
                   12296: 
1.488     albertel 12297: sub metadata_create_package_def {
1.483     albertel 12298:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12299:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12300:     if ($subp eq 'default') { next; }
                   12301:     
1.599     albertel 12302:     if (defined($metaentry{':packages'})) {
                   12303: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12304:     } else {
1.599     albertel 12305: 	$metaentry{':packages'}=$package;
1.483     albertel 12306:     }
                   12307:     my $value=$packagetab{$key};
                   12308:     my $unikey;
                   12309:     $unikey='parameter_0_'.$name;
1.599     albertel 12310:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12311:     $$metathesekeys{$unikey}=1;
1.599     albertel 12312:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12313: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12314:     }
1.599     albertel 12315:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12316: 	$metaentry{':'.$unikey}=
                   12317: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12318:     }
                   12319: }
                   12320: 
1.261     albertel 12321: sub metadata_generate_part0 {
                   12322:     my ($metadata,$metacache,$uri) = @_;
                   12323:     my %allnames;
1.737     albertel 12324:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12325: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12326: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12327: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12328: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12329: 	    $allnames{$name}=$part;
                   12330: 	  }
                   12331: 	}
                   12332:     }
                   12333:     foreach my $name (keys(%allnames)) {
                   12334:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12335:       my $key=":parameter_0_$name";
1.261     albertel 12336:       $$metacache{"$key.part"}='0';
                   12337:       $$metacache{"$key.name"}=$name;
1.428     albertel 12338:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12339: 					   $allnames{$name}.'_'.$name.
                   12340: 					   '.type'};
1.428     albertel 12341:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12342: 			     '.display'};
1.644     www      12343:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12344:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12345:       $$metacache{"$key.display"}=$olddis;
                   12346:     }
1.71      www      12347: }
                   12348: 
1.764     albertel 12349: # ------------------------------------------------------ Devalidate title cache
                   12350: 
                   12351: sub devalidate_title_cache {
                   12352:     my ($url)=@_;
                   12353:     if (!$env{'request.course.id'}) { return; }
                   12354:     my $symb=&symbread($url);
                   12355:     if (!$symb) { return; }
                   12356:     my $key=$env{'request.course.id'}."\0".$symb;
                   12357:     &devalidate_cache_new('title',$key);
                   12358: }
                   12359: 
1.1014    droeschl 12360: # ------------------------------------------------- Get the title of a course
                   12361: 
                   12362: sub current_course_title {
                   12363:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12364: }
1.301     www      12365: # ------------------------------------------------- Get the title of a resource
                   12366: 
                   12367: sub gettitle {
                   12368:     my $urlsymb=shift;
                   12369:     my $symb=&symbread($urlsymb);
1.534     albertel 12370:     if ($symb) {
1.620     albertel 12371: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12372: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12373: 	if (defined($cached)) { 
                   12374: 	    return $result;
                   12375: 	}
1.534     albertel 12376: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12377: 	my $title='';
1.907     albertel 12378: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12379: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12380: 	} else {
                   12381: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12382: 		    &GDBM_READER(),0640)) {
                   12383: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12384: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12385: 		untie(%bighash);
                   12386: 	    }
1.534     albertel 12387: 	}
                   12388: 	$title=~s/\&colon\;/\:/gs;
                   12389: 	if ($title) {
1.1159    www      12390: # Remember both $symb and $title for dynamic metadata
                   12391:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12392:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12393: # Cache this title and then return it
1.599     albertel 12394: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12395: 	}
                   12396: 	$urlsymb=$url;
                   12397:     }
                   12398:     my $title=&metadata($urlsymb,'title');
                   12399:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12400:     return $title;
1.301     www      12401: }
1.613     albertel 12402: 
1.614     albertel 12403: sub get_slot {
                   12404:     my ($which,$cnum,$cdom)=@_;
                   12405:     if (!$cnum || !$cdom) {
1.790     albertel 12406: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12407: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12408: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12409:     }
1.703     albertel 12410:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12411:     my %slotinfo;
                   12412:     if (exists($remembered{$key})) {
                   12413: 	$slotinfo{$which} = $remembered{$key};
                   12414:     } else {
                   12415: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12416: 	&Apache::lonhomework::showhash(%slotinfo);
                   12417: 	my ($tmp)=keys(%slotinfo);
                   12418: 	if ($tmp=~/^error:/) { return (); }
                   12419: 	$remembered{$key} = $slotinfo{$which};
                   12420:     }
1.616     albertel 12421:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12422: 	return %{$slotinfo{$which}};
                   12423:     }
                   12424:     return $slotinfo{$which};
1.614     albertel 12425: }
1.1150    raeburn  12426: 
                   12427: sub get_reservable_slots {
                   12428:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12429:     my $now = time;
                   12430:     my $reservable_info;
                   12431:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12432:     if (exists($remembered{$key})) {
                   12433:         $reservable_info = $remembered{$key};
                   12434:     } else {
                   12435:         my %resv;
                   12436:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12437:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12438:         $reservable_info = \%resv;
                   12439:         $remembered{$key} = $reservable_info;
                   12440:     }
                   12441:     return $reservable_info;
                   12442: }
                   12443: 
                   12444: sub get_course_slots {
                   12445:     my ($cnum,$cdom) = @_;
                   12446:     my $hashid=$cnum.':'.$cdom;
                   12447:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12448:     if (defined($cached)) {
                   12449:         if (ref($result) eq 'HASH') {
                   12450:             return %{$result};
                   12451:         }
                   12452:     } else {
                   12453:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12454:         my ($tmp) = keys(%slots);
                   12455:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12456:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12457:             return %slots;
                   12458:         }
                   12459:     }
                   12460:     return;
                   12461: }
                   12462: 
                   12463: sub devalidate_slots_cache {
                   12464:     my ($cnum,$cdom)=@_;
                   12465:     my $hashid=$cnum.':'.$cdom;
                   12466:     &devalidate_cache_new('allslots',$hashid);
                   12467: }
                   12468: 
1.1172.2.8  raeburn  12469: sub get_coursechange {
                   12470:     my ($cdom,$cnum) = @_;
                   12471:     if ($cdom eq '' || $cnum eq '') {
                   12472:         return unless ($env{'request.course.id'});
                   12473:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12474:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12475:     }
                   12476:     my $hashid=$cdom.'_'.$cnum;
                   12477:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12478:     if ((defined($cached)) && ($change ne '')) {
                   12479:         return $change;
                   12480:     } else {
                   12481:         my %crshash;
                   12482:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12483:         if ($crshash{'internal.contentchange'} eq '') {
                   12484:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12485:             if ($change eq '') {
                   12486:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12487:                 $change = $crshash{'internal.created'};
                   12488:             }
                   12489:         } else {
                   12490:             $change = $crshash{'internal.contentchange'};
                   12491:         }
                   12492:         my $cachetime = 600;
                   12493:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12494:     }
                   12495:     return $change;
                   12496: }
                   12497: 
                   12498: sub devalidate_coursechange_cache {
                   12499:     my ($cnum,$cdom)=@_;
                   12500:     my $hashid=$cnum.':'.$cdom;
                   12501:     &devalidate_cache_new('crschange',$hashid);
                   12502: }
                   12503: 
1.31      www      12504: # ------------------------------------------------- Update symbolic store links
                   12505: 
                   12506: sub symblist {
                   12507:     my ($mapname,%newhash)=@_;
1.438     www      12508:     $mapname=&deversion(&declutter($mapname));
1.31      www      12509:     my %hash;
1.620     albertel 12510:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12511:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12512:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12513: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12514: 		next if ($url eq 'last_known'
                   12515: 			 && $env{'form.no_update_last_known'});
                   12516: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12517: 						    $newhash{$url}->[1],
                   12518: 						    $newhash{$url}->[0]);
1.191     harris41 12519:             }
1.31      www      12520:             if (untie(%hash)) {
                   12521: 		return 'ok';
                   12522:             }
                   12523:         }
                   12524:     }
                   12525:     return 'error';
1.212     www      12526: }
                   12527: 
                   12528: # --------------------------------------------------------------- Verify a symb
                   12529: 
                   12530: sub symbverify {
1.1172.2.11  raeburn  12531:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12532:     my $thisfn=$thisurl;
1.439     www      12533:     $thisfn=&declutter($thisfn);
1.215     www      12534: # direct jump to resource in page or to a sequence - will construct own symbs
                   12535:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12536: # check URL part
1.409     www      12537:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12538: 
1.431     www      12539:     unless ($url eq $thisfn) { return 0; }
1.213     www      12540: 
1.216     www      12541:     $symb=&symbclean($symb);
1.510     www      12542:     $thisurl=&deversion($thisurl);
1.439     www      12543:     $thisfn=&deversion($thisfn);
1.213     www      12544: 
                   12545:     my %bighash;
                   12546:     my $okay=0;
1.431     www      12547: 
1.620     albertel 12548:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12549:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12550:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12551:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12552:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12553:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12554:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12555:             }
                   12556:         }
                   12557:         my $ids;
1.1172.2.122  raeburn  12558:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12559:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12560:         } else {
                   12561:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12562:         }
1.1102    raeburn  12563:         unless ($ids) {
1.1172.2.13  raeburn  12564:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12565:             $ids=$bighash{$idkey};
1.216     www      12566:         }
                   12567:         if ($ids) {
                   12568: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12569:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12570:                 $symb =~ s/\?.+$//;
                   12571:             }
1.800     albertel 12572: 	    foreach my $id (split(/\,/,$ids)) {
                   12573: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12574:                if (
                   12575:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12576:    eq $symb) {
1.1172.2.11  raeburn  12577:                    if (ref($encstate)) {
                   12578:                        $$encstate = $bighash{'encrypted_'.$id};
                   12579:                    }
1.1172.2.13  raeburn  12580:                    if (($env{'request.role.adv'}) ||
                   12581:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12582:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12583:                        $okay=1;
                   12584:                        last;
                   12585:                    }
                   12586:                }
                   12587:            }
1.216     www      12588:         }
1.213     www      12589: 	untie(%bighash);
                   12590:     }
                   12591:     return $okay;
1.31      www      12592: }
                   12593: 
1.210     www      12594: # --------------------------------------------------------------- Clean-up symb
                   12595: 
                   12596: sub symbclean {
                   12597:     my $symb=shift;
1.568     albertel 12598:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12599: # remove version from map
                   12600:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12601: 
1.210     www      12602: # remove version from URL
                   12603:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12604: 
1.507     www      12605: # remove wrapper
                   12606: 
1.510     www      12607:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12608:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12609:     return $symb;
1.409     www      12610: }
                   12611: 
                   12612: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12613: 
                   12614: sub encode_symb {
                   12615:     my ($map,$resid,$url)=@_;
                   12616:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12617: }
1.409     www      12618: 
                   12619: sub decode_symb {
1.568     albertel 12620:     my $symb=shift;
                   12621:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12622:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12623:     return (&fixversion($map),$resid,&fixversion($url));
                   12624: }
                   12625: 
                   12626: sub fixversion {
                   12627:     my $fn=shift;
1.609     banghart 12628:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12629:     my %bighash;
                   12630:     my $uri=&clutter($fn);
1.620     albertel 12631:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12632: # is this cached?
1.599     albertel 12633:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12634:     if (defined($cached)) { return $result; }
                   12635: # unfortunately not cached, or expired
1.620     albertel 12636:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12637: 	    &GDBM_READER(),0640)) {
                   12638:  	if ($bighash{'version_'.$uri}) {
                   12639:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12640:  	    unless (($version eq 'mostrecent') || 
                   12641: 		    ($version==&getversion($uri))) {
1.440     www      12642:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12643:  	    }
                   12644:  	}
                   12645:  	untie %bighash;
1.413     www      12646:     }
1.599     albertel 12647:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12648: }
                   12649: 
                   12650: sub deversion {
                   12651:     my $url=shift;
                   12652:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12653:     return $url;
1.210     www      12654: }
                   12655: 
1.31      www      12656: # ------------------------------------------------------ Return symb list entry
                   12657: 
                   12658: sub symbread {
1.1172.2.126  raeburn  12659:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12660:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12661:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12662:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12663:         unless (ref($possibles) eq 'HASH') {
                   12664:             if ($ignorecachednull) {
                   12665:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12666:             } else {
                   12667:                 return $env{$cache_str};
                   12668:             }
1.1172.2.66  raeburn  12669:         }
                   12670:     }
1.242     www      12671: # no filename provided? try from environment
1.1172.2.54  raeburn  12672:     unless ($thisfn) {
1.620     albertel 12673:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12674:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12675:         }
                   12676:         $thisfn=$env{'request.filename'};
1.44      www      12677:     }
1.569     albertel 12678:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12679: # is that filename actually a symb? Verify, clean, and return
                   12680:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12681: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12682: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12683: 	}
1.242     www      12684:     }
1.44      www      12685:     $thisfn=declutter($thisfn);
1.31      www      12686:     my %hash;
1.37      www      12687:     my %bighash;
                   12688:     my $syval='';
1.620     albertel 12689:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12690:         my $targetfn = $thisfn;
1.609     banghart 12691:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12692:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12693:         }
1.687     albertel 12694: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12695: 	    $targetfn=$1;
                   12696: 	}
1.1172.2.128  raeburn  12697:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12698:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12699:                           &GDBM_READER(),0640)) {
                   12700: 	        $syval=$hash{$targetfn};
                   12701:                 untie(%hash);
                   12702:             }
1.1172.2.128  raeburn  12703:             if ($syval && $checkforblock) {
                   12704:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12705:                 if (@blockers) {
                   12706:                     $syval='';
                   12707:                 }
                   12708:             }
1.37      www      12709:         }
                   12710: # ---------------------------------------------------------- There was an entry
                   12711:         if ($syval) {
1.601     albertel 12712: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12713: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12714: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12715: 		    #return $env{$cache_str}='';
1.601     albertel 12716: 		#}    
                   12717: 		#$syval.=$1;
                   12718: 	    #}
1.37      www      12719:         } else {
                   12720: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12721:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12722:                             &GDBM_READER(),0640)) {
1.37      www      12723: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12724:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12725:               unless ($ids) { 
                   12726:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12727:               }
                   12728:               unless ($ids) {
                   12729: # alias?
                   12730: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12731:               }
1.37      www      12732:               if ($ids) {
                   12733: # ------------------------------------------------------------------- Has ID(s)
                   12734:                  my @possibilities=split(/\,/,$ids);
1.39      www      12735:                  if ($#possibilities==0) {
                   12736: # ----------------------------------------------- There is only one possibility
1.37      www      12737: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12738: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12739: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12740:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12741:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12742:                              $possibles->{$syval} = 1;
                   12743:                          }
1.1172.2.66  raeburn  12744:                      }
                   12745:                      if ($checkforblock) {
1.1172.2.126  raeburn  12746:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12747:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12748:                              if (@blockers) {
                   12749:                                  $syval = '';
                   12750:                                  untie(%bighash);
                   12751:                                  return $env{$cache_str}='';
                   12752:                              }
1.1172.2.66  raeburn  12753:                          }
                   12754:                      }
                   12755:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12756: # ------------------------------------------ There is more than one possibility
                   12757:                      my $realpossible=0;
1.800     albertel 12758:                      foreach my $id (@possibilities) {
                   12759: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12760:                          my $canaccess;
                   12761:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12762:                              $canaccess = 1;
                   12763:                          } else {
                   12764:                              $canaccess = &allowed('bre',$file);
                   12765:                          }
                   12766:                          if ($canaccess) {
                   12767:          		     my ($mapid,$resid)=split(/\./,$id);
                   12768:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12769:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12770:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12771:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12772:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12773:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12774:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12775:                                      if (@blockers > 0) {
                   12776:                                          $syval = '';
                   12777:                                      } else {
1.1172.2.66  raeburn  12778:                                          $syval = $poss_syval;
                   12779:                                          $realpossible++;
                   12780:                                      }
                   12781:                                  } else {
                   12782:                                      $syval = $poss_syval;
                   12783:                                      $realpossible++;
                   12784:                                  }
1.1172.2.126  raeburn  12785:                                  if ($syval) {
                   12786:                                      if (ref($possibles) eq 'HASH') {
                   12787:                                          $possibles->{$syval} = 1;
                   12788:                                      }
                   12789:                                  }
1.1172.2.66  raeburn  12790:                              }
1.39      www      12791: 			 }
1.191     harris41 12792:                      }
1.39      www      12793: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12794:                  } else {
                   12795:                      $syval='';
1.37      www      12796:                  }
                   12797: 	      }
1.1172.2.66  raeburn  12798:               untie(%bighash);
1.481     raeburn  12799:            }
1.31      www      12800:         }
1.62      www      12801:         if ($syval) {
1.1172.2.128  raeburn  12802: 	    return $env{$cache_str}=$syval;
1.62      www      12803:         }
1.31      www      12804:     }
1.949     raeburn  12805:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12806:     return $env{$cache_str}='';
1.31      www      12807: }
                   12808: 
                   12809: # ---------------------------------------------------------- Return random seed
                   12810: 
1.32      www      12811: sub numval {
                   12812:     my $txt=shift;
                   12813:     $txt=~tr/A-J/0-9/;
                   12814:     $txt=~tr/a-j/0-9/;
                   12815:     $txt=~tr/K-T/0-9/;
                   12816:     $txt=~tr/k-t/0-9/;
                   12817:     $txt=~tr/U-Z/0-5/;
                   12818:     $txt=~tr/u-z/0-5/;
                   12819:     $txt=~s/\D//g;
1.564     albertel 12820:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12821:     return int($txt);
1.368     albertel 12822: }
                   12823: 
1.484     albertel 12824: sub numval2 {
                   12825:     my $txt=shift;
                   12826:     $txt=~tr/A-J/0-9/;
                   12827:     $txt=~tr/a-j/0-9/;
                   12828:     $txt=~tr/K-T/0-9/;
                   12829:     $txt=~tr/k-t/0-9/;
                   12830:     $txt=~tr/U-Z/0-5/;
                   12831:     $txt=~tr/u-z/0-5/;
                   12832:     $txt=~s/\D//g;
                   12833:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12834:     my $total;
                   12835:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12836:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12837:     return int($total);
                   12838: }
                   12839: 
1.575     albertel 12840: sub numval3 {
                   12841:     use integer;
                   12842:     my $txt=shift;
                   12843:     $txt=~tr/A-J/0-9/;
                   12844:     $txt=~tr/a-j/0-9/;
                   12845:     $txt=~tr/K-T/0-9/;
                   12846:     $txt=~tr/k-t/0-9/;
                   12847:     $txt=~tr/U-Z/0-5/;
                   12848:     $txt=~tr/u-z/0-5/;
                   12849:     $txt=~s/\D//g;
                   12850:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12851:     my $total;
                   12852:     foreach my $val (@txts) { $total+=$val; }
                   12853:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12854:     return $total;
                   12855: }
                   12856: 
1.675     albertel 12857: sub digest {
                   12858:     my ($data)=@_;
                   12859:     my $digest=&Digest::MD5::md5($data);
                   12860:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12861:     my ($e,$f);
                   12862:     {
                   12863:         use integer;
                   12864:         $e=($a+$b);
                   12865:         $f=($c+$d);
                   12866:         if ($_64bit) {
                   12867:             $e=(($e<<32)>>32);
                   12868:             $f=(($f<<32)>>32);
                   12869:         }
                   12870:     }
                   12871:     if (wantarray) {
                   12872: 	return ($e,$f);
                   12873:     } else {
                   12874: 	my $g;
                   12875: 	{
                   12876: 	    use integer;
                   12877: 	    $g=($e+$f);
                   12878: 	    if ($_64bit) {
                   12879: 		$g=(($g<<32)>>32);
                   12880: 	    }
                   12881: 	}
                   12882: 	return $g;
                   12883:     }
                   12884: }
                   12885: 
1.368     albertel 12886: sub latest_rnd_algorithm_id {
1.675     albertel 12887:     return '64bit5';
1.366     albertel 12888: }
1.32      www      12889: 
1.503     albertel 12890: sub get_rand_alg {
                   12891:     my ($courseid)=@_;
1.790     albertel 12892:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12893:     if ($courseid) {
1.620     albertel 12894: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12895:     }
                   12896:     return &latest_rnd_algorithm_id();
                   12897: }
                   12898: 
1.562     albertel 12899: sub validCODE {
                   12900:     my ($CODE)=@_;
                   12901:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12902:     return 0;
                   12903: }
                   12904: 
1.491     albertel 12905: sub getCODE {
1.620     albertel 12906:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12907:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12908: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12909: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12910: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12911:     }
                   12912:     return undef;
                   12913: }
1.1133    foxr     12914: #
                   12915: #  Determines the random seed for a specific context:
                   12916: #
                   12917: # parameters:
                   12918: #   symb      - in course context the symb for the seed.
                   12919: #   course_id - The course id of the form domain_coursenum.
                   12920: #   domain    - Domain for the user.
                   12921: #   course    - Course for the user.
                   12922: #   cenv      - environment of the course.
                   12923: #
                   12924: # NOTE:
                   12925: #   All parameters are picked out of the environment if missing
                   12926: #   or not defined.
                   12927: #   If a symb cannot be determined the current time is used instead.
                   12928: #
                   12929: #  For a given well defined symb, courside, domain, username,
                   12930: #  and course environment, the seed is reproducible.
                   12931: #
1.31      www      12932: sub rndseed {
1.1133    foxr     12933:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12934:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12935:     if (!defined($symb)) {
1.366     albertel 12936: 	unless ($symb=$wsymb) { return time; }
                   12937:     }
1.1146    foxr     12938:     if (!defined $courseid) { 
                   12939: 	$courseid=$wcourseid; 
                   12940:     }
                   12941:     if (!defined $domain) { $domain=$wdomain; }
                   12942:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12943: 
                   12944:     my $which;
                   12945:     if (defined($cenv->{'rndseed'})) {
                   12946: 	$which = $cenv->{'rndseed'};
                   12947:     } else {
                   12948: 	$which =&get_rand_alg($courseid);
                   12949:     }
1.491     albertel 12950:     if (defined(&getCODE())) {
1.675     albertel 12951: 	if ($which eq '64bit5') {
                   12952: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12953: 	} elsif ($which eq '64bit4') {
1.575     albertel 12954: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12955: 	} else {
                   12956: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12957: 	}
1.675     albertel 12958:     } elsif ($which eq '64bit5') {
                   12959: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12960:     } elsif ($which eq '64bit4') {
                   12961: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12962:     } elsif ($which eq '64bit3') {
                   12963: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12964:     } elsif ($which eq '64bit2') {
                   12965: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12966:     } elsif ($which eq '64bit') {
                   12967: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12968:     }
                   12969:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12970: }
                   12971: 
                   12972: sub rndseed_32bit {
                   12973:     my ($symb,$courseid,$domain,$username)=@_;
                   12974:     {
                   12975: 	use integer;
                   12976: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12977: 	my $symbseed=numval($symb) << 22;
                   12978: 	my $namechck=unpack("%32C*",$username) << 17;
                   12979: 	my $nameseed=numval($username) << 12;
                   12980: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12981: 	my $courseseed=unpack("%32C*",$courseid);
                   12982: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12983: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12984: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12985: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12986: 	return $num;
                   12987:     }
                   12988: }
                   12989: 
                   12990: sub rndseed_64bit {
                   12991:     my ($symb,$courseid,$domain,$username)=@_;
                   12992:     {
                   12993: 	use integer;
                   12994: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12995: 	my $symbseed=numval($symb) << 10;
                   12996: 	my $namechck=unpack("%32S*",$username);
                   12997: 	
                   12998: 	my $nameseed=numval($username) << 21;
                   12999: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13000: 	my $courseseed=unpack("%32S*",$courseid);
                   13001: 	
                   13002: 	my $num1=$symbchck+$symbseed+$namechck;
                   13003: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13004: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13005: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13007: 	return "$num1,$num2";
1.155     albertel 13008:     }
1.366     albertel 13009: }
                   13010: 
1.443     albertel 13011: sub rndseed_64bit2 {
                   13012:     my ($symb,$courseid,$domain,$username)=@_;
                   13013:     {
                   13014: 	use integer;
                   13015: 	# strings need to be an even # of cahracters long, it it is odd the
                   13016:         # last characters gets thrown away
                   13017: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13018: 	my $symbseed=numval($symb) << 10;
                   13019: 	my $namechck=unpack("%32S*",$username.' ');
                   13020: 	
                   13021: 	my $nameseed=numval($username) << 21;
1.501     albertel 13022: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13023: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13024: 	
                   13025: 	my $num1=$symbchck+$symbseed+$namechck;
                   13026: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13027: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13028: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13029: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13030: 	return "$num1,$num2";
                   13031:     }
                   13032: }
                   13033: 
                   13034: sub rndseed_64bit3 {
                   13035:     my ($symb,$courseid,$domain,$username)=@_;
                   13036:     {
                   13037: 	use integer;
                   13038: 	# strings need to be an even # of cahracters long, it it is odd the
                   13039:         # last characters gets thrown away
                   13040: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13041: 	my $symbseed=numval2($symb) << 10;
                   13042: 	my $namechck=unpack("%32S*",$username.' ');
                   13043: 	
                   13044: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13045: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13046: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13047: 	
                   13048: 	my $num1=$symbchck+$symbseed+$namechck;
                   13049: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13050: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13051: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13052: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13053: 	
1.503     albertel 13054: 	return "$num1:$num2";
1.443     albertel 13055:     }
                   13056: }
                   13057: 
1.575     albertel 13058: sub rndseed_64bit4 {
                   13059:     my ($symb,$courseid,$domain,$username)=@_;
                   13060:     {
                   13061: 	use integer;
                   13062: 	# strings need to be an even # of cahracters long, it it is odd the
                   13063:         # last characters gets thrown away
                   13064: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13065: 	my $symbseed=numval3($symb) << 10;
                   13066: 	my $namechck=unpack("%32S*",$username.' ');
                   13067: 	
                   13068: 	my $nameseed=numval3($username) << 21;
                   13069: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13070: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13071: 	
                   13072: 	my $num1=$symbchck+$symbseed+$namechck;
                   13073: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13074: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13075: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13076: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13077: 	
1.575     albertel 13078: 	return "$num1:$num2";
                   13079:     }
                   13080: }
                   13081: 
1.675     albertel 13082: sub rndseed_64bit5 {
                   13083:     my ($symb,$courseid,$domain,$username)=@_;
                   13084:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13085:     return "$num1:$num2";
                   13086: }
                   13087: 
1.366     albertel 13088: sub rndseed_CODE_64bit {
                   13089:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13090:     {
1.366     albertel 13091: 	use integer;
1.443     albertel 13092: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13093: 	my $symbseed=numval2($symb);
1.491     albertel 13094: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13095: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13096: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13097: 	my $num1=$symbseed+$CODEchck;
                   13098: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13099: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13100: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13101: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13102: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13103: 	return "$num1:$num2";
1.366     albertel 13104:     }
                   13105: }
                   13106: 
1.575     albertel 13107: sub rndseed_CODE_64bit4 {
                   13108:     my ($symb,$courseid,$domain,$username)=@_;
                   13109:     {
                   13110: 	use integer;
                   13111: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13112: 	my $symbseed=numval3($symb);
                   13113: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13114: 	my $CODEseed=numval3(&getCODE());
                   13115: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13116: 	my $num1=$symbseed+$CODEchck;
                   13117: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13118: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13119: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13120: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13121: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13122: 	return "$num1:$num2";
                   13123:     }
                   13124: }
                   13125: 
1.675     albertel 13126: sub rndseed_CODE_64bit5 {
                   13127:     my ($symb,$courseid,$domain,$username)=@_;
                   13128:     my $code = &getCODE();
                   13129:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13130:     return "$num1:$num2";
                   13131: }
                   13132: 
1.366     albertel 13133: sub setup_random_from_rndseed {
                   13134:     my ($rndseed)=@_;
1.503     albertel 13135:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13136: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13137:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13138:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13139:         } else {
                   13140:             &Math::Random::random_set_seed($num1,$num2);
                   13141:         }
1.366     albertel 13142:     } else {
                   13143: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13144:     }
1.36      albertel 13145: }
                   13146: 
1.474     albertel 13147: sub latest_receipt_algorithm_id {
1.835     albertel 13148:     return 'receipt3';
1.474     albertel 13149: }
                   13150: 
1.480     www      13151: sub recunique {
                   13152:     my $fucourseid=shift;
                   13153:     my $unique;
1.835     albertel 13154:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13155: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13156: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13157:     } else {
                   13158: 	$unique=$perlvar{'lonReceipt'};
                   13159:     }
                   13160:     return unpack("%32C*",$unique);
                   13161: }
                   13162: 
                   13163: sub recprefix {
                   13164:     my $fucourseid=shift;
                   13165:     my $prefix;
1.835     albertel 13166:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13167: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13168: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13169:     } else {
                   13170: 	$prefix=$perlvar{'lonHostID'};
                   13171:     }
                   13172:     return unpack("%32C*",$prefix);
                   13173: }
                   13174: 
1.76      www      13175: sub ireceipt {
1.474     albertel 13176:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13177: 
                   13178:     my $return =&recprefix($fucourseid).'-';
                   13179: 
                   13180:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13181: 	$env{'request.state'} eq 'construct') {
                   13182: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13183: 	return $return;
                   13184:     }
                   13185: 
1.76      www      13186:     my $cuname=unpack("%32C*",$funame);
                   13187:     my $cudom=unpack("%32C*",$fudom);
                   13188:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13189:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13190:     my $cunique=&recunique($fucourseid);
1.474     albertel 13191:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13192:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13193: 
1.790     albertel 13194: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13195: 			       
                   13196: 	$return.= ($cunique%$cuname+
                   13197: 		   $cunique%$cudom+
                   13198: 		   $cusymb%$cuname+
                   13199: 		   $cusymb%$cudom+
                   13200: 		   $cucourseid%$cuname+
                   13201: 		   $cucourseid%$cudom+
                   13202: 		   $cpart%$cuname+
                   13203: 		   $cpart%$cudom);
                   13204:     } else {
                   13205: 	$return.= ($cunique%$cuname+
                   13206: 		   $cunique%$cudom+
                   13207: 		   $cusymb%$cuname+
                   13208: 		   $cusymb%$cudom+
                   13209: 		   $cucourseid%$cuname+
                   13210: 		   $cucourseid%$cudom);
                   13211:     }
                   13212:     return $return;
1.76      www      13213: }
                   13214: 
                   13215: sub receipt {
1.474     albertel 13216:     my ($part)=@_;
1.790     albertel 13217:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13218:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13219: }
1.260     ng       13220: 
1.790     albertel 13221: sub whichuser {
                   13222:     my ($passedsymb)=@_;
                   13223:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13224:     if (defined($env{'form.grade_symb'})) {
                   13225: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13226: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13227: 	if (!$allowed &&
                   13228: 	    exists($env{'request.course.sec'}) &&
                   13229: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13230: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13231: 			      '/'.$env{'request.course.sec'});
                   13232: 	}
                   13233: 	if ($allowed) {
                   13234: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13235: 	    $courseid=$tmp_courseid;
                   13236: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13237: 	    ($name)=&get_env_multiple('form.grade_username');
                   13238: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13239: 	}
                   13240:     }
                   13241:     if (!$passedsymb) {
                   13242: 	$symb=&symbread();
                   13243:     } else {
                   13244: 	$symb=$passedsymb;
                   13245:     }
                   13246:     $courseid=$env{'request.course.id'};
                   13247:     $domain=$env{'user.domain'};
                   13248:     $name=$env{'user.name'};
                   13249:     if ($name eq 'public' && $domain eq 'public') {
                   13250: 	if (!defined($env{'form.username'})) {
                   13251: 	    $env{'form.username'}.=time.rand(10000000);
                   13252: 	}
                   13253: 	$name.=$env{'form.username'};
                   13254:     }
                   13255:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13256: 
                   13257: }
                   13258: 
1.36      albertel 13259: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13260: # returns either the contents of the file or 
                   13261: # -1 if the file doesn't exist
1.481     raeburn  13262: #
                   13263: # if the target is a file that was uploaded via DOCS, 
                   13264: # a check will be made to see if a current copy exists on the local server,
                   13265: # if it does this will be served, otherwise a copy will be retrieved from
                   13266: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13267: # the local server.   
1.472     albertel 13268: 
1.36      albertel 13269: sub getfile {
1.538     albertel 13270:     my ($file) = @_;
1.609     banghart 13271:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13272:     &repcopy($file);
                   13273:     return &readfile($file);
                   13274: }
                   13275: 
                   13276: sub repcopy_userfile {
                   13277:     my ($file)=@_;
1.1142    raeburn  13278:     my $londocroot = $perlvar{'lonDocRoot'};
                   13279:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13280:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13281:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13282: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13283:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13284:     if (-e "$file") {
1.828     www      13285: # we already have a local copy, check it out
1.538     albertel 13286: 	my @fileinfo = stat($file);
1.828     www      13287: 	my $rtncode;
                   13288: 	my $info;
1.538     albertel 13289: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13290: 	if ($lwpresp ne 'ok') {
1.828     www      13291: # there is no such file anymore, even though we had a local copy
1.482     albertel 13292: 	    if ($rtncode eq '404') {
1.538     albertel 13293: 		unlink($file);
1.482     albertel 13294: 	    }
                   13295: 	    return -1;
                   13296: 	}
                   13297: 	if ($info < $fileinfo[9]) {
1.828     www      13298: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13299: 	    return 'ok';
1.828     www      13300: 	} else {
                   13301: # the file is outdated, get rid of it
                   13302: 	    unlink($file);
1.482     albertel 13303: 	}
1.828     www      13304:     }
                   13305: # one way or the other, at this point, we don't have the file
                   13306: # construct the correct path for the file
                   13307:     my @parts = ($cdom,$cnum); 
                   13308:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13309: 	push @parts, split(/\//,$1);
                   13310:     }
                   13311:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13312:     foreach my $part (@parts) {
                   13313: 	$path .= '/'.$part;
                   13314: 	if (!-e $path) {
                   13315: 	    mkdir($path,0770);
1.482     albertel 13316: 	}
                   13317:     }
1.828     www      13318: # now the path exists for sure
                   13319: # get a user agent
                   13320:     my $ua=new LWP::UserAgent;
                   13321:     my $transferfile=$file.'.in.transfer';
                   13322: # FIXME: this should flock
                   13323:     if (-e $transferfile) { return 'ok'; }
                   13324:     my $request;
                   13325:     $uri=~s/^\///;
1.980     raeburn  13326:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13327:     my $hostname = &hostname($homeserver);
1.980     raeburn  13328:     my $protocol = $protocol{$homeserver};
                   13329:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13330:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13331:     my $response=$ua->request($request,$transferfile);
                   13332: # did it work?
                   13333:     if ($response->is_error()) {
                   13334: 	unlink($transferfile);
                   13335: 	&logthis("Userfile repcopy failed for $uri");
                   13336: 	return -1;
                   13337:     }
                   13338: # worked, rename the transfer file
                   13339:     rename($transferfile,$file);
1.607     raeburn  13340:     return 'ok';
1.481     raeburn  13341: }
                   13342: 
1.517     albertel 13343: sub tokenwrapper {
                   13344:     my $uri=shift;
1.980     raeburn  13345:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13346:     $uri=~s|^/||;
1.620     albertel 13347:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13348:     my $token=$1;
1.552     albertel 13349:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13350:     if ($udom && $uname && $file) {
                   13351: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13352:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13353:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13354:         my $hostname = &hostname($homeserver);
1.980     raeburn  13355:         my $protocol = $protocol{$homeserver};
                   13356:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13357:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13358:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13359:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13360:     } else {
                   13361:         return '/adm/notfound.html';
                   13362:     }
                   13363: }
                   13364: 
1.828     www      13365: # call with reqtype HEAD: get last modification time
                   13366: # call with reqtype GET: get the file contents
                   13367: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13368: #
1.481     raeburn  13369: sub getuploaded {
                   13370:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13371:     $uri=~s/^\///;
1.980     raeburn  13372:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13373:     my $hostname = &hostname($homeserver);
1.980     raeburn  13374:     my $protocol = $protocol{$homeserver};
                   13375:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13376:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13377:     my $ua=new LWP::UserAgent;
                   13378:     my $request=new HTTP::Request($reqtype,$uri);
                   13379:     my $response=$ua->request($request);
                   13380:     $$rtncode = $response->code;
1.482     albertel 13381:     if (! $response->is_success()) {
                   13382: 	return 'failed';
                   13383:     }      
                   13384:     if ($reqtype eq 'HEAD') {
1.486     www      13385: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13386:     } elsif ($reqtype eq 'GET') {
                   13387: 	$$info = $response->content;
1.472     albertel 13388:     }
1.482     albertel 13389:     return 'ok';
1.36      albertel 13390: }
                   13391: 
1.481     raeburn  13392: sub readfile {
                   13393:     my $file = shift;
                   13394:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13395:     my $fh;
1.1172.2.96  raeburn  13396:     open($fh,"<",$file);
1.481     raeburn  13397:     my $a='';
1.800     albertel 13398:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13399:     return $a;
                   13400: }
                   13401: 
1.36      albertel 13402: sub filelocation {
1.590     banghart 13403:     my ($dir,$file) = @_;
                   13404:     my $location;
                   13405:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13406: 
                   13407:     if ($file =~ m-^/adm/-) {
                   13408: 	$file=~s-^/adm/wrapper/-/-;
                   13409: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13410:     }
1.882     albertel 13411: 
1.1139    www      13412:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13413:         $location = $file;
1.609     banghart 13414:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13415:         my ($udom,$uname,$filename)=
1.811     albertel 13416:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13417:         my $home=&homeserver($uname,$udom);
                   13418:         my $is_me=0;
                   13419:         my @ids=&current_machine_ids();
                   13420:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13421:         if ($is_me) {
1.1117    foxr     13422:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13423:         } else {
                   13424:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13425:   	      $udom.'/'.$uname.'/'.$filename;
                   13426:         }
1.882     albertel 13427:     } elsif ($file =~ m-^/adm/-) {
                   13428: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13429:     } else {
                   13430:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13431:         $file=~s:^/(res|priv)/:/:;
                   13432:         my $space=$1;
1.590     banghart 13433:         if ( !( $file =~ m:^/:) ) {
                   13434:             $location = $dir. '/'.$file;
                   13435:         } else {
1.1142    raeburn  13436:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13437:         }
1.59      albertel 13438:     }
1.590     banghart 13439:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13440:     while ($location=~m{/\.\./}) {
                   13441: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13442: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13443: 	} else {
                   13444: 	    $location=~ s{/\.\./}{/}g;
                   13445: 	}
                   13446:     } #remove dir/..
1.590     banghart 13447:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13448:     return $location;
1.46      www      13449: }
1.36      albertel 13450: 
1.46      www      13451: sub hreflocation {
                   13452:     my ($dir,$file)=@_;
1.980     raeburn  13453:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13454: 	$file=filelocation($dir,$file);
1.700     albertel 13455:     } elsif ($file=~m-^/adm/-) {
                   13456: 	$file=~s-^/adm/wrapper/-/-;
                   13457: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13458:     }
                   13459:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13460: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13461:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13462: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13463: 	        {/uploaded/$1/$2/}x;
1.46      www      13464:     }
1.913     albertel 13465:     if ($file=~ m{^/userfiles/}) {
                   13466: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13467:     }
1.462     albertel 13468:     return $file;
1.465     albertel 13469: }
                   13470: 
1.1139    www      13471: 
                   13472: 
                   13473: 
                   13474: 
1.465     albertel 13475: sub current_machine_domains {
1.853     albertel 13476:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13477: }
                   13478: 
                   13479: sub machine_domains {
                   13480:     my ($hostname) = @_;
1.465     albertel 13481:     my @domains;
1.838     albertel 13482:     my %hostname = &all_hostnames();
1.465     albertel 13483:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13484: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13485: 	if ($hostname eq $name) {
1.844     albertel 13486: 	    push(@domains,&host_domain($id));
1.465     albertel 13487: 	}
                   13488:     }
                   13489:     return @domains;
                   13490: }
                   13491: 
                   13492: sub current_machine_ids {
1.853     albertel 13493:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13494: }
                   13495: 
                   13496: sub machine_ids {
                   13497:     my ($hostname) = @_;
                   13498:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13499:     my @ids;
1.888     albertel 13500:     my %name_to_host = &all_names();
1.889     albertel 13501:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13502: 	return @{ $name_to_host{$hostname} };
                   13503:     }
                   13504:     return;
1.31      www      13505: }
                   13506: 
1.824     raeburn  13507: sub additional_machine_domains {
                   13508:     my @domains;
1.1172.2.142  raeburn  13509:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13510:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13511:             while( my $line = <$fh>) {
                   13512:                 chomp($line);
                   13513:                 $line =~ s/\s//g;
                   13514:                 push(@domains,$line);
                   13515:             }
                   13516:             close($fh);
                   13517:         }
1.824     raeburn  13518:     }
                   13519:     return @domains;
                   13520: }
                   13521: 
                   13522: sub default_login_domain {
                   13523:     my $domain = $perlvar{'lonDefDomain'};
                   13524:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13525:     foreach my $posdom (&current_machine_domains(),
                   13526:                         &additional_machine_domains()) {
                   13527:         if (lc($posdom) eq lc($testdomain)) {
                   13528:             $domain=$posdom;
                   13529:             last;
                   13530:         }
                   13531:     }
                   13532:     return $domain;
                   13533: }
                   13534: 
1.1172.2.106  raeburn  13535: sub shared_institution {
1.1172.2.136  raeburn  13536:     my ($dom,$lonhost) = @_;
                   13537:     if ($lonhost eq '') {
                   13538:         $lonhost = $perlvar{'lonHostID'};
                   13539:     }
1.1172.2.106  raeburn  13540:     my $same_intdom;
1.1172.2.136  raeburn  13541:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13542:     if ($hostintdom ne '') {
                   13543:         my %iphost = &get_iphost();
                   13544:         my $primary_id = &domain($dom,'primary');
                   13545:         my $primary_ip = &get_host_ip($primary_id);
                   13546:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13547:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13548:                 my $intdom = &internet_dom($id);
                   13549:                 if ($intdom eq $hostintdom) {
                   13550:                     $same_intdom = 1;
                   13551:                     last;
                   13552:                 }
                   13553:             }
                   13554:         }
                   13555:     }
                   13556:     return $same_intdom;
                   13557: }
                   13558: 
1.1172.2.120  raeburn  13559: sub uses_sts {
                   13560:     my ($ignore_cache) = @_;
                   13561:     my $lonhost = $perlvar{'lonHostID'};
                   13562:     my $hostname = &hostname($lonhost);
                   13563:     my $sts_on;
                   13564:     if ($protocol{$lonhost} eq 'https') {
                   13565:         my $cachetime = 12*3600;
                   13566:         if (!$ignore_cache) {
                   13567:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13568:             if (defined($cached)) {
                   13569:                 return $sts_on;
                   13570:             }
                   13571:         }
1.1172.2.121  raeburn  13572:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13573:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13574:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13575:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13576:         if ($response->is_success) {
                   13577:             my $has_sts = $response->header('Strict-Transport-Security');
                   13578:             if ($has_sts eq '') {
                   13579:                 $sts_on = 0;
                   13580:             } else {
                   13581:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13582:                     my $maxage = $1;
                   13583:                     if ($maxage) {
                   13584:                         $sts_on = 1;
                   13585:                     } else {
                   13586:                         $sts_on = 0;
                   13587:                     }
                   13588:                 } else {
                   13589:                     $sts_on = 0;
                   13590:                 }
                   13591:             }
                   13592:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13593:         }
                   13594:     }
                   13595:     return;
                   13596: }
                   13597: 
1.1172.2.142  raeburn  13598: sub waf_allssl {
                   13599:     my ($host_name) = @_;
                   13600:     my $alias = &get_proxy_alias();
                   13601:     if ($host_name eq '') {
                   13602:         $host_name = $ENV{'SERVER_NAME'};
                   13603:     }
                   13604:     if (($host_name ne '') && ($alias eq $host_name)) {
                   13605:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   13606:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   13607:         if ($defdomdefaults{'waf_sslopt'}) {
                   13608:             return $defdomdefaults{'waf_sslopt'};
                   13609:         }
                   13610:     }
                   13611:     return;
                   13612: }
                   13613: 
1.1172.2.134  raeburn  13614: sub get_requestor_ip {
                   13615:     my ($r,$nolookup,$noproxy) = @_;
                   13616:     my $from_ip;
                   13617:     if (ref($r)) {
1.1172.2.142  raeburn  13618:         if ($r->can('useragent_ip')) {
                   13619:             if ($noproxy && $r->can('client_ip')) {
                   13620:                 $from_ip = $r->client_ip();
                   13621:             } else {
                   13622:                 $from_ip = $r->useragent_ip();
                   13623:             }
                   13624:         } elsif ($r->connection->can('remote_ip')) {
                   13625:             $from_ip = $r->connection->remote_ip();
                   13626:         } else {
                   13627:             $from_ip = $r->get_remote_host($nolookup);
                   13628:         }
1.1172.2.134  raeburn  13629:     } else {
                   13630:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13631:     }
1.1172.2.142  raeburn  13632:     return $from_ip if ($noproxy);
                   13633:    # Who controls proxy settings for server
                   13634:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   13635:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   13636:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   13637:         if ($proxyinfo->{'vpnint'}) {
                   13638:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   13639:                 return $from_ip;
                   13640:             }
                   13641:         }
                   13642:         if ($proxyinfo->{'trusted'}) {
                   13643:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   13644:                 my $ipheader = $proxyinfo->{'ipheader'};
                   13645:                 my ($ip,$xfor);
                   13646:                 if (ref($r)) {
                   13647:                     if ($ipheader) {
                   13648:                         $ip = $r->headers_in->{$ipheader};
                   13649:                     }
                   13650:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   13651:                 } else {
                   13652:                     if ($ipheader) {
                   13653:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   13654:                     }
                   13655:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   13656:                 }
                   13657:                 if (($ip eq '') && ($xfor ne '')) {
                   13658:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   13659:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   13660:                             $ip = $poss_ip;
                   13661:                             last;
                   13662:                         }
                   13663:                     }
                   13664:                 }
                   13665:                 if ($ip ne '') {
                   13666:                     return $ip;
                   13667:                 }
                   13668:             }
                   13669:         }
                   13670:     }
1.1172.2.134  raeburn  13671:     return $from_ip;
                   13672: }
                   13673: 
1.1172.2.142  raeburn  13674: sub get_proxy_settings {
                   13675:     my ($dom_in_use) = @_;
                   13676:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   13677:     my $proxyinfo = {
                   13678:                        ipheader => $domdefaults{'waf_ipheader'},
                   13679:                        trusted  => $domdefaults{'waf_trusted'},
                   13680:                        vpnint   => $domdefaults{'waf_vpnint'},
                   13681:                        vpnext   => $domdefaults{'waf_vpnext'},
                   13682:                        sslopt   => $domdefaults{'waf_sslopt'},
                   13683:                     };
                   13684:     return $proxyinfo;
                   13685: }
                   13686: 
                   13687: sub ip_match {
                   13688:     my ($ip,$pattern_str) = @_;
                   13689:     $ip=Net::CIDR::cidrvalidate($ip);
                   13690:     if ($ip) {
                   13691:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   13692:     }
                   13693:     return;
                   13694: }
                   13695: 
                   13696: sub get_proxy_alias {
                   13697:     my ($lonid) = @_;
                   13698:     if ($lonid eq '') {
                   13699:         $lonid = $perlvar{'lonHostID'};
                   13700:     }
                   13701:     if (!defined(&hostname($lonid))) {
                   13702:         return;
                   13703:     }
                   13704:     if ($lonid ne '') {
                   13705:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   13706:         if ($cached) {
                   13707:             return $alias;
                   13708:         }
                   13709:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13710:         if ($dom ne '') {
                   13711:             my $cachetime = 60*60*24;
                   13712:             my %domconfig =
                   13713:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13714:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13715:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   13716:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   13717:                 }
                   13718:             }
                   13719:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   13720:         }
                   13721:     }
                   13722:     return;
                   13723: }
                   13724: 
                   13725: sub use_proxy_alias {
                   13726:     my ($r,$lonid) = @_;
                   13727:     my $alias = &get_proxy_alias($lonid);
                   13728:     if ($alias) {
                   13729:         my $dom = &host_domain($lonid);
                   13730:         if ($dom ne '') {
                   13731:             my $proxyinfo = &get_proxy_settings($dom);
                   13732:             my ($vpnint,$remote_ip);
                   13733:             if (ref($proxyinfo) eq 'HASH') {
                   13734:                 $vpnint = $proxyinfo->{'vpnint'};
                   13735:                 if ($vpnint) {
                   13736:                     $remote_ip = &get_requestor_ip($r,1,1);
                   13737:                 }
                   13738:             }
                   13739:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   13740:                 return $alias;
                   13741:             }
                   13742:         }
                   13743:     }
                   13744:     return;
                   13745: }
                   13746: 
                   13747: sub alias_sso {
                   13748:     my ($lonid) = @_;
                   13749:     if ($lonid eq '') {
                   13750:         $lonid = $perlvar{'lonHostID'};
                   13751:     }
                   13752:     if (!defined(&hostname($lonid))) {
                   13753:         return;
                   13754:     }
                   13755:     if ($lonid ne '') {
                   13756:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   13757:         if ($cached) {
                   13758:             return $use_alias;
                   13759:         }
                   13760:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13761:         if ($dom ne '') {
                   13762:             my $cachetime = 60*60*24;
                   13763:             my %domconfig =
                   13764:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13765:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13766:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   13767:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   13768:                 }
                   13769:             }
                   13770:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   13771:         }
                   13772:     }
                   13773:     return;
                   13774: }
                   13775: 
                   13776: sub get_saml_landing {
                   13777:     my ($lonid) = @_;
                   13778:     if ($lonid eq '') {
                   13779:         my $defdom = &default_login_domain();
                   13780:         my @hosts = &current_machine_ids();
                   13781:         if (@hosts > 1) {
                   13782:             foreach my $hostid (@hosts) {
                   13783:                 if (&host_domain($hostid) eq $defdom) {
                   13784:                     $lonid = $hostid;
                   13785:                     last;
                   13786:                 }
                   13787:             }
                   13788:         } else {
                   13789:             $lonid = $perlvar{'lonHostID'};
                   13790:         }
                   13791:         if ($lonid) {
                   13792:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   13793:                 return;
                   13794:             }
                   13795:         } else {
                   13796:             return;
                   13797:         }
                   13798:     } elsif (!defined(&hostname($lonid))) {
                   13799:         return;
                   13800:     }
                   13801:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   13802:     if ($cached) {
                   13803:         return $landing;
                   13804:     }
                   13805:     my $dom = &Apache::lonnet::host_domain($lonid);
                   13806:     if ($dom ne '') {
                   13807:         my $cachetime = 60*60*24;
                   13808:         my %domconfig =
                   13809:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   13810:         if (ref($domconfig{'login'}) eq 'HASH') {
                   13811:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   13812:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   13813:                     $landing = 1;
                   13814:                 }
                   13815:             }
                   13816:         }
                   13817:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   13818:     }
                   13819:     return;
                   13820: }
                   13821: 
1.31      www      13822: # ------------------------------------------------------------- Declutters URLs
                   13823: 
                   13824: sub declutter {
                   13825:     my $thisfn=shift;
1.569     albertel 13826:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13827:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13828:         $thisfn=~s{^/home/httpd/html}{};
                   13829:     }
1.31      www      13830:     $thisfn=~s/^\///;
1.697     albertel 13831:     $thisfn=~s|^adm/wrapper/||;
                   13832:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13833:     $thisfn=~s/^res\///;
1.1172    bisitz   13834:     $thisfn=~s/^priv\///;
1.1032    raeburn  13835:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13836:         $thisfn=~s/\?.+$//;
                   13837:     }
1.268     www      13838:     return $thisfn;
                   13839: }
                   13840: 
                   13841: # ------------------------------------------------------------- Clutter up URLs
                   13842: 
                   13843: sub clutter {
                   13844:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13845:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13846: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13847:        $thisfn='/res'.$thisfn; 
                   13848:     }
1.1031    raeburn  13849:     if ($thisfn !~m|^/adm|) {
                   13850: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13851: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13852: 	} else {
                   13853: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13854: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13855: 	    if ($embstyle eq 'ssi'
                   13856: 		|| ($embstyle eq 'hdn')
                   13857: 		|| ($embstyle eq 'rat')
                   13858: 		|| ($embstyle eq 'prv')
                   13859: 		|| ($embstyle eq 'ign')) {
                   13860: 		#do nothing with these
                   13861: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13862: 		|| ($embstyle eq 'emb')
                   13863: 		|| ($embstyle eq 'wrp')) {
                   13864: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13865: 	    } elsif ($embstyle eq 'unk'
                   13866: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13867: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13868: 	    } else {
1.718     www      13869: #		&logthis("Got a blank emb style");
1.695     albertel 13870: 	    }
1.694     albertel 13871: 	}
                   13872:     }
1.31      www      13873:     return $thisfn;
1.12      www      13874: }
                   13875: 
1.787     albertel 13876: sub clutter_with_no_wrapper {
                   13877:     my $uri = &clutter(shift);
                   13878:     if ($uri =~ m-^/adm/-) {
                   13879: 	$uri =~ s-^/adm/wrapper/-/-;
                   13880: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13881:     }
                   13882:     return $uri;
                   13883: }
                   13884: 
1.557     albertel 13885: sub freeze_escape {
                   13886:     my ($value)=@_;
                   13887:     if (ref($value)) {
                   13888: 	$value=&nfreeze($value);
                   13889: 	return '__FROZEN__'.&escape($value);
                   13890:     }
                   13891:     return &escape($value);
                   13892: }
                   13893: 
1.11      www      13894: 
1.557     albertel 13895: sub thaw_unescape {
                   13896:     my ($value)=@_;
                   13897:     if ($value =~ /^__FROZEN__/) {
                   13898: 	substr($value,0,10,undef);
                   13899: 	$value=&unescape($value);
                   13900: 	return &thaw($value);
                   13901:     }
                   13902:     return &unescape($value);
                   13903: }
                   13904: 
1.436     albertel 13905: sub correct_line_ends {
                   13906:     my ($result)=@_;
                   13907:     $$result =~s/\r\n/\n/mg;
                   13908:     $$result =~s/\r/\n/mg;
1.415     albertel 13909: }
1.1       albertel 13910: # ================================================================ Main Program
                   13911: 
1.184     www      13912: sub goodbye {
1.204     albertel 13913:    &logthis("Starting Shut down");
1.443     albertel 13914: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13915:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13916: #converted
1.599     albertel 13917: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13918:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13919: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13920: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13921: #1.1 only
1.870     albertel 13922: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13923: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13924: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13925: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13926:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13927:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13928:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13929:    &flushcourselogs();
                   13930:    &logthis("Shutting down");
                   13931: }
                   13932: 
1.852     albertel 13933: sub get_dns {
1.1172.2.17  raeburn  13934:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13935:     if (!$ignore_cache) {
                   13936: 	my ($content,$cached)=
                   13937: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13938: 	if ($cached) {
1.1172.2.17  raeburn  13939: 	    &$func($content,$hashref);
1.869     albertel 13940: 	    return;
                   13941: 	}
                   13942:     }
                   13943: 
                   13944:     my %alldns;
1.1172.2.96  raeburn  13945:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13946:         foreach my $dns (<$config>) {
                   13947: 	    next if ($dns !~ /^\^(\S*)/x);
                   13948:             my $line = $1;
                   13949:             my ($host,$protocol) = split(/:/,$line);
                   13950:             if ($protocol ne 'https') {
                   13951:                 $protocol = 'http';
                   13952:             }
                   13953: 	    $alldns{$host} = $protocol;
1.979     raeburn  13954:         }
1.1172.2.96  raeburn  13955:         close($config);
1.869     albertel 13956:     }
                   13957:     while (%alldns) {
1.1172.2.52  raeburn  13958: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  13959:         my @content;
                   13960:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   13961:             my $command = (split('/',$url))[3];
                   13962:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   13963:             delete($alldns{$dns});
                   13964:             next if (($dir eq '') || ($file eq ''));
                   13965:             if (open(my $config,'<',"$dir/$file")) {
                   13966:                 @content = <$config>;
                   13967:                 close($config);
                   13968:             }
                   13969:         } else {
                   13970: 	    my $ua=new LWP::UserAgent;
                   13971:             $ua->timeout(30);
                   13972: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   13973: 	    my $response=$ua->request($request);
                   13974:             delete($alldns{$dns});
                   13975: 	    next if ($response->is_error());
                   13976: 	    @content = split("\n",$response->content);
                   13977:         }
1.1172.2.17  raeburn  13978:         unless ($nocache) {
1.1172.2.23  raeburn  13979: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13980:         }
                   13981: 	&$func(\@content,$hashref);
1.869     albertel 13982: 	return;
1.852     albertel 13983:     }
1.871     albertel 13984:     my $which = (split('/',$url))[3];
                   13985:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13986:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13987:         my @content = <$config>;
                   13988:         &$func(\@content,$hashref);
                   13989:     }
1.1172.2.17  raeburn  13990:     return;
                   13991: }
                   13992: 
                   13993: # ------------------------------------------------------Get DNS checksums file
                   13994: sub parse_dns_checksums_tab {
                   13995:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13996:     my $lonhost = $perlvar{'lonHostID'};
                   13997:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13998:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13999:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14000:     my $webconfdir = '/etc/httpd/conf';
                   14001:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14002:         $webconfdir = '/etc/apache2';
                   14003:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14004:         if ($1 >= 10) {
                   14005:             $webconfdir = '/etc/apache2';
                   14006:         }
                   14007:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14008:         if ($1 >= 10.0) {
                   14009:             $webconfdir = '/etc/apache2';
                   14010:         }
                   14011:     }
1.1172.2.17  raeburn  14012:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14013:     my (%chksum,%revnum);
                   14014:     if (ref($lines) eq 'ARRAY') {
                   14015:         chomp(@{$lines});
1.1172.2.34  raeburn  14016:         my $version = shift(@{$lines});
                   14017:         if ($version eq $release) {
1.1172.2.17  raeburn  14018:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14019:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14020:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14021:                     if ($webconfdir eq '/etc/apache2') {
                   14022:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14023:                     }
                   14024:                 }
1.1172.2.34  raeburn  14025:                 $chksum{$file} = $shasum;
                   14026:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14027:             }
                   14028:             if (ref($hashref) eq 'HASH') {
                   14029:                 %{$hashref} = (
                   14030:                                 sums     => \%chksum,
                   14031:                                 versions => \%revnum,
                   14032:                               );
                   14033:             }
                   14034:         }
                   14035:     }
1.869     albertel 14036:     return;
1.852     albertel 14037: }
1.1172.2.17  raeburn  14038: 
                   14039: sub fetch_dns_checksums {
                   14040:     my %checksums;
1.1172.2.34  raeburn  14041:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14042:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14043:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14044:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14045:              \%checksums);
                   14046:     return \%checksums;
                   14047: }
                   14048: 
1.1172.2.142  raeburn  14049: sub parse_getdns_url {
                   14050:     my ($command,$url) = @_;
                   14051:     my $dir = $perlvar{'lonTabDir'};
                   14052:     my $file;
                   14053:     if ($command eq 'hosts') {
                   14054:         $file = 'dns_hosts.tab';
                   14055:     } elsif ($command eq 'domain') {
                   14056:         $file = 'dns_domain.tab';
                   14057:     } elsif ($command eq 'checksums') {
                   14058:         my $version = (split('/',$url))[4];
                   14059:         $file = "dns_checksums/$version.tab",
                   14060:     }
                   14061:     return ($dir,$file);
                   14062: }
                   14063: 
1.327     albertel 14064: # ------------------------------------------------------------ Read domain file
                   14065: {
1.852     albertel 14066:     my $loaded;
1.846     albertel 14067:     my %domain;
                   14068: 
1.852     albertel 14069:     sub parse_domain_tab {
                   14070: 	my ($lines) = @_;
                   14071: 	foreach my $line (@$lines) {
                   14072: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14073: 
1.846     albertel 14074: 	    chomp($line);
1.852     albertel 14075: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14076: 	    my %this_domain;
                   14077: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14078: 			       'lang_def', 'city', 'longi', 'lati',
                   14079: 			       'primary') {
                   14080: 		$this_domain{$field} = shift(@elements);
                   14081: 	    }
                   14082: 	    $domain{$name} = \%this_domain;
1.852     albertel 14083: 	}
                   14084:     }
1.864     albertel 14085: 
                   14086:     sub reset_domain_info {
                   14087: 	undef($loaded);
                   14088: 	undef(%domain);
                   14089:     }
                   14090: 
1.852     albertel 14091:     sub load_domain_tab {
1.1172.2.70  raeburn  14092: 	my ($ignore_cache,$nocache) = @_;
                   14093: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14094: 	my $fh;
1.1172.2.96  raeburn  14095: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14096: 	    my @lines = <$fh>;
                   14097: 	    &parse_domain_tab(\@lines);
1.448     albertel 14098: 	}
1.852     albertel 14099: 	close($fh);
                   14100: 	$loaded = 1;
1.327     albertel 14101:     }
1.846     albertel 14102: 
                   14103:     sub domain {
1.852     albertel 14104: 	&load_domain_tab() if (!$loaded);
                   14105: 
1.846     albertel 14106: 	my ($name,$what) = @_;
                   14107: 	return if ( !exists($domain{$name}) );
                   14108: 
                   14109: 	if (!$what) {
                   14110: 	    return $domain{$name}{'description'};
                   14111: 	}
                   14112: 	return $domain{$name}{$what};
                   14113:     }
1.974     raeburn  14114: 
                   14115:     sub domain_info {
                   14116:         &load_domain_tab() if (!$loaded);
                   14117:         return %domain;
                   14118:     }
                   14119: 
1.327     albertel 14120: }
                   14121: 
                   14122: 
1.1       albertel 14123: # ------------------------------------------------------------- Read hosts file
                   14124: {
1.838     albertel 14125:     my %hostname;
1.844     albertel 14126:     my %hostdom;
1.845     albertel 14127:     my %libserv;
1.852     albertel 14128:     my $loaded;
1.888     albertel 14129:     my %name_to_host;
1.1074    raeburn  14130:     my %internetdom;
1.1107    raeburn  14131:     my %LC_dns_serv;
1.852     albertel 14132: 
                   14133:     sub parse_hosts_tab {
                   14134: 	my ($file) = @_;
                   14135: 	foreach my $configline (@$file) {
                   14136: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14137:             chomp($configline);
                   14138: 	    if ($configline =~ /^\^/) {
                   14139:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14140:                     $LC_dns_serv{$1} = 1;
                   14141:                 }
                   14142:                 next;
                   14143:             }
1.1074    raeburn  14144: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14145: 	    $name=~s/\s//g;
                   14146: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14147:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14148:                     my $curr = $hostname{$id};
                   14149:                     my $skip;
                   14150:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14151:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14152:                             $skip = 1;
                   14153:                         } else {
                   14154:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14155:                         }
                   14156:                     }
                   14157:                     unless ($skip) {
                   14158:                         push(@{$name_to_host{$name}},$id);
                   14159:                     }
                   14160:                 } else {
                   14161:                     push(@{$name_to_host{$name}},$id);
                   14162:                 }
1.852     albertel 14163: 		$hostname{$id}=$name;
                   14164: 		$hostdom{$id}=$domain;
                   14165: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14166:                 if (defined($protocol)) {
                   14167:                     if ($protocol eq 'https') {
                   14168:                         $protocol{$id} = $protocol;
                   14169:                     } else {
                   14170:                         $protocol{$id} = 'http'; 
                   14171:                     }
1.968     raeburn  14172:                 } else {
1.969     raeburn  14173:                     $protocol{$id} = 'http';
1.968     raeburn  14174:                 }
1.1074    raeburn  14175:                 if (defined($intdom)) {
                   14176:                     $internetdom{$id} = $intdom;
                   14177:                 }
1.852     albertel 14178: 	    }
                   14179: 	}
                   14180:     }
1.864     albertel 14181:     
                   14182:     sub reset_hosts_info {
1.897     albertel 14183: 	&purge_remembered();
1.864     albertel 14184: 	&reset_domain_info();
                   14185: 	&reset_hosts_ip_info();
1.892     albertel 14186: 	undef(%name_to_host);
1.864     albertel 14187: 	undef(%hostname);
                   14188: 	undef(%hostdom);
                   14189: 	undef(%libserv);
                   14190: 	undef($loaded);
                   14191:     }
1.1       albertel 14192: 
1.852     albertel 14193:     sub load_hosts_tab {
1.1172.2.70  raeburn  14194: 	my ($ignore_cache,$nocache) = @_;
                   14195: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14196: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14197: 	my @config = <$config>;
                   14198: 	&parse_hosts_tab(\@config);
                   14199: 	close($config);
                   14200: 	$loaded=1;
1.1       albertel 14201:     }
1.852     albertel 14202: 
1.838     albertel 14203:     sub hostname {
1.852     albertel 14204: 	&load_hosts_tab() if (!$loaded);
                   14205: 
1.838     albertel 14206: 	my ($lonid) = @_;
                   14207: 	return $hostname{$lonid};
                   14208:     }
1.845     albertel 14209: 
1.838     albertel 14210:     sub all_hostnames {
1.852     albertel 14211: 	&load_hosts_tab() if (!$loaded);
                   14212: 
1.838     albertel 14213: 	return %hostname;
                   14214:     }
1.845     albertel 14215: 
1.888     albertel 14216:     sub all_names {
1.1172.2.70  raeburn  14217:         my ($ignore_cache,$nocache) = @_;
                   14218: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14219: 
                   14220: 	return %name_to_host;
                   14221:     }
                   14222: 
1.974     raeburn  14223:     sub all_host_domain {
                   14224:         &load_hosts_tab() if (!$loaded);
                   14225:         return %hostdom;
                   14226:     }
                   14227: 
1.845     albertel 14228:     sub is_library {
1.852     albertel 14229: 	&load_hosts_tab() if (!$loaded);
                   14230: 
1.845     albertel 14231: 	return exists($libserv{$_[0]});
                   14232:     }
                   14233: 
                   14234:     sub all_library {
1.852     albertel 14235: 	&load_hosts_tab() if (!$loaded);
                   14236: 
1.845     albertel 14237: 	return %libserv;
                   14238:     }
                   14239: 
1.1062    droeschl 14240:     sub unique_library {
                   14241: 	#2x reverse removes all hostnames that appear more than once
                   14242:         my %unique = reverse &all_library();
                   14243:         return reverse %unique;
                   14244:     }
                   14245: 
1.841     albertel 14246:     sub get_servers {
1.852     albertel 14247: 	&load_hosts_tab() if (!$loaded);
                   14248: 
1.841     albertel 14249: 	my ($domain,$type) = @_;
                   14250: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14251: 	                                          : %hostname;
                   14252: 	my %result;
1.842     albertel 14253: 	if (ref($domain) eq 'ARRAY') {
                   14254: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14255: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14256: 		    $result{$host} = $hostname;
                   14257: 		}
                   14258: 	    }
                   14259: 	} else {
                   14260: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14261: 		if ($hostdom{$host} eq $domain) {
                   14262: 		    $result{$host} = $hostname;
                   14263: 		}
1.841     albertel 14264: 	    }
                   14265: 	}
                   14266: 	return %result;
                   14267:     }
1.845     albertel 14268: 
1.1062    droeschl 14269:     sub get_unique_servers {
                   14270:         my %unique = reverse &get_servers(@_);
                   14271: 	return reverse %unique;
                   14272:     }
                   14273: 
1.844     albertel 14274:     sub host_domain {
1.852     albertel 14275: 	&load_hosts_tab() if (!$loaded);
                   14276: 
1.844     albertel 14277: 	my ($lonid) = @_;
                   14278: 	return $hostdom{$lonid};
                   14279:     }
                   14280: 
1.841     albertel 14281:     sub all_domains {
1.852     albertel 14282: 	&load_hosts_tab() if (!$loaded);
                   14283: 
1.841     albertel 14284: 	my %seen;
                   14285: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14286: 	return @uniq;
                   14287:     }
1.1074    raeburn  14288: 
                   14289:     sub internet_dom {
                   14290:         &load_hosts_tab() if (!$loaded);
                   14291: 
                   14292:         my ($lonid) = @_;
                   14293:         return $internetdom{$lonid};
                   14294:     }
1.1107    raeburn  14295: 
                   14296:     sub is_LC_dns {
                   14297:         &load_hosts_tab() if (!$loaded);
                   14298: 
                   14299:         my ($hostname) = @_;
                   14300:         return exists($LC_dns_serv{$hostname});
                   14301:     }
                   14302: 
1.1       albertel 14303: }
                   14304: 
1.847     albertel 14305: { 
                   14306:     my %iphost;
1.856     albertel 14307:     my %name_to_ip;
                   14308:     my %lonid_to_ip;
1.869     albertel 14309: 
1.847     albertel 14310:     sub get_hosts_from_ip {
                   14311: 	my ($ip) = @_;
                   14312: 	my %iphosts = &get_iphost();
                   14313: 	if (ref($iphosts{$ip})) {
                   14314: 	    return @{$iphosts{$ip}};
                   14315: 	}
                   14316: 	return;
1.839     albertel 14317:     }
1.864     albertel 14318:     
                   14319:     sub reset_hosts_ip_info {
                   14320: 	undef(%iphost);
                   14321: 	undef(%name_to_ip);
                   14322: 	undef(%lonid_to_ip);
                   14323:     }
1.856     albertel 14324: 
                   14325:     sub get_host_ip {
                   14326: 	my ($lonid) = @_;
                   14327: 	if (exists($lonid_to_ip{$lonid})) {
                   14328: 	    return $lonid_to_ip{$lonid};
                   14329: 	}
                   14330: 	my $name=&hostname($lonid);
                   14331:    	my $ip = gethostbyname($name);
                   14332: 	return if (!$ip || length($ip) ne 4);
                   14333: 	$ip=inet_ntoa($ip);
                   14334: 	$name_to_ip{$name}   = $ip;
                   14335: 	$lonid_to_ip{$lonid} = $ip;
                   14336: 	return $ip;
                   14337:     }
1.847     albertel 14338:     
                   14339:     sub get_iphost {
1.1172.2.70  raeburn  14340: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14341: 
1.869     albertel 14342: 	if (!$ignore_cache) {
                   14343: 	    if (%iphost) {
                   14344: 		return %iphost;
                   14345: 	    }
                   14346: 	    my ($ip_info,$cached)=
                   14347: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14348: 	    if ($cached) {
                   14349: 		%iphost      = %{$ip_info->[0]};
                   14350: 		%name_to_ip  = %{$ip_info->[1]};
                   14351: 		%lonid_to_ip = %{$ip_info->[2]};
                   14352: 		return %iphost;
                   14353: 	    }
                   14354: 	}
1.894     albertel 14355: 
                   14356: 	# get yesterday's info for fallback
                   14357: 	my %old_name_to_ip;
                   14358: 	my ($ip_info,$cached)=
                   14359: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14360: 	if ($cached) {
                   14361: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14362: 	}
                   14363: 
1.1172.2.70  raeburn  14364: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14365: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14366: 	    my $ip;
                   14367: 	    if (!exists($name_to_ip{$name})) {
                   14368: 		$ip = gethostbyname($name);
                   14369: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14370: 		    if (defined($old_name_to_ip{$name})) {
                   14371: 			$ip = $old_name_to_ip{$name};
                   14372: 			&logthis("Can't find $name defaulting to old $ip");
                   14373: 		    } else {
                   14374: 			&logthis("Name $name no IP found");
                   14375: 			next;
                   14376: 		    }
                   14377: 		} else {
                   14378: 		    $ip=inet_ntoa($ip);
1.847     albertel 14379: 		}
                   14380: 		$name_to_ip{$name} = $ip;
                   14381: 	    } else {
                   14382: 		$ip = $name_to_ip{$name};
1.653     albertel 14383: 	    }
1.888     albertel 14384: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14385: 		$lonid_to_ip{$id} = $ip;
                   14386: 	    }
                   14387: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14388: 	}
1.1172.2.70  raeburn  14389:         unless ($nocache) {
                   14390: 	    &do_cache_new('iphost','iphost',
                   14391: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14392: 		          48*60*60);
                   14393:         }
1.869     albertel 14394: 
1.847     albertel 14395: 	return %iphost;
1.598     albertel 14396:     }
                   14397: 
1.992     raeburn  14398:     #
                   14399:     #  Given a DNS returns the loncapa host name for that DNS 
                   14400:     # 
                   14401:     sub host_from_dns {
                   14402:         my ($dns) = @_;
                   14403:         my @hosts;
                   14404:         my $ip;
                   14405: 
1.993     raeburn  14406:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14407:             $ip = $name_to_ip{$dns};
                   14408:         }
                   14409:         if (!$ip) {
                   14410:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14411:             if (length($ip) == 4) { 
                   14412: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14413:             }
                   14414:         }
                   14415:         if ($ip) {
                   14416: 	    @hosts = get_hosts_from_ip($ip);
                   14417: 	    return $hosts[0];
                   14418:         }
                   14419:         return undef;
1.986     foxr     14420:     }
1.992     raeburn  14421: 
1.1074    raeburn  14422:     sub get_internet_names {
                   14423:         my ($lonid) = @_;
                   14424:         return if ($lonid eq '');
                   14425:         my ($idnref,$cached)=
                   14426:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14427:         if ($cached) {
                   14428:             return $idnref;
                   14429:         }
                   14430:         my $ip = &get_host_ip($lonid);
                   14431:         my @hosts = &get_hosts_from_ip($ip);
                   14432:         my %iphost = &get_iphost();
                   14433:         my (@idns,%seen);
                   14434:         foreach my $id (@hosts) {
                   14435:             my $dom = &host_domain($id);
                   14436:             my $prim_id = &domain($dom,'primary');
                   14437:             my $prim_ip = &get_host_ip($prim_id);
                   14438:             next if ($seen{$prim_ip});
                   14439:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14440:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14441:                     my $intdom = &internet_dom($id);
                   14442:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14443:                         push(@idns,$intdom);
                   14444:                     }
                   14445:                 }
                   14446:             }
                   14447:             $seen{$prim_ip} = 1;
                   14448:         }
1.1172.2.23  raeburn  14449:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14450:     }
                   14451: 
1.986     foxr     14452: }
                   14453: 
1.1079    raeburn  14454: sub all_loncaparevs {
1.1172.2.39  raeburn  14455:     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  14456: }
                   14457: 
1.1172.2.27  raeburn  14458: # ------------------------------------------------------- Read loncaparev table
                   14459: {
                   14460:     sub load_loncaparevs {
                   14461:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14462:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14463:                 while (my $configline=<$config>) {
                   14464:                     chomp($configline);
                   14465:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14466:                     $loncaparevs{$hostid}=$loncaparev;
                   14467:                 }
                   14468:                 close($config);
                   14469:             }
                   14470:         }
                   14471:     }
                   14472: }
                   14473: 
                   14474: # ----------------------------------------------------- Read serverhostID table
                   14475: {
                   14476:     sub load_serverhomeIDs {
                   14477:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14478:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14479:                 while (my $configline=<$config>) {
                   14480:                     chomp($configline);
                   14481:                     my ($name,$id)=split(/:/,$configline);
                   14482:                     $serverhomeIDs{$name}=$id;
                   14483:                 }
                   14484:                 close($config);
                   14485:             }
                   14486:         }
                   14487:     }
                   14488: }
                   14489: 
                   14490: 
1.862     albertel 14491: BEGIN {
                   14492: 
                   14493: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14494:     unless ($readit) {
                   14495: {
                   14496:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14497:     %perlvar = (%perlvar,%{$configvars});
                   14498: }
                   14499: 
                   14500: 
1.1       albertel 14501: # ------------------------------------------------------ Read spare server file
                   14502: {
1.1172.2.96  raeburn  14503:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14504: 
                   14505:     while (my $configline=<$config>) {
                   14506:        chomp($configline);
1.284     matthew  14507:        if ($configline) {
1.784     albertel 14508: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14509: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14510: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14511:        }
                   14512:     }
1.448     albertel 14513:     close($config);
1.1       albertel 14514: }
1.11      www      14515: # ------------------------------------------------------------ Read permissions
                   14516: {
1.1172.2.96  raeburn  14517:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14518: 
                   14519:     while (my $configline=<$config>) {
1.448     albertel 14520: 	chomp($configline);
                   14521: 	if ($configline) {
                   14522: 	    my ($role,$perm)=split(/ /,$configline);
                   14523: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14524: 	}
1.11      www      14525:     }
1.448     albertel 14526:     close($config);
1.11      www      14527: }
                   14528: 
                   14529: # -------------------------------------------- Read plain texts for permissions
                   14530: {
1.1172.2.96  raeburn  14531:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14532: 
                   14533:     while (my $configline=<$config>) {
1.448     albertel 14534: 	chomp($configline);
                   14535: 	if ($configline) {
1.742     raeburn  14536: 	    my ($short,@plain)=split(/:/,$configline);
                   14537:             %{$prp{$short}} = ();
                   14538: 	    if (@plain > 0) {
                   14539:                 $prp{$short}{'std'} = $plain[0];
                   14540:                 for (my $i=1; $i<@plain; $i++) {
                   14541:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14542:                 }
                   14543:             }
1.448     albertel 14544: 	}
1.135     www      14545:     }
1.448     albertel 14546:     close($config);
1.135     www      14547: }
                   14548: 
                   14549: # ---------------------------------------------------------- Read package table
                   14550: {
1.1172.2.96  raeburn  14551:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14552: 
                   14553:     while (my $configline=<$config>) {
1.483     albertel 14554: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14555: 	chomp($configline);
                   14556: 	my ($short,$plain)=split(/:/,$configline);
                   14557: 	my ($pack,$name)=split(/\&/,$short);
                   14558: 	if ($plain ne '') {
                   14559: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14560: 	    $packagetab{$short}=$plain; 
                   14561: 	}
1.11      www      14562:     }
1.448     albertel 14563:     close($config);
1.329     matthew  14564: }
                   14565: 
1.1172.2.27  raeburn  14566: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14567: 
1.1172.2.27  raeburn  14568: &load_loncaparevs();
                   14569: 
                   14570: # ------------------------------------------------------- Read serverhostID table
                   14571: 
                   14572: &load_serverhomeIDs();
1.1074    raeburn  14573: 
1.1172.2.27  raeburn  14574: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14575: {
                   14576:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14577:     if (-e $file) {
                   14578:         my $parser = HTML::LCParser->new($file);
                   14579:         while (my $token = $parser->get_token()) {
                   14580:             if ($token->[0] eq 'S') {
                   14581:                 my $item = $token->[1];
                   14582:                 my $name = $token->[2]{'name'};
                   14583:                 my $value = $token->[2]{'value'};
                   14584:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14585:                     my $release = $parser->get_text();
                   14586:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14587:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14588:                 }
                   14589:             }
                   14590:         }
                   14591:     }
1.1073    raeburn  14592: }
                   14593: 
1.1138    raeburn  14594: # ---------------------------------------------------------- Read managers table
                   14595: {
                   14596:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14597:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14598:             while (my $configline=<$config>) {
                   14599:                 chomp($configline);
                   14600:                 next if ($configline =~ /^\#/);
                   14601:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14602:                     $managerstab{$configline} = 1;
                   14603:                 }
                   14604:             }
                   14605:             close($config);
                   14606:         }
                   14607:     }
                   14608: }
                   14609: 
1.329     matthew  14610: # ------------- set up temporary directory
                   14611: {
1.1117    foxr     14612:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14613: 
1.11      www      14614: }
                   14615: 
1.1172.2.104  raeburn  14616: # ------------- set default texengine (domain default overrides this)
                   14617: {
                   14618:     $deftex = LONCAPA::texengine();
                   14619: }
                   14620: 
1.1172.2.114  raeburn  14621: # ------------- set default minimum length for passwords for internal auth users
                   14622: {
                   14623:     $passwdmin = LONCAPA::passwd_min();
                   14624: }
                   14625: 
1.794     albertel 14626: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14627: 				'compress_threshold'=> 20_000,
                   14628:  			        });
1.185     www      14629: 
1.281     www      14630: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14631: $dumpcount=0;
1.958     www      14632: $locknum=0;
1.22      www      14633: 
1.163     harris41 14634: &logtouch();
1.672     albertel 14635: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14636: $readit=1;
1.564     albertel 14637:     {
                   14638: 	use integer;
                   14639: 	my $test=(2**32)+1;
1.568     albertel 14640: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14641: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14642:     }
1.195     www      14643: }
1.1       albertel 14644: }
1.179     www      14645: 
1.1       albertel 14646: 1;
1.191     harris41 14647: __END__
                   14648: 
1.243     albertel 14649: =pod
                   14650: 
1.191     harris41 14651: =head1 NAME
                   14652: 
1.243     albertel 14653: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14654: 
                   14655: =head1 SYNOPSIS
                   14656: 
1.243     albertel 14657: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14658: 
                   14659:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14660: 
1.243     albertel 14661: Common parameters:
                   14662: 
                   14663: =over 4
                   14664: 
                   14665: =item *
                   14666: 
                   14667: $uname : an internal username (if $cname expecting a course Id specifically)
                   14668: 
                   14669: =item *
                   14670: 
                   14671: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14672: 
                   14673: =item *
                   14674: 
                   14675: $symb : a resource instance identifier
                   14676: 
                   14677: =item *
                   14678: 
                   14679: $namespace : the name of a .db file that contains the data needed or
                   14680: being set.
                   14681: 
                   14682: =back
                   14683: 
1.394     bowersj2 14684: =head1 OVERVIEW
1.191     harris41 14685: 
1.394     bowersj2 14686: lonnet provides subroutines which interact with the
                   14687: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14688: about classes, users, and resources.
1.243     albertel 14689: 
                   14690: For many of these objects you can also use this to store data about
                   14691: them or modify them in various ways.
1.191     harris41 14692: 
1.394     bowersj2 14693: =head2 Symbs
1.191     harris41 14694: 
1.394     bowersj2 14695: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14696: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14697: map, the resource number of the resource in the map, and the URL of
                   14698: the resource itself. The latter is somewhat redundant, but might help
                   14699: if maps change.
                   14700: 
                   14701: An example is
                   14702: 
                   14703:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14704: 
                   14705: The respective map entry is
                   14706: 
                   14707:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14708:   title="Problem 2">
                   14709:  </resource>
                   14710: 
                   14711: Symbs are used by the random number generator, as well as to store and
                   14712: restore data specific to a certain instance of for example a problem.
                   14713: 
                   14714: =head2 Storing And Retrieving Data
                   14715: 
                   14716: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14717: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14718: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14719: is is the non-critical message twin of cstore. These functions are for
                   14720: handlers to store a perl hash to a user's permanent data space in an
                   14721: easy manner, and to retrieve it again on another call. It is expected
                   14722: that a handler would use this once at the beginning to retrieve data,
                   14723: and then again once at the end to send only the new data back.
                   14724: 
                   14725: The data is stored in the user's data directory on the user's
                   14726: homeserver under the ID of the course.
                   14727: 
                   14728: The hash that is returned by restore will have all of the previous
                   14729: value for all of the elements of the hash.
                   14730: 
                   14731: Example:
                   14732: 
                   14733:  #creating a hash
                   14734:  my %hash;
                   14735:  $hash{'foo'}='bar';
                   14736: 
                   14737:  #storing it
                   14738:  &Apache::lonnet::cstore(\%hash);
                   14739: 
                   14740:  #changing a value
                   14741:  $hash{'foo'}='notbar';
                   14742: 
                   14743:  #adding a new value
                   14744:  $hash{'bar'}='foo';
                   14745:  &Apache::lonnet::cstore(\%hash);
                   14746: 
                   14747:  #retrieving the hash
                   14748:  my %history=&Apache::lonnet::restore();
                   14749: 
                   14750:  #print the hash
                   14751:  foreach my $key (sort(keys(%history))) {
                   14752:    print("\%history{$key} = $history{$key}");
                   14753:  }
                   14754: 
                   14755: Will print out:
1.191     harris41 14756: 
1.394     bowersj2 14757:  %history{1:foo} = bar
                   14758:  %history{1:keys} = foo:timestamp
                   14759:  %history{1:timestamp} = 990455579
                   14760:  %history{2:bar} = foo
                   14761:  %history{2:foo} = notbar
                   14762:  %history{2:keys} = foo:bar:timestamp
                   14763:  %history{2:timestamp} = 990455580
                   14764:  %history{bar} = foo
                   14765:  %history{foo} = notbar
                   14766:  %history{timestamp} = 990455580
                   14767:  %history{version} = 2
                   14768: 
                   14769: Note that the special hash entries C<keys>, C<version> and
                   14770: C<timestamp> were added to the hash. C<version> will be equal to the
                   14771: total number of versions of the data that have been stored. The
                   14772: C<timestamp> attribute will be the UNIX time the hash was
                   14773: stored. C<keys> is available in every historical section to list which
                   14774: keys were added or changed at a specific historical revision of a
                   14775: hash.
                   14776: 
                   14777: B<Warning>: do not store the hash that restore returns directly. This
                   14778: will cause a mess since it will restore the historical keys as if the
                   14779: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14780: 
1.394     bowersj2 14781: Calling convention:
1.191     harris41 14782: 
1.1172.2.27  raeburn  14783:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14784:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14785: 
1.394     bowersj2 14786: For more detailed information, see lonnet specific documentation.
1.191     harris41 14787: 
1.394     bowersj2 14788: =head1 RETURN MESSAGES
1.191     harris41 14789: 
1.394     bowersj2 14790: =over 4
1.191     harris41 14791: 
1.394     bowersj2 14792: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14793: 
1.394     bowersj2 14794: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14795: when the connection is brought back up
1.191     harris41 14796: 
1.394     bowersj2 14797: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14798: for later delivery
1.191     harris41 14799: 
1.967     bisitz   14800: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14801: 
1.394     bowersj2 14802: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14803: that was requested
1.191     harris41 14804: 
1.243     albertel 14805: =back
1.191     harris41 14806: 
1.243     albertel 14807: =head1 PUBLIC SUBROUTINES
1.191     harris41 14808: 
1.243     albertel 14809: =head2 Session Environment Functions
1.191     harris41 14810: 
1.243     albertel 14811: =over 4
1.191     harris41 14812: 
1.394     bowersj2 14813: =item * 
                   14814: X<appenv()>
1.949     raeburn  14815: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14816: the user envirnoment file, and will be restored for each access this
1.620     albertel 14817: user makes during this session, also modifies the %env for the current
1.949     raeburn  14818: process. Optional rolesarrayref - if defined contains a reference to an array
                   14819: of roles which are exempt from the restriction on modifying user.role entries 
                   14820: in the user's environment.db and in %env.    
1.191     harris41 14821: 
                   14822: =item *
1.394     bowersj2 14823: X<delenv()>
1.987     raeburn  14824: B<delenv($delthis,$regexp)>: removes all items from the session
                   14825: environment file that begin with $delthis. If the 
                   14826: optional second arg - $regexp - is true, $delthis is treated as a 
                   14827: regular expression, otherwise \Q$delthis\E is used. 
                   14828: The values are also deleted from the current processes %env.
1.191     harris41 14829: 
1.795     albertel 14830: =item * get_env_multiple($name) 
                   14831: 
                   14832: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14833: values may be defined and end up as an array ref.
                   14834: 
                   14835: returns an array of values
                   14836: 
1.243     albertel 14837: =back
                   14838: 
                   14839: =head2 User Information
1.191     harris41 14840: 
1.243     albertel 14841: =over 4
1.191     harris41 14842: 
                   14843: =item *
1.394     bowersj2 14844: X<queryauthenticate()>
                   14845: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14846: authentication scheme
                   14847: 
                   14848: =item *
1.394     bowersj2 14849: X<authenticate()>
1.1073    raeburn  14850: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14851: authenticate user from domain's lib servers (first use the current
                   14852: one). C<$upass> should be the users password.
1.1073    raeburn  14853: $checkdefauth is optional (value is 1 if a check should be made to
                   14854:    authenticate user using default authentication method, and allow
                   14855:    account creation if username does not have account in the domain).
                   14856: $clientcancheckhost is optional (value is 1 if checking whether the
                   14857:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14858: 
                   14859: =item *
1.394     bowersj2 14860: X<homeserver()>
                   14861: B<homeserver($uname,$udom)>: find the server which has
                   14862: the user's directory and files (there must be only one), this caches
                   14863: the answer, and also caches if there is a borken connection.
1.191     harris41 14864: 
                   14865: =item *
1.394     bowersj2 14866: X<idget()>
                   14867: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14868: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14869: username, and only 1 username per ID in a specific domain) (returns
                   14870: hash: id=>name,id=>name)
1.191     harris41 14871: 
                   14872: =item *
1.394     bowersj2 14873: X<idrget()>
                   14874: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14875: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14876: 
                   14877: =item *
1.394     bowersj2 14878: X<idput()>
                   14879: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14880: 
                   14881: =item *
1.394     bowersj2 14882: X<rolesinit()>
1.1169    droeschl 14883: B<rolesinit($udom,$username)>: get user privileges.
                   14884: returns user role, first access and timer interval hashes
1.243     albertel 14885: 
                   14886: =item *
1.1171    droeschl 14887: X<privileged()>
                   14888: B<privileged($username,$domain)>: returns a true if user has a
                   14889: privileged and active role (i.e. su or dc), false otherwise.
                   14890: 
                   14891: =item *
1.551     albertel 14892: X<getsection()>
                   14893: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14894: course $cname, return section name/number or '' for "not in course"
                   14895: and '-1' for "no section"
                   14896: 
                   14897: =item *
1.394     bowersj2 14898: X<userenvironment()>
                   14899: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14900: passed in @what from the requested user's environment, returns a hash
                   14901: 
1.858     raeburn  14902: =item * 
                   14903: X<userlog_query()>
1.859     albertel 14904: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14905: activity.log file. %filters defines filters applied when parsing the
                   14906: log file. These can be start or end timestamps, or the type of action
                   14907: - log to look for Login or Logout events, check for Checkin or
                   14908: Checkout, role for role selection. The response is in the form
                   14909: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14910: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14911: 
1.243     albertel 14912: =back
                   14913: 
                   14914: =head2 User Roles
                   14915: 
                   14916: =over 4
                   14917: 
                   14918: =item *
                   14919: 
1.1172.2.65  raeburn  14920: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14921: returns codes for allowed actions.
                   14922: 
                   14923: The first argument is required, all others are optional.
                   14924: 
                   14925: $priv is the privilege being checked.
                   14926: $uri contains additional information about what is being checked for access (e.g.,
                   14927: URL, course ID etc.).
                   14928: $symb is the unique resource instance identifier in a course; if needed,
                   14929: but not provided, it will be retrieved via a call to &symbread().
                   14930: $role is the role for which a priv is being checked (only used if priv is evb).
                   14931: $clientip is the user's IP address (only used when checking for access to portfolio
                   14932: files).
                   14933: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14934: prevents recursive calls to &allowed.
                   14935: 
1.243     albertel 14936:  F: full access
                   14937:  U,I,K: authentication modes (cxx only)
                   14938:  '': forbidden
                   14939:  1: user needs to choose course
                   14940:  2: browse allowed
1.766     albertel 14941:  A: passphrase authentication needed
1.1172.2.65  raeburn  14942:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14943: 
                   14944: =item *
                   14945: 
1.1172.2.13  raeburn  14946: constructaccess($url,$setpriv) : check for access to construction space URL
                   14947: 
                   14948: See if the owner domain and name in the URL match those in the
                   14949: expected environment.  If so, return three element list
                   14950: ($ownername,$ownerdomain,$ownerhome).
                   14951: 
                   14952: Otherwise return the null string.
                   14953: 
                   14954: If second argument 'setpriv' is true, it assigns the privileges,
                   14955: and returns the same three element list, unless the owner has
                   14956: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14957: in which case the null string is returned.
                   14958: 
                   14959: =item *
                   14960: 
1.1172.2.84  raeburn  14961: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14962: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14963: for system, domain, and course level. $uname and $udom are optional (current
                   14964: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14965: 
                   14966: =item *
                   14967: 
1.988     raeburn  14968: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14969: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14970: $type is Course (default) or Community.
1.988     raeburn  14971: If $forcedefault evaluates to true, text returned will be default 
                   14972: text for $type. Otherwise, if this is a course, the text returned 
                   14973: will be a custom name for the role (if defined in the course's 
                   14974: environment).  If no custom name is defined the default is returned.
                   14975:    
1.832     raeburn  14976: =item *
                   14977: 
1.1172.2.23  raeburn  14978: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14979: All arguments are optional. Returns a hash of a roles, either for
                   14980: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14981: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14982: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14983: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14984: For each key, value is set to colon-separated start and end times for
                   14985: the role.  If no username and domain are specified, will default to
1.934     raeburn  14986: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14987: of role statuses (active, future or previous), roles 
                   14988: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14989: to restrict the list of roles reported. If no array ref is 
                   14990: provided for types, will default to return only active roles.
1.834     albertel 14991: 
1.1172.2.13  raeburn  14992: =item *
                   14993: 
                   14994: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14995: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14996: 
                   14997: Additional optional arguments are: $type (if role checking is to be restricted
                   14998: to certain user status types -- previous (expired roles), active (currently
                   14999: available roles) or future (roles available in the future), and
                   15000: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15001: have active Domain Coordinator role in course's domain or in additional
                   15002: domains (specified in 'Domains to check for privileged users' in course
                   15003: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15004: 
                   15005: =item *
                   15006: 
                   15007: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15008: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15009: $possdomains and $possroles are optional array refs -- to domains to check and
                   15010: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15011: users' roles.db to check for a dc or su role in any domain. This can be
                   15012: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15013: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15014: this then allows &privileged_by_domain() to be used, which caches the identity
                   15015: of privileged users, eliminating the need for repeated calls to &dump().
                   15016: 
                   15017: =item *
                   15018: 
                   15019: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15020: where the outer hash keys are domains specified in the $possdomains array ref,
                   15021: next inner hash keys are privileged roles specified in the $roles array ref,
                   15022: and the innermost hash contains key = value pairs for username:domain = end:start
                   15023: for active or future "privileged" users with that role in that domain. To avoid
                   15024: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15025: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15026: 
1.243     albertel 15027: =back
                   15028: 
                   15029: =head2 User Modification
                   15030: 
                   15031: =over 4
                   15032: 
                   15033: =item *
                   15034: 
1.957     raeburn  15035: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15036: user for the level given by URL.  Optional start and end dates (leave empty
                   15037: string or zero for "no date")
1.191     harris41 15038: 
                   15039: =item *
                   15040: 
1.243     albertel 15041: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15042: change a users, password, possible return values are: ok,
                   15043: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15044: refused
1.191     harris41 15045: 
                   15046: =item *
                   15047: 
1.243     albertel 15048: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15049: 
                   15050: =item *
                   15051: 
1.1058    raeburn  15052: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15053:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15054: 
                   15055: will update user information (firstname,middlename,lastname,generation,
                   15056: permanentemail), and if forceid is true, student/employee ID also.
                   15057: A user's institutional affiliation(s) can also be updated.
                   15058: User information fields will not be overwritten with empty entries 
                   15059: unless the field is included in the $candelete array reference.
                   15060: This array is included when a single user is modified via "Manage Users",
                   15061: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15062: 
                   15063: =item *
                   15064: 
1.286     matthew  15065: modifystudent
                   15066: 
1.957     raeburn  15067: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15068: The course id is resolved based on the current user's environment.  
                   15069: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15070: associated with a course.
                   15071: 
1.297     matthew  15072: This call is essentially a wrapper for lonnet::modifyuser and
                   15073: lonnet::modify_student_enrollment
1.286     matthew  15074: 
                   15075: Inputs: 
                   15076: 
                   15077: =over 4
                   15078: 
1.957     raeburn  15079: =item B<$udom> Student's loncapa domain
1.286     matthew  15080: 
1.957     raeburn  15081: =item B<$uname> Student's loncapa login name
1.286     matthew  15082: 
1.964     bisitz   15083: =item B<$uid> Student/Employee ID
1.286     matthew  15084: 
1.957     raeburn  15085: =item B<$umode> Student's authentication mode
1.286     matthew  15086: 
1.957     raeburn  15087: =item B<$upass> Student's password
1.286     matthew  15088: 
1.957     raeburn  15089: =item B<$first> Student's first name
1.286     matthew  15090: 
1.957     raeburn  15091: =item B<$middle> Student's middle name
1.286     matthew  15092: 
1.957     raeburn  15093: =item B<$last> Student's last name
1.286     matthew  15094: 
1.957     raeburn  15095: =item B<$gene> Student's generation
1.286     matthew  15096: 
1.957     raeburn  15097: =item B<$usec> Student's section in course
1.286     matthew  15098: 
                   15099: =item B<$end> Unix time of the roles expiration
                   15100: 
                   15101: =item B<$start> Unix time of the roles start date
                   15102: 
                   15103: =item B<$forceid> If defined, allow $uid to be changed
                   15104: 
                   15105: =item B<$desiredhome> server to use as home server for student
                   15106: 
1.957     raeburn  15107: =item B<$email> Student's permanent e-mail address
                   15108: 
                   15109: =item B<$type> Type of enrollment (auto or manual)
                   15110: 
1.963     raeburn  15111: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15112: 
                   15113: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15114: 
1.963     raeburn  15115: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15116: 
1.963     raeburn  15117: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15118: 
1.1172.2.19  raeburn  15119: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15120: 
                   15121: =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  15122: 
1.286     matthew  15123: =back
1.297     matthew  15124: 
                   15125: =item *
                   15126: 
                   15127: modify_student_enrollment
                   15128: 
1.1172.2.31  raeburn  15129: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15130: 'role.request.course' must be defined for this function to proceed.
                   15131: 
                   15132: Inputs:
                   15133: 
                   15134: =over 4
                   15135: 
1.1172.2.31  raeburn  15136: =item $udom, student's domain
1.297     matthew  15137: 
1.1172.2.31  raeburn  15138: =item $uname, student's name
1.297     matthew  15139: 
1.1172.2.31  raeburn  15140: =item $uid, student's user id
1.297     matthew  15141: 
1.1172.2.31  raeburn  15142: =item $first, student's first name
1.297     matthew  15143: 
                   15144: =item $middle
                   15145: 
                   15146: =item $last
                   15147: 
                   15148: =item $gene
                   15149: 
                   15150: =item $usec
                   15151: 
                   15152: =item $end
                   15153: 
                   15154: =item $start
                   15155: 
1.957     raeburn  15156: =item $type
                   15157: 
                   15158: =item $locktype
                   15159: 
                   15160: =item $cid
                   15161: 
                   15162: =item $selfenroll
                   15163: 
                   15164: =item $context
                   15165: 
1.1172.2.19  raeburn  15166: =item $credits, number of credits student will earn from this class
                   15167: 
1.1172.2.76  raeburn  15168: =item $instsec, institutional course section code for student
                   15169: 
1.297     matthew  15170: =back
                   15171: 
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.243     albertel 15175: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15176: custom role; give a custom role to a user for the level given by URL.  Specify
                   15177: name and domain of role author, and role name
1.191     harris41 15178: 
                   15179: =item *
                   15180: 
1.243     albertel 15181: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15182: 
                   15183: =item *
                   15184: 
1.243     albertel 15185: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15186: 
                   15187: =back
                   15188: 
                   15189: =head2 Course Infomation
                   15190: 
                   15191: =over 4
1.191     harris41 15192: 
                   15193: =item *
                   15194: 
1.1118    foxr     15195: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15196: specified course id, including all environment settings for the
                   15197: course, the description of the course will be in the hash under the
                   15198: key 'description'
1.191     harris41 15199: 
1.1118    foxr     15200: $options is an optional parameter that if supplied is a hash reference that controls
                   15201: what how this function works.  It has the following key/values:
                   15202: 
                   15203: =over 4
                   15204: 
                   15205: =item freshen_cache
                   15206: 
                   15207: If defined, and the environment cache for the course is valid, it is 
                   15208: returned in the returned hash.
                   15209: 
                   15210: =item one_time
                   15211: 
                   15212: If defined, the last cache time is set to _now_
                   15213: 
                   15214: =item user
                   15215: 
                   15216: If defined, the supplied username is used instead of the current user.
                   15217: 
                   15218: 
                   15219: =back
                   15220: 
1.191     harris41 15221: =item *
                   15222: 
1.624     albertel 15223: resdata($name,$domain,$type,@which) : request for current parameter
                   15224: setting for a specific $type, where $type is either 'course' or 'user',
                   15225: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15226: answers for 10 minutes.
1.243     albertel 15227: 
1.877     foxr     15228: =item *
                   15229: 
                   15230: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15231: data base, returning a hash that is keyed by the resource name and has
                   15232: values that are the resource value.  I believe that the timestamps and
                   15233: versions are also returned.
                   15234: 
1.1172.2.31  raeburn  15235: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15236: supplemental content area. This routine caches the number of files for
                   15237: 10 minutes.
                   15238: 
1.243     albertel 15239: =back
                   15240: 
                   15241: =head2 Course Modification
                   15242: 
                   15243: =over 4
1.191     harris41 15244: 
                   15245: =item *
                   15246: 
1.243     albertel 15247: writecoursepref($courseid,%prefs) : write preferences (environment
                   15248: database) for a course
1.191     harris41 15249: 
                   15250: =item *
                   15251: 
1.1011    raeburn  15252: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15253: 
                   15254: =item *
                   15255: 
1.1038    raeburn  15256: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15257: 
1.1167    droeschl 15258: =item *
                   15259: 
                   15260: is_course($courseid), is_course($cdom, $cnum)
                   15261: 
                   15262: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15263: two component version $cdom, $cnum. It checks if the specified course exists.
                   15264: 
                   15265: Returns:
                   15266:     undef if the course doesn't exist, otherwise
                   15267:     in scalar context the combined courseid.
                   15268:     in list context the two components of the course identifier, domain and 
                   15269:     courseid.    
                   15270: 
1.243     albertel 15271: =back
                   15272: 
1.1172.2.109  raeburn  15273: =head2 Bubblesheet Configuration
                   15274: 
                   15275: =over 4
                   15276: 
                   15277: =item *
                   15278: 
                   15279: get_scantron_config($which)
                   15280: 
                   15281: $which - the name of the configuration to parse from the file.
                   15282: 
                   15283: Parses and returns the bubblesheet configuration line selected as a
                   15284: hash of configuration file fields.
                   15285: 
                   15286: 
                   15287: Returns:
                   15288:     If the named configuration is not in the file, an empty
                   15289:     hash is returned.
                   15290: 
                   15291:     a hash with the fields
                   15292:       name         - internal name for the this configuration setup
                   15293:       description  - text to display to operator that describes this config
                   15294:       CODElocation - if 0 or the string 'none'
                   15295:                           - no CODE exists for this config
                   15296:                      if -1 || the string 'letter'
                   15297:                           - a CODE exists for this config and is
                   15298:                             a string of letters
                   15299:                      Unsupported value (but planned for future support)
                   15300:                           if a positive integer
                   15301:                                - The CODE exists as the first n items from
                   15302:                                  the question section of the form
                   15303:                           if the string 'number'
                   15304:                                - The CODE exists for this config and is
                   15305:                                  a string of numbers
                   15306:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15307:                      the CODE starts
                   15308:       CODElength  - length of the CODE
                   15309:       IDstart     - column where the student/employee ID starts
                   15310:       IDlength    - length of the student/employee ID info
                   15311:       Qstart      - column where the information from the bubbled
                   15312:                     'questions' start
                   15313:       Qlength     - number of columns comprising a single bubble line from
                   15314:                     the sheet. (usually either 1 or 10)
                   15315:       Qon         - either a single character representing the character used
                   15316:                     to signal a bubble was chosen in the positional setup, or
                   15317:                     the string 'letter' if the letter of the chosen bubble is
                   15318:                     in the final, or 'number' if a number representing the
                   15319:                     chosen bubble is in the file (1->A 0->J)
                   15320:       Qoff        - the character used to represent that a bubble was
                   15321:                     left blank
                   15322:       PaperID     - if the scanning process generates a unique number for each
                   15323:                     sheet scanned the column that this ID number starts in
                   15324:       PaperIDlength - number of columns that comprise the unique ID number
                   15325:                       for the sheet of paper
                   15326:       FirstName   - column that the first name starts in
                   15327:       FirstNameLength - number of columns that the first name spans
                   15328:       LastName    - column that the last name starts in
                   15329:       LastNameLength - number of columns that the last name spans
                   15330:       BubblesPerRow - number of bubbles available in each row used to
                   15331:                       bubble an answer. (If not specified, 10 assumed).
                   15332: 
                   15333: 
                   15334: =item *
                   15335: 
                   15336: get_scantronformat_file($cdom)
                   15337: 
                   15338: $cdom - the course's domain (optional); if not supplied, uses
                   15339: domain for current $env{'request.course.id'}.
                   15340: 
                   15341: Returns an array containing lines from the scantron format file for
                   15342: the domain of the course.
                   15343: 
                   15344: If a url for a custom.tab file is listed in domain's configuration.db,
                   15345: lines are from this file.
                   15346: 
                   15347: Otherwise, if a default.tab has been published in RES space by the
                   15348: domainconfig user, lines are from this file.
                   15349: 
                   15350: Otherwise, fall back to getting lines from the legacy file on the
                   15351: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15352: 
                   15353: =back
                   15354: 
1.243     albertel 15355: =head2 Resource Subroutines
                   15356: 
                   15357: =over 4
1.191     harris41 15358: 
                   15359: =item *
                   15360: 
1.243     albertel 15361: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15362: 
                   15363: =item *
                   15364: 
1.243     albertel 15365: repcopy($filename) : subscribes to the requested file, and attempts to
                   15366: replicate from the owning library server, Might return
1.607     raeburn  15367: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15368: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15369: resource. Expects the local filesystem pathname
                   15370: (/home/httpd/html/res/....)
                   15371: 
                   15372: =back
                   15373: 
                   15374: =head2 Resource Information
                   15375: 
                   15376: =over 4
1.191     harris41 15377: 
                   15378: =item *
                   15379: 
1.1172.2.28  raeburn  15380: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15381: and returns the value of a variety of different possible values,
                   15382: $varname should be a request string, and the other parameters can be
                   15383: used to specify who and what one is asking about. Ordinarily, $cid 
                   15384: does not need to be specified, as it is retrived from 
                   15385: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15386: within lonuserstate::loadmap() when initializing a course, before
                   15387: $env{'request.course.id'} has been set, so it needs to be provided
                   15388: in that one case.
1.243     albertel 15389: 
                   15390: Possible values for $varname are environment.lastname (or other item
                   15391: from the envirnment hash), user.name (or someother aspect about the
                   15392: user), resource.0.maxtries (or some other part and parameter of a
                   15393: resource)
1.204     albertel 15394: 
                   15395: =item *
                   15396: 
1.243     albertel 15397: directcondval($number) : get current value of a condition; reads from a state
                   15398: string
1.204     albertel 15399: 
                   15400: =item *
                   15401: 
1.243     albertel 15402: condval($condidx) : value of condition index based on state
1.204     albertel 15403: 
                   15404: =item *
                   15405: 
1.243     albertel 15406: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15407: resource's metadata, $what should be either a specific key, or either
                   15408: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15409: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15410: 
                   15411: this function automatically caches all requests
1.191     harris41 15412: 
                   15413: =item *
                   15414: 
1.243     albertel 15415: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15416: network of library servers; returns file handle of where SQL and regex results
                   15417: will be stored for query
1.191     harris41 15418: 
                   15419: =item *
                   15420: 
1.1172.2.66  raeburn  15421: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15422: return symbolic list entry (all arguments optional).
                   15423: 
                   15424: Args: filename is the filename (including path) for the file for which a symb
                   15425: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15426: to check access status if more than one resource was found in the bighash
                   15427: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15428: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15429: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15430: cause possible symbs to be checked to determine if they are subject to content
                   15431: blocking, if so they will not be included as possible symbs; possibles is a
                   15432: ref to a hash, which, as a side effect, will be populated with all possible
                   15433: symbs (content blocking not tested).
                   15434: 
1.243     albertel 15435: returns the data handle
1.191     harris41 15436: 
                   15437: =item *
                   15438: 
1.1172.2.17  raeburn  15439: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15440: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15441: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15442: on failure, user must be in a course, as it assumes the existence of
                   15443: the course initial hash, and uses $env('request.course.id'}.  The third
                   15444: arg is an optional reference to a scalar.  If this arg is passed in the
                   15445: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15446: encrypted; otherwise it will be null.
1.243     albertel 15447: 
1.191     harris41 15448: =item *
                   15449: 
1.243     albertel 15450: symbclean($symb) : removes versions numbers from a symb, returns the
                   15451: cleaned symb
1.191     harris41 15452: 
                   15453: =item *
                   15454: 
1.243     albertel 15455: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15456: course map, user must be in a course for it to work.
1.191     harris41 15457: 
                   15458: =item *
                   15459: 
1.243     albertel 15460: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15461: 
                   15462: =item *
                   15463: 
1.243     albertel 15464: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15465: a random seed, all arguments are optional, if they aren't sent it uses the
                   15466: environment to derive them. Note: if symb isn't sent and it can't get one
                   15467: from &symbread it will use the current time as its return value
1.191     harris41 15468: 
                   15469: =item *
                   15470: 
1.243     albertel 15471: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15472: unfakeable, receipt
1.191     harris41 15473: 
                   15474: =item *
                   15475: 
1.620     albertel 15476: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15477: 
                   15478: =item *
                   15479: 
1.243     albertel 15480: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15481: 
                   15482: =item *
                   15483: 
1.243     albertel 15484: 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 15485: 
                   15486: =item *
                   15487: 
1.243     albertel 15488: 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 15489: 
                   15490: =item *
                   15491: 
1.243     albertel 15492: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15493: 
                   15494: =item *
                   15495: 
1.243     albertel 15496: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15497: forcing spreadsheet to reevaluate the resource scores next time.
                   15498: 
1.1172.2.13  raeburn  15499: =item *
                   15500: 
                   15501: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15502: when viewing in course context.
                   15503: 
                   15504:  input: six args -- filename (decluttered), course number, course domain,
                   15505:                     url, symb (if registered) and group (if this is a
                   15506:                     group item -- e.g., bulletin board, group page etc.).
                   15507: 
                   15508:  output: array of five scalars --
                   15509:          $cfile -- url for file editing if editable on current server
                   15510:          $home -- homeserver of resource (i.e., for author if published,
                   15511:                                           or course if uploaded.).
                   15512:          $switchserver --  1 if server switch will be needed.
                   15513:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15514:          $forceview -- 1 if icon/link should be to go to view mode
                   15515: 
                   15516: =item *
                   15517: 
                   15518: is_course_upload($file,$cnum,$cdom)
                   15519: 
                   15520: Used in course context to determine if current file was uploaded to
                   15521: the course (i.e., would be found in /userfiles/docs on the course's
                   15522: homeserver.
                   15523: 
                   15524:   input: 3 args -- filename (decluttered), course number and course domain.
                   15525:   output: boolean -- 1 if file was uploaded.
                   15526: 
1.243     albertel 15527: =back
                   15528: 
                   15529: =head2 Storing/Retreiving Data
                   15530: 
                   15531: =over 4
1.191     harris41 15532: 
                   15533: =item *
                   15534: 
1.1172.2.64  raeburn  15535: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15536: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15537: the remaining args aren't required and if they aren't passed or are '' they will
                   15538: be derived from the env (with the exception of $laststore, which is an
                   15539: optional arg used when a user's submission is stored in grading).
                   15540: $laststore is $version=$timestamp, where $version is the most recent version
                   15541: number retrieved for the corresponding $symb in the $namespace db file, and
                   15542: $timestamp is the timestamp for that transaction (UNIX time).
                   15543: $laststore is currently only passed when cstore() is called by
                   15544: structuretags::finalize_storage().
1.191     harris41 15545: 
                   15546: =item *
                   15547: 
1.1172.2.64  raeburn  15548: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15549: but uses critical subroutine
1.191     harris41 15550: 
                   15551: =item *
                   15552: 
1.243     albertel 15553: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15554: all args are optional
1.191     harris41 15555: 
                   15556: =item *
                   15557: 
1.717     albertel 15558: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15559: dumps the complete (or key matching regexp) namespace into a hash
                   15560: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15561: normally &store()ed into
                   15562: 
                   15563: $range should be either an integer '100' (give me the first 100
                   15564:                                            matching records)
                   15565:               or be  two integers sperated by a - with no spaces
                   15566:                  '30-50' (give me the 30th through the 50th matching
                   15567:                           records)
                   15568: 
                   15569: 
                   15570: =item *
                   15571: 
1.1172.2.59  raeburn  15572: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15573: replaces a &store() version of data with a replacement set of data
                   15574: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15575: reference. If $tolog is true, the transaction is logged in the courselog
                   15576: with an action=PUTSTORE.
1.717     albertel 15577: 
                   15578: =item *
                   15579: 
1.243     albertel 15580: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15581: works very similar to store/cstore, but all data is stored in a
                   15582: temporary location and can be reset using tmpreset, $storehash should
                   15583: be a hash reference, returns nothing on success
1.191     harris41 15584: 
                   15585: =item *
                   15586: 
1.243     albertel 15587: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15588: similar to restore, but all data is stored in a temporary location and
                   15589: can be reset using tmpreset. Returns a hash of values on success,
                   15590: error string otherwise.
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.243     albertel 15594: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15595: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15596: 
                   15597: =item *
                   15598: 
1.243     albertel 15599: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15600: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15601: 
                   15602: =item *
                   15603: 
1.243     albertel 15604: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15605: namesp ($udom and $uname are optional)
1.191     harris41 15606: 
                   15607: =item *
                   15608: 
1.702     albertel 15609: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15610: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15611: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15612: 
1.702     albertel 15613: $range should be either an integer '100' (give me the first 100
                   15614:                                            matching records)
                   15615:               or be  two integers sperated by a - with no spaces
                   15616:                  '30-50' (give me the 30th through the 50th matching
                   15617:                           records)
1.449     matthew  15618: =item *
                   15619: 
                   15620: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15621: $store can be a scalar, an array reference, or if the amount to be 
                   15622: incremented is > 1, a hash reference.
                   15623: 
                   15624: ($udom and $uname are optional)
1.191     harris41 15625: 
                   15626: =item *
                   15627: 
1.243     albertel 15628: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15629: ($udom and $uname are optional)
1.191     harris41 15630: 
                   15631: =item *
                   15632: 
1.243     albertel 15633: cput($namespace,$storehash,$udom,$uname) : critical put
                   15634: ($udom and $uname are optional)
1.191     harris41 15635: 
                   15636: =item *
                   15637: 
1.748     albertel 15638: newput($namespace,$storehash,$udom,$uname) :
                   15639: 
                   15640: Attempts to store the items in the $storehash, but only if they don't
                   15641: currently exist, if this succeeds you can be certain that you have 
                   15642: successfully created a new key value pair in the $namespace db.
                   15643: 
                   15644: 
                   15645: Args:
                   15646:  $namespace: name of database to store values to
                   15647:  $storehash: hashref to store to the db
                   15648:  $udom: (optional) domain of user containing the db
                   15649:  $uname: (optional) name of user caontaining the db
                   15650: 
                   15651: Returns:
                   15652:  'ok' -> succeeded in storing all keys of $storehash
                   15653:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15654:                         least <key> already existed in the db (other
                   15655:                         requested keys may also already exist)
1.967     bisitz   15656:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15657:  'con_lost' -> unable to contact request server
                   15658:  'refused' -> action was not allowed by remote machine
                   15659: 
                   15660: 
                   15661: =item *
                   15662: 
1.243     albertel 15663: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15664: reference filled in from namesp (encrypts the return communication)
                   15665: ($udom and $uname are optional)
1.191     harris41 15666: 
                   15667: =item *
                   15668: 
1.243     albertel 15669: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15670: critical subroutine
                   15671: 
1.806     raeburn  15672: =item *
                   15673: 
1.860     raeburn  15674: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15675: array reference filled in from namespace found in domain level on either
                   15676: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15677: 
                   15678: =item *
                   15679: 
1.860     raeburn  15680: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15681: domain level either on specified domain server ($uhome) or primary domain 
                   15682: server ($udom and $uhome are optional)
1.806     raeburn  15683: 
1.943     raeburn  15684: =item * 
                   15685: 
1.1172.2.35  raeburn  15686: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15687: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15688: the target domain.
                   15689: 
                   15690: May also include additional key => value pairs for the following groups:
                   15691: 
                   15692: =over
                   15693: 
                   15694: =item
                   15695: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15696: 
                   15697: =over
                   15698: 
                   15699: =item defaultquota, authorquota
                   15700: 
                   15701: =back
                   15702: 
                   15703: =item
                   15704: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15705: portfolio for users).
                   15706: 
                   15707: =over
                   15708: 
                   15709: =item
                   15710: aboutme, blog, webdav, portfolio
                   15711: 
                   15712: =back
                   15713: 
                   15714: =item
                   15715: requestcourses: ability to request courses, and how requests are processed.
                   15716: 
                   15717: =over
                   15718: 
                   15719: =item
1.1172.2.37  raeburn  15720: official, unofficial, community, textbook
1.1172.2.35  raeburn  15721: 
                   15722: =back
                   15723: 
                   15724: =item
                   15725: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15726: 
                   15727: =over
                   15728: 
                   15729: =item
1.1172.2.44  raeburn  15730: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15731: 
                   15732: =back
                   15733: 
                   15734: =item
                   15735: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15736: for course's uploaded content.
                   15737: 
                   15738: =over
                   15739: 
                   15740: =item
1.1172.2.68  raeburn  15741: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15742: communityquota, textbookquota
1.1172.2.35  raeburn  15743: 
                   15744: =back
                   15745: 
                   15746: =item
                   15747: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15748: on your servers.
                   15749: 
                   15750: =over
                   15751: 
                   15752: =item
                   15753: remotesessions, hostedsessions
                   15754: 
                   15755: =back
                   15756: 
                   15757: =back
                   15758: 
                   15759: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15760: utility to create a configuration.db file on a domain's primary library server
                   15761: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15762: -- corresponding values are authentication type (internal, krb4, krb5,
                   15763: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15764: will be available. Values are retrieved from cache (if current), unless the
                   15765: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15766: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15767: 
                   15768: Typical usage:
1.943     raeburn  15769: 
1.1172.2.35  raeburn  15770: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15771: 
1.243     albertel 15772: =back
                   15773: 
                   15774: =head2 Network Status Functions
                   15775: 
                   15776: =over 4
1.191     harris41 15777: 
                   15778: =item *
                   15779: 
1.1137    raeburn  15780: dirlist() : return directory list based on URI (first arg).
                   15781: 
                   15782: Inputs: 1 required, 5 optional.
                   15783: 
                   15784: =over
                   15785: 
                   15786: =item 
                   15787: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15788: 
                   15789: =item
                   15790: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15791: 
                   15792: =item
                   15793: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15794: 
                   15795: =item
                   15796: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15797: 
                   15798: =item
                   15799: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15800: 
                   15801: =item 
                   15802: $alternateRoot - path to prepend in place of path from $uri.
                   15803: 
                   15804: =back
                   15805: 
                   15806: Returns: Array of up to two items.
                   15807: 
                   15808: =over
                   15809: 
                   15810: a reference to an array of files/subdirectories
                   15811: 
                   15812: =over
                   15813: 
                   15814: Each element in the array of files/subdirectories is a & separated list of
                   15815: item name and the result of running stat on the item.  If dirlist was requested
                   15816: for a file instead of a directory, the item name will be ''. For a directory 
                   15817: listing, if the item is a metadata file, the element will end &N&M 
                   15818: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15819: default copyright set (1).  
                   15820: 
                   15821: =back
                   15822: 
                   15823: a scalar containing error condition (if encountered).
                   15824: 
                   15825: =over
                   15826: 
                   15827: =item 
                   15828: no_host (no homeserver identified for $username:$domain).
                   15829: 
                   15830: =item 
                   15831: no_such_host (server contacted for listing not identified as valid host).
                   15832: 
                   15833: =item 
                   15834: con_lost (connection to remote server failed).
                   15835: 
                   15836: =item 
                   15837: refused (invalid $username:$domain received on lond side).
                   15838: 
                   15839: =item 
                   15840: no_such_dir (directory at specified path on lond side does not exist). 
                   15841: 
                   15842: =item 
                   15843: empty (directory at specified path on lond side is empty).
                   15844: 
                   15845: =over
                   15846: 
                   15847: This is currently not encountered because the &ls3, &ls2, 
                   15848: &ls (_handler) routines on the lond side do not filter out
                   15849: . and .. from a directory listing. 
                   15850: 
                   15851: =back
                   15852: 
                   15853: =back
                   15854: 
                   15855: =back
1.191     harris41 15856: 
                   15857: =item *
                   15858: 
1.243     albertel 15859: spareserver() : find server with least workload from spare.tab
                   15860: 
1.986     foxr     15861: 
                   15862: =item *
                   15863: 
                   15864: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15865: if there is no corresponding loncapa host.
                   15866: 
1.243     albertel 15867: =back
                   15868: 
1.986     foxr     15869: 
1.243     albertel 15870: =head2 Apache Request
                   15871: 
                   15872: =over 4
1.191     harris41 15873: 
                   15874: =item *
                   15875: 
1.243     albertel 15876: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15877: localhost, posts hash
                   15878: 
                   15879: =back
                   15880: 
                   15881: =head2 Data to String to Data
                   15882: 
                   15883: =over 4
1.191     harris41 15884: 
                   15885: =item *
                   15886: 
1.243     albertel 15887: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15888: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15889: 
                   15890: =item *
                   15891: 
1.243     albertel 15892: hashref2str($hashref) : convert a hashref into a string complete with
                   15893: escaping and '=' and '&' separators, supports elements that are
                   15894: arrayrefs and hashrefs
1.191     harris41 15895: 
                   15896: =item *
                   15897: 
1.243     albertel 15898: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15899: with escaping and '&' separators, supports elements that are arrayrefs
                   15900: and hashrefs
1.191     harris41 15901: 
                   15902: =item *
                   15903: 
1.243     albertel 15904: str2hash($string) : convert string to hash using unescaping and
                   15905: splitting on '=' and '&', supports elements that are arrayrefs and
                   15906: hashrefs
1.191     harris41 15907: 
                   15908: =item *
                   15909: 
1.243     albertel 15910: str2array($string) : convert string to hash using unescaping and
                   15911: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15912: 
                   15913: =back
                   15914: 
                   15915: =head2 Logging Routines
                   15916: 
                   15917: 
                   15918: These routines allow one to make log messages in the lonnet.log and
                   15919: lonnet.perm logfiles.
1.191     harris41 15920: 
1.1119    foxr     15921: =over 4
                   15922: 
1.191     harris41 15923: =item *
                   15924: 
1.243     albertel 15925: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15926: 
                   15927: =item *
                   15928: 
1.243     albertel 15929: logthis() : append message to the normal lonnet.log file, it gets
                   15930: preiodically rolled over and deleted.
1.191     harris41 15931: 
                   15932: =item *
                   15933: 
1.243     albertel 15934: logperm() : append a permanent message to lonnet.perm.log, this log
                   15935: file never gets deleted by any automated portion of the system, only
                   15936: messages of critical importance should go in here.
                   15937: 
1.1119    foxr     15938: 
1.243     albertel 15939: =back
                   15940: 
                   15941: =head2 General File Helper Routines
                   15942: 
                   15943: =over 4
1.191     harris41 15944: 
                   15945: =item *
                   15946: 
1.481     raeburn  15947: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15948: (a) files in /uploaded
                   15949:   (i) If a local copy of the file exists - 
                   15950:       compares modification date of local copy with last-modified date for 
                   15951:       definitive version stored on home server for course. If local copy is 
                   15952:       stale, requests a new version from the home server and stores it. 
                   15953:       If the original has been removed from the home server, then local copy 
                   15954:       is unlinked.
                   15955:   (ii) If local copy does not exist -
                   15956:       requests the file from the home server and stores it. 
                   15957:   
                   15958:   If $caller is 'uploadrep':  
                   15959:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15960:     for request for files originally uploaded via DOCS. 
                   15961:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15962:   
                   15963:   Otherwise:
                   15964:      This indicates a call from the content generation phase of the request.
                   15965:      -  returns the entire contents of the file or -1.
                   15966:      
                   15967: (b) files in /res
                   15968:    - returns the entire contents of a file or -1; 
                   15969:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15970: 
1.712     albertel 15971: 
                   15972: =item *
                   15973: 
                   15974: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15975:                   reference
                   15976: 
                   15977: returns either a stat() list of data about the file or an empty list
                   15978: if the file doesn't exist or couldn't find out about it (connection
                   15979: problems or user unknown)
                   15980: 
1.191     harris41 15981: =item *
                   15982: 
1.243     albertel 15983: filelocation($dir,$file) : returns file system location of a file
                   15984: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15985: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15986: and a file of ../bob will become /a/bob)
1.191     harris41 15987: 
                   15988: =item *
                   15989: 
                   15990: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15991: filelocation except for hrefs
                   15992: 
                   15993: =item *
                   15994: 
1.1172.2.49  raeburn  15995: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15996: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15997: 
1.243     albertel 15998: =back
                   15999: 
1.608     albertel 16000: =head2 Usererfile file routines (/uploaded*)
                   16001: 
                   16002: =over 4
                   16003: 
                   16004: =item *
                   16005: 
                   16006: userfileupload(): main rotine for putting a file in a user or course's
                   16007:                   filespace, arguments are,
                   16008: 
1.620     albertel 16009:  formname - required - this is the name of the element in $env where the
1.608     albertel 16010:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16011:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16012:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16013:  context - if coursedoc, store the file in the course of the active role
                   16014:              of the current user; 
                   16015:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16016:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16017:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16018:          if undefined, it will be placed in "unknown"
                   16019: 
                   16020:  (This routine calls clean_filename() to remove any dangerous
                   16021:  characters from the filename, and then calls finuserfileupload() to
                   16022:  complete the transaction)
                   16023: 
                   16024:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16025:  and /adm/notfound.html if unsuccessful
                   16026: 
                   16027: =item *
                   16028: 
                   16029: clean_filename(): routine for cleaing a filename up for storage in
                   16030:                  userfile space, argument is:
                   16031: 
                   16032:  filename - proposed filename
                   16033: 
                   16034: returns: the new clean filename
                   16035: 
                   16036: =item *
                   16037: 
1.1090    raeburn  16038: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16039: userspace, probably shouldn't be called directly
                   16040: 
                   16041:   docuname: username or courseid of destination for the file
                   16042:   docudom: domain of user/course of destination for the file
                   16043:   formname: same as for userfileupload()
1.1090    raeburn  16044:   fname: filename (including subdirectories) for the file
                   16045:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16046:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16047:   allfiles: reference to hash used to store objects found by parser
                   16048:   codebase: reference to hash used for codebases of java objects found by parser
                   16049:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16050:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16051:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16052:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16053:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16054:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16055:   mimetype: reference to scalar to accommodate mime type determined
                   16056:             from File::MMagic if $parser = parse.
1.608     albertel 16057: 
                   16058:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16059:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16060:  was 'overwrite').
                   16061:  
1.608     albertel 16062: 
                   16063: =item *
                   16064: 
                   16065: renameuserfile(): renames an existing userfile to a new name
                   16066: 
                   16067:   Args:
                   16068:    docuname: username or courseid of destination for the file
                   16069:    docudom: domain of user/course of destination for the file
                   16070:    old: current file name (including any subdirs under userfiles)
                   16071:    new: desired file name (including any subdirs under userfiles)
                   16072: 
                   16073: =item *
                   16074: 
                   16075: mkdiruserfile(): creates a directory is a userfiles dir
                   16076: 
                   16077:   Args:
                   16078:    docuname: username or courseid of destination for the file
                   16079:    docudom: domain of user/course of destination for the file
                   16080:    dir: dir to create (including any subdirs under userfiles)
                   16081: 
                   16082: =item *
                   16083: 
                   16084: removeuserfile(): removes a file that exists in userfiles
                   16085: 
                   16086:   Args:
                   16087:    docuname: username or courseid of destination for the file
                   16088:    docudom: domain of user/course of destination for the file
                   16089:    fname: filname to delete (including any subdirs under userfiles)
                   16090: 
                   16091: =item *
                   16092: 
                   16093: removeuploadedurl(): convience function for removeuserfile()
                   16094: 
                   16095:   Args:
                   16096:    url:  a full /uploaded/... url to delete
                   16097: 
1.747     albertel 16098: =item * 
                   16099: 
                   16100: get_portfile_permissions():
                   16101:   Args:
                   16102:     domain: domain of user or course contain the portfolio files
                   16103:     user: name of user or num of course contain the portfolio files
                   16104:   Returns:
                   16105:     hashref of a dump of the proper file_permissions.db
                   16106:    
                   16107: 
                   16108: =item * 
                   16109: 
                   16110: get_access_controls():
                   16111: 
                   16112: Args:
                   16113:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16114:   group: (optional) the group you want the files associated with
                   16115:   file: (optional) the file you want access info on
                   16116: 
                   16117: Returns:
1.749     raeburn  16118:     a hash (keys are file names) of hashes containing
                   16119:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16120:         values are XML containing access control settings (see below) 
1.747     albertel 16121: 
                   16122: Internal notes:
                   16123: 
1.749     raeburn  16124:  access controls are stored in file_permissions.db as key=value pairs.
                   16125:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16126:         where scope -> public,guest,course,group,domains or users.
                   16127:               end -> UNIX time for end of access (0 -> no end date)
                   16128:               start -> UNIX time for start of access
                   16129: 
                   16130:     value -> XML description of access control
                   16131:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16132:             <start></start>
                   16133:             <end></end>
                   16134: 
                   16135:             <password></password>  for scope type = guest
                   16136: 
                   16137:             <domain></domain>     for scope type = course or group
                   16138:             <number></number>
                   16139:             <roles id="">
                   16140:              <role></role>
                   16141:              <access></access>
                   16142:              <section></section>
                   16143:              <group></group>
                   16144:             </roles>
                   16145: 
                   16146:             <dom></dom>         for scope type = domains
                   16147: 
                   16148:             <users>             for scope type = users
                   16149:              <user>
                   16150:               <uname></uname>
                   16151:               <udom></udom>
                   16152:              </user>
                   16153:             </users>
                   16154:            </scope> 
                   16155:               
                   16156:  Access data is also aggregated for each file in an additional key=value pair:
                   16157:  key -> path to file/file_name\0accesscontrol 
                   16158:  value -> reference to hash
                   16159:           hash contains key = value pairs
                   16160:           where key = uniqueID:scope_end_start
                   16161:                 value = UNIX time record was last updated
                   16162: 
                   16163:           Used to improve speed of look-ups of access controls for each file.  
                   16164:  
                   16165:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16166: 
1.1172.2.13  raeburn  16167: =item *
                   16168: 
1.749     raeburn  16169: modify_access_controls():
                   16170: 
                   16171: Modifies access controls for a portfolio file
                   16172: Args
                   16173: 1. file name
                   16174: 2. reference to hash of required changes,
                   16175: 3. domain
                   16176: 4. username
                   16177:   where domain,username are the domain of the portfolio owner 
                   16178:   (either a user or a course) 
                   16179: 
                   16180: Returns:
                   16181: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16182: 2. result of deletions ('ok' or 'error', with error message).
                   16183: 3. reference to hash of any new or updated access controls.
                   16184: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16185:    key = integer (inbound ID)
1.1172.2.13  raeburn  16186:    value = uniqueID
                   16187: 
                   16188: =item *
                   16189: 
                   16190: get_timebased_id():
                   16191: 
                   16192: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16193: course via the Course Editor (e.g., folders, composite pages,
                   16194: group bulletin boards).
                   16195: 
                   16196: Args: (first three required; six others optional)
                   16197: 
                   16198: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16199:    docssequence, or name of group
                   16200: 
                   16201: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16202:    e.g., num, boardids
                   16203: 
                   16204: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16205:    file will be named nohist_namespace.db
                   16206: 
                   16207: 4. cdom: domain of course; default is current course domain from %env
                   16208: 
                   16209: 5. cnum: course number; default is current course number from %env
                   16210: 
                   16211: 6. idtype: set to concat if an additional digit is to be appended to the
                   16212:    unix timestamp to form the suffix, if the plain timestamp is already
                   16213:    in use.  Default is to not do this, but simply increment the unix
                   16214:    timestamp by 1 until a unique key is obtained.
                   16215: 
                   16216: 7. who: holder of locking key; defaults to user:domain for user.
                   16217: 
                   16218: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16219:    retrying); default is 3.
                   16220: 
                   16221: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16222: 
                   16223: Returns:
                   16224: 
                   16225: 1. suffix obtained (numeric)
                   16226: 
                   16227: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16228: 
                   16229: 3. error: contains (localized) error message if an error occurred.
                   16230: 
1.747     albertel 16231: 
1.608     albertel 16232: =back
                   16233: 
1.243     albertel 16234: =head2 HTTP Helper Routines
                   16235: 
                   16236: =over 4
                   16237: 
1.191     harris41 16238: =item *
                   16239: 
                   16240: escape() : unpack non-word characters into CGI-compatible hex codes
                   16241: 
                   16242: =item *
                   16243: 
                   16244: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16245: 
1.243     albertel 16246: =back
                   16247: 
                   16248: =head1 PRIVATE SUBROUTINES
                   16249: 
                   16250: =head2 Underlying communication routines (Shouldn't call)
                   16251: 
                   16252: =over 4
                   16253: 
                   16254: =item *
                   16255: 
                   16256: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16257: 
                   16258: =item *
                   16259: 
                   16260: reply() : uses subreply to send a message to remote machine, logs all failures
                   16261: 
                   16262: =item *
                   16263: 
                   16264: critical() : passes a critical message to another server; if cannot
                   16265: get through then place message in connection buffer directory and
                   16266: returns con_delayed, if incapable of saving message, returns
                   16267: con_failed
                   16268: 
                   16269: =item *
                   16270: 
                   16271: reconlonc() : tries to reconnect lonc client processes.
                   16272: 
                   16273: =back
                   16274: 
                   16275: =head2 Resource Access Logging
                   16276: 
                   16277: =over 4
                   16278: 
                   16279: =item *
                   16280: 
                   16281: flushcourselogs() : flush (save) buffer logs and access logs
                   16282: 
                   16283: =item *
                   16284: 
                   16285: courselog($what) : save message for course in hash
                   16286: 
                   16287: =item *
                   16288: 
                   16289: courseacclog($what) : save message for course using &courselog().  Perform
                   16290: special processing for specific resource types (problems, exams, quizzes, etc).
                   16291: 
1.191     harris41 16292: =item *
                   16293: 
                   16294: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16295: as a PerlChildExitHandler
1.243     albertel 16296: 
                   16297: =back
                   16298: 
                   16299: =head2 Other
                   16300: 
                   16301: =over 4
                   16302: 
                   16303: =item *
                   16304: 
                   16305: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16306: 
                   16307: =back
                   16308: 
                   16309: =cut
1.877     foxr     16310: 

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