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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.144! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.143 2021/12/19 02:47:19 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 {
                   3170:     my ($host_name) = @_;
                   3171:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3172:     if ($host_name eq '') {
                   3173: 	$host_name = $ENV{'SERVER_NAME'};
                   3174:     }
                   3175:     return $protocol.$host_name;
                   3176: }
                   3177: 
1.942     foxr     3178: #
                   3179: #   Server side include.
                   3180: # Parameters:
                   3181: #  fn     Possibly encrypted resource name/id.
                   3182: #  form   Hash that describes how the rendering should be done
                   3183: #         and other things.
1.944     foxr     3184: # Returns:
1.950     raeburn  3185: #   Scalar context: The content of the response.
                   3186: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3187: #     
1.15      www      3188: sub ssi {
                   3189: 
1.944     foxr     3190:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3191:     my ($request,$response);
1.711     albertel 3192: 
                   3193:     $form{'no_update_last_known'}=1;
1.895     albertel 3194:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3195:     if (%form) {
1.782     albertel 3196:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3197:       $request->content(join('&',map {
                   3198:             my $name = escape($_);
                   3199:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3200:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3201:             : &escape($form{$_}) );
                   3202:         } keys(%form)));
1.23      www      3203:     } else {
1.782     albertel 3204:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3205:     }
                   3206: 
1.15      www      3207:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3208: 
1.1172.2.101  raeburn  3209:     if (($env{'request.course.id'}) &&
                   3210:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3211:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3212:         ($form{'grade_symb'} ne '') &&
                   3213:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3214:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3215:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3216:             my $ua=new LWP::UserAgent;
                   3217:             $ua->local_address('127.0.0.1');
                   3218:             $response = $ua->request($request);
                   3219:         } else {
                   3220:             {
                   3221:                 require LWP::Protocol::http;
                   3222:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3223:                 my $ua=new LWP::UserAgent;
                   3224:                 $response = $ua->request($request);
                   3225:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3226:             }
                   3227:         }
                   3228:     } else {
                   3229:         my $ua=new LWP::UserAgent;
                   3230:         $response = $ua->request($request);
                   3231:     }
1.944     foxr     3232:     if (wantarray) {
1.1172.2.3  raeburn  3233: 	return ($response->content, $response);
1.944     foxr     3234:     } else {
1.1172.2.3  raeburn  3235: 	return $response->content;
1.942     foxr     3236:     }
1.324     www      3237: }
                   3238: 
                   3239: sub externalssi {
                   3240:     my ($url)=@_;
                   3241:     my $ua=new LWP::UserAgent;
                   3242:     my $request=new HTTP::Request('GET',$url);
                   3243:     my $response=$ua->request($request);
1.954     raeburn  3244:     if (wantarray) {
                   3245:         return ($response->content, $response);
                   3246:     } else {
                   3247:         return $response->content;
                   3248:     }
1.15      www      3249: }
1.254     www      3250: 
1.1172.2.98  raeburn  3251: # If the local copy of a replicated resource is outdated, trigger a
                   3252: # connection from the homeserver to flush the delayed queue. If no update
                   3253: # happens, remove local copies of outdated resource (and corresponding
                   3254: # metadata file).
                   3255: 
                   3256: sub remove_stale_resfile {
                   3257:     my ($url) = @_;
                   3258:     my $removed;
                   3259:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3260:         my $audom = $1;
                   3261:         my $auname = $2;
                   3262:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3263:             my $homeserver = &homeserver($auname,$audom);
                   3264:             unless (($homeserver eq 'no_host') ||
                   3265:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3266:                 my $fname = &filelocation('',$url);
                   3267:                 if (-e $fname) {
                   3268:                     my $hostname = &hostname($homeserver);
                   3269:                     if ($hostname) {
1.1172.2.120  raeburn  3270:                         my $protocol = $protocol{$homeserver};
                   3271:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3272:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3273:                         my $ua=new LWP::UserAgent;
                   3274:                         $ua->timeout(5);
1.1172.2.98  raeburn  3275:                         my $request=new HTTP::Request('HEAD',$uri);
                   3276:                         my $response=$ua->request($request);
                   3277:                         if ($response->is_success()) {
                   3278:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3279:                             my $locmodtime = (stat($fname))[9];
                   3280:                             if ($locmodtime < $remmodtime) {
                   3281:                                 my $stale;
                   3282:                                 my $answer = &reply('pong',$homeserver);
                   3283:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3284:                                     sleep(0.2);
                   3285:                                     $locmodtime = (stat($fname))[9];
                   3286:                                     if ($locmodtime < $remmodtime) {
                   3287:                                         my $posstransfer = $fname.'.in.transfer';
                   3288:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3289:                                             $removed = 1;
                   3290:                                         } else {
                   3291:                                             $stale = 1;
                   3292:                                         }
                   3293:                                     } else {
                   3294:                                         $removed = 1;
                   3295:                                     }
                   3296:                                 } else {
                   3297:                                     $stale = 1;
                   3298:                                 }
                   3299:                                 if ($stale) {
1.1172.2.124  raeburn  3300:                                     if (unlink($fname)) {
                   3301:                                         if ($uri!~/\.meta$/) {
                   3302:                                             if (-e $fname.'.meta') {
                   3303:                                                 unlink($fname.'.meta');
                   3304:                                             }
                   3305:                                         }
                   3306:                                         my $unsubresult = &unsubscribe($fname);
                   3307:                                         unless ($unsubresult eq 'ok') {
                   3308:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3309:                                         }
                   3310:                                         $removed = 1;
1.1172.2.98  raeburn  3311:                                     }
                   3312:                                 }
                   3313:                             }
                   3314:                         }
                   3315:                     }
                   3316:                 }
                   3317:             }
                   3318:         }
                   3319:     }
                   3320:     return $removed;
                   3321: }
                   3322: 
1.492     albertel 3323: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3324: 
                   3325: sub allowuploaded {
                   3326:     my ($srcurl,$url)=@_;
                   3327:     $url=&clutter(&declutter($url));
                   3328:     my $dir=$url;
                   3329:     $dir=~s/\/[^\/]+$//;
                   3330:     my %httpref=();
                   3331:     my $httpurl=&hreflocation('',$url);
                   3332:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3333:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3334: }
1.477     raeburn  3335: 
1.1172.2.13  raeburn  3336: #
                   3337: # Determine if the current user should be able to edit a particular resource,
                   3338: # when viewing in course context.
                   3339: # (a) When viewing resource used to determine if "Edit" item is included in
                   3340: #     Functions.
                   3341: # (b) When displaying folder contents in course editor, used to determine if
                   3342: #     "Edit" link will be displayed alongside resource.
                   3343: #
                   3344: #  input: six args -- filename (decluttered), course number, course domain,
                   3345: #                   url, symb (if registered) and group (if this is a group
                   3346: #                   item -- e.g., bulletin board, group page etc.).
                   3347: #  output: array of five scalars --
                   3348: #          $cfile -- url for file editing if editable on current server
                   3349: #          $home -- homeserver of resource (i.e., for author if published,
                   3350: #                                           or course if uploaded.).
                   3351: #          $switchserver --  1 if server switch will be needed.
                   3352: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3353: #          $forceview -- 1 if icon/link should be to go to view mode
                   3354: #
                   3355: 
                   3356: sub can_edit_resource {
                   3357:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3358:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3359: #
                   3360: # For aboutme pages user can only edit his/her own.
                   3361: #
                   3362:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3363:         my ($sdom,$sname) = ($1,$2);
                   3364:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3365:             $home = $env{'user.home'};
                   3366:             $cfile = $resurl;
                   3367:             if ($env{'form.forceedit'}) {
                   3368:                 $forceview = 1;
                   3369:             } else {
                   3370:                 $forceedit = 1;
                   3371:             }
                   3372:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3373:         } else {
                   3374:             return;
                   3375:         }
                   3376:     }
                   3377: 
                   3378:     if ($env{'request.course.id'}) {
                   3379:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3380:         if ($group ne '') {
                   3381: # if this is a group homepage or group bulletin board, check group privs
                   3382:             my $allowed = 0;
                   3383:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3384:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3385:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3386:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3387:                     $allowed = 1;
                   3388:                 }
                   3389:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3390:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3391:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3392:                     $allowed = 1;
                   3393:                 }
                   3394:             }
                   3395:             if ($allowed) {
                   3396:                 $home=&homeserver($cnum,$cdom);
                   3397:                 if ($env{'form.forceedit'}) {
                   3398:                     $forceview = 1;
                   3399:                 } else {
                   3400:                     $forceedit = 1;
                   3401:                 }
                   3402:                 $cfile = $resurl;
                   3403:             } else {
                   3404:                 return;
                   3405:             }
                   3406:         } else {
1.1172.2.15  raeburn  3407:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3408:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3409:                     return;
                   3410:                 }
                   3411:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3412: #
                   3413: # No edit allowed where CC has switched to student role.
                   3414: #
                   3415:                 return;
                   3416:             }
                   3417:         }
                   3418:     }
                   3419: 
                   3420:     if ($file ne '') {
                   3421:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3422:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3423:                 $uploaded = 1;
                   3424:                 $incourse = 1;
                   3425:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3426:                     $cfile = &hreflocation('',$file);
                   3427:                     if ($env{'form.forceedit'}) {
                   3428:                         $forceview = 1;
                   3429:                     } else {
                   3430:                         $forceedit = 1;
                   3431:                     }
                   3432:                 }
                   3433:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3434:                 $incourse = 1;
                   3435:                 if ($env{'form.forceedit'}) {
                   3436:                     $forceview = 1;
                   3437:                 } else {
                   3438:                     $forceedit = 1;
                   3439:                 }
                   3440:                 $cfile = $resurl;
                   3441:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3442:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3443:                     $incourse = 1;
                   3444:                     if ($env{'form.forceedit'}) {
                   3445:                         $forceview = 1;
                   3446:                     } else {
                   3447:                         $forceedit = 1;
                   3448:                     }
                   3449:                     $cfile = $resurl;
                   3450:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3451:                     $incourse = 1;
                   3452:                     $cfile = $resurl.'/smpedit';
                   3453:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3454:                     $incourse = 1;
                   3455:                     if ($env{'form.forceedit'}) {
                   3456:                         $forceview = 1;
                   3457:                     } else {
                   3458:                         $forceedit = 1;
                   3459:                     }
                   3460:                     $cfile = $resurl;
1.1172.2.122  raeburn  3461:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3462:                     my ($map,$id,$res) = &decode_symb($symb);
                   3463:                     if ($map =~ /\.page$/) {
                   3464:                         $incourse = 1;
                   3465:                         if ($env{'form.forceedit'}) {
                   3466:                             $forceview = 1;
                   3467:                             $cfile = $map;
                   3468:                         } else {
                   3469:                             $forceedit = 1;
                   3470:                             $cfile =  '/adm/wrapper'.$resurl;
                   3471:                         }
                   3472:                     }
1.1172.2.15  raeburn  3473:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3474:                     $incourse = 1;
                   3475:                     if ($env{'form.forceedit'}) {
                   3476:                         $forceview = 1;
                   3477:                     } else {
                   3478:                         $forceedit = 1;
                   3479:                     }
                   3480:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3481:                 }
                   3482:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3483:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3484:                 if (&is_on_map($template)) {
                   3485:                     $incourse = 1;
                   3486:                     $forceview = 1;
                   3487:                     $cfile = $template;
                   3488:                 }
                   3489:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3490:                 $incourse = 1;
                   3491:                 if ($env{'form.forceedit'}) {
                   3492:                     $forceview = 1;
                   3493:                 } else {
                   3494:                     $forceedit = 1;
                   3495:                 }
                   3496:                 $cfile = $resurl;
1.1172.2.13  raeburn  3497:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3498:                 $incourse = 1;
                   3499:                 $forceview = 1;
                   3500:                 if ($symb) {
                   3501:                     my ($map,$id,$res)=&decode_symb($symb);
                   3502:                     $env{'request.symb'} = $symb;
                   3503:                     $cfile = &clutter($res);
                   3504:                 } else {
                   3505:                     $cfile = $env{'form.suppurl'};
                   3506:                     $cfile =~ s{^http://}{};
                   3507:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3508:                 }
1.1172.2.31  raeburn  3509:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3510:                 if ($env{'form.forceedit'}) {
                   3511:                     $forceview = 1;
                   3512:                 } else {
                   3513:                     $forceedit = 1;
                   3514:                 }
                   3515:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3516:             }
                   3517:         }
                   3518:         if ($uploaded || $incourse) {
                   3519:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3520:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3521:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3522:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3523:             # Check that the user has permission to edit this resource
                   3524:             my $setpriv = 1;
                   3525:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3526:             if (defined($cfudom)) {
                   3527:                 $home=&homeserver($cfuname,$cfudom);
                   3528:                 $cfile=$file;
                   3529:             }
                   3530:         }
                   3531:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3532:             (($home ne '') && ($home ne 'no_host'))) {
                   3533:             my @ids=&current_machine_ids();
                   3534:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3535:                 $switchserver=1;
                   3536:             }
                   3537:         }
                   3538:     }
                   3539:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3540: }
                   3541: 
                   3542: sub is_course_upload {
                   3543:     my ($file,$cnum,$cdom) = @_;
                   3544:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3545:     $uploadpath =~ s{^\/}{};
                   3546:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3547:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3548:         return 1;
                   3549:     }
                   3550:     return;
                   3551: }
                   3552: 
                   3553: sub in_course {
                   3554:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3555:     if ($hideprivileged) {
                   3556:         my $skipuser;
1.1172.2.23  raeburn  3557:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3558:         my @possdoms = ($cdom);
                   3559:         if ($coursehash{'checkforpriv'}) {
                   3560:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3561:         }
                   3562:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3563:             $skipuser = 1;
                   3564:             if ($coursehash{'nothideprivileged'}) {
                   3565:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3566:                     my $user;
                   3567:                     if ($item =~ /:/) {
                   3568:                         $user = $item;
                   3569:                     } else {
                   3570:                         $user = join(':',split(/[\@]/,$item));
                   3571:                     }
                   3572:                     if ($user eq $uname.':'.$udom) {
                   3573:                         undef($skipuser);
                   3574:                         last;
                   3575:                     }
                   3576:                 }
                   3577:             }
                   3578:             if ($skipuser) {
                   3579:                 return 0;
                   3580:             }
                   3581:         }
                   3582:     }
                   3583:     $type ||= 'any';
                   3584:     if (!defined($cdom) || !defined($cnum)) {
                   3585:         my $cid  = $env{'request.course.id'};
                   3586:         $cdom = $env{'course.'.$cid.'.domain'};
                   3587:         $cnum = $env{'course.'.$cid.'.num'};
                   3588:     }
                   3589:     my $typesref;
                   3590:     if (($type eq 'any') || ($type eq 'all')) {
                   3591:         $typesref = ['active','previous','future'];
                   3592:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3593:         $typesref = [$type];
                   3594:     }
                   3595:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3596:                               $typesref,undef,[$cdom]);
                   3597:     my ($tmp) = keys(%roles);
                   3598:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3599:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3600:     if (@course_roles > 0) {
                   3601:         return 1;
                   3602:     }
                   3603:     return 0;
                   3604: }
                   3605: 
1.478     albertel 3606: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3607: # input: action, courseID, current domain, intended
1.637     raeburn  3608: #        path to file, source of file, instruction to parse file for objects,
                   3609: #        ref to hash for embedded objects,
                   3610: #        ref to hash for codebase of java objects.
1.1095    raeburn  3611: #        reference to scalar to accommodate mime type determined
                   3612: #          from File::MMagic if $parser = parse.
1.637     raeburn  3613: #
1.485     raeburn  3614: # output: url to file (if action was uploaddoc), 
                   3615: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3616: #
1.478     albertel 3617: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3618: # course.
1.477     raeburn  3619: #
1.478     albertel 3620: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3621: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3622: #          course's home server.
1.477     raeburn  3623: #
1.478     albertel 3624: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3625: #          be copied from $source (current location) to 
                   3626: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3627: #         and will then be copied to
                   3628: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3629: #         course's home server.
1.485     raeburn  3630: #
1.481     raeburn  3631: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3632: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3633: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3634: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3635: #         in course's home server.
1.637     raeburn  3636: #
1.477     raeburn  3637: 
                   3638: sub process_coursefile {
1.1095    raeburn  3639:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3640:         $mimetype)=@_;
1.477     raeburn  3641:     my $fetchresult;
1.638     albertel 3642:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3643:     if ($action eq 'propagate') {
1.638     albertel 3644:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3645: 			     $home);
1.481     raeburn  3646:     } else {
1.477     raeburn  3647:         my $fpath = '';
                   3648:         my $fname = $file;
1.478     albertel 3649:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3650:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3651:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3652:         if ($action eq 'copy') {
                   3653:             if ($source eq '') {
                   3654:                 $fetchresult = 'no source file';
                   3655:                 return $fetchresult;
                   3656:             } else {
                   3657:                 my $destination = $filepath.'/'.$fname;
                   3658:                 rename($source,$destination);
                   3659:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3660:                                  $home);
1.481     raeburn  3661:             }
                   3662:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3663:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3664:             print $fh $env{'form.'.$source};
1.481     raeburn  3665:             close($fh);
1.637     raeburn  3666:             if ($parser eq 'parse') {
1.1024    raeburn  3667:                 my $mm = new File::MMagic;
1.1095    raeburn  3668:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3669:                 if ($type eq 'text/html') {
1.1024    raeburn  3670:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3671:                     unless ($parse_result eq 'ok') {
                   3672:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3673:                     }
1.637     raeburn  3674:                 }
1.1095    raeburn  3675:                 if (ref($mimetype)) {
                   3676:                     $$mimetype = $type;
                   3677:                 } 
1.637     raeburn  3678:             }
1.477     raeburn  3679:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3680:                                  $home);
1.481     raeburn  3681:             if ($fetchresult eq 'ok') {
                   3682:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3683:             } else {
                   3684:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3685:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3686:                 return '/adm/notfound.html';
                   3687:             }
1.477     raeburn  3688:         }
                   3689:     }
1.485     raeburn  3690:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3691:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3692:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3693:     }
                   3694:     return $fetchresult;
                   3695: }
                   3696: 
1.637     raeburn  3697: sub build_filepath {
                   3698:     my ($fpath) = @_;
                   3699:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3700:     unless ($fpath eq '') {
                   3701:         my @parts=split('/',$fpath);
                   3702:         foreach my $part (@parts) {
                   3703:             $filepath.= '/'.$part;
                   3704:             if ((-e $filepath)!=1) {
                   3705:                 mkdir($filepath,0777);
                   3706:             }
                   3707:         }
                   3708:     }
                   3709:     return $filepath;
                   3710: }
                   3711: 
                   3712: sub store_edited_file {
1.638     albertel 3713:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3714:     my $file = $primary_url;
                   3715:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3716:     my $fpath = '';
                   3717:     my $fname = $file;
                   3718:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3719:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3720:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3721:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3722:     print $fh $content;
                   3723:     close($fh);
1.638     albertel 3724:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3725:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3726: 			  $home);
1.637     raeburn  3727:     if ($$fetchresult eq 'ok') {
                   3728:         return '/uploaded/'.$fpath.'/'.$fname;
                   3729:     } else {
1.638     albertel 3730:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3731: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3732:         return '/adm/notfound.html';
                   3733:     }
                   3734: }
                   3735: 
1.531     albertel 3736: sub clean_filename {
1.831     albertel 3737:     my ($fname,$args)=@_;
1.315     www      3738: # Replace Windows backslashes by forward slashes
1.257     www      3739:     $fname=~s/\\/\//g;
1.831     albertel 3740:     if (!$args->{'keep_path'}) {
                   3741:         # Get rid of everything but the actual filename
                   3742: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3743:     }
1.315     www      3744: # Replace spaces by underscores
                   3745:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3746: # Transliterate non-ascii text to ascii
                   3747:     my $lang = &Apache::lonlocal::current_language();
                   3748:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3749: # Replace all other weird characters by nothing
1.831     albertel 3750:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3751: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3752: # numbers
                   3753:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3754: # Replace three or more adjacent underscores with one for consistency
                   3755: # with loncfile::filename_check() so complete url can be extracted by
                   3756: # lonnet::decode_symb()
                   3757:     $fname=~s/_{3,}/_/g;
1.531     albertel 3758:     return $fname;
                   3759: }
1.1172.2.110  raeburn  3760: 
1.1051    raeburn  3761: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3762: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3763: # image with the same aspect ratio as the original, but with dimensions which do 
                   3764: # not exceed $resizewidth and $resizeheight.
                   3765:  
1.984     neumanie 3766: sub resizeImage {
1.1051    raeburn  3767:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3768:     my $ima = Image::Magick->new;
                   3769:     my $resized;
                   3770:     if (-e $img_path) {
                   3771:         $ima->Read($img_path);
                   3772:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3773:             my $width = $ima->Get('width');
                   3774:             my $height = $ima->Get('height');
                   3775:             if ($width > $resizewidth) {
                   3776: 	        my $factor = $width/$resizewidth;
                   3777:                 my $newheight = $height/$factor;
                   3778:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3779:                 $resized = 1;
                   3780:             }
                   3781:         }
                   3782:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3783:             my $width = $ima->Get('width');
                   3784:             my $height = $ima->Get('height');
                   3785:             if ($height > $resizeheight) {
                   3786:                 my $factor = $height/$resizeheight;
                   3787:                 my $newwidth = $width/$factor;
                   3788:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3789:                 $resized = 1;
                   3790:             }
                   3791:         }
                   3792:         if ($resized) {
                   3793:             $ima->Write($img_path);
                   3794:         }
                   3795:     }
                   3796:     return;
1.977     amueller 3797: }
                   3798: 
1.608     albertel 3799: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3800: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3801: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3802: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3803: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3804: #                   if 'coursedoc': upload to the current course
                   3805: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3806: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3807: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3808: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3809: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3810: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3811: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3812: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3813: #        $allfiles - reference to hash for embedded objects
                   3814: #        $codebase - reference to hash for codebase of java objects
                   3815: #        $desuname - username for permanent storage of uploaded file
                   3816: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3817: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3818: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3819: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3820: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3821: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3822: #                    from File::MMagic.
1.858     raeburn  3823: # 
1.686     albertel 3824: # output: url of file in userspace, or error: <message> 
                   3825: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3826: 
1.531     albertel 3827: sub userfileupload {
1.1090    raeburn  3828:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3829:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3830:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3831:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3832:     $fname=&clean_filename($fname);
1.1090    raeburn  3833:     # See if there is anything left
1.257     www      3834:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3835:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3836:     if ($fname =~ /^\./) {
                   3837:         my ($s,$usec) = &gettimeofday();
                   3838:         while (length($usec) < 6) {
                   3839:             $usec = '0'.$usec;
                   3840:         }
                   3841:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3842:     }
1.1090    raeburn  3843:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3844:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3845:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3846:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3847:         my $now = time;
1.1090    raeburn  3848:         my $filepath;
1.1095    raeburn  3849:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3850:              $filepath = 'tmp/helprequests/'.$now;
                   3851:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3852:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3853:                          '_'.$env{'user.domain'}.'/pending';
                   3854:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3855:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3856:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3857:                 $docudom = $destudom;
                   3858:             } else {
                   3859:                 $docudom = $env{'user.domain'};
                   3860:             }
1.1172.2.96  raeburn  3861:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3862:                 $docuname = $destuname;
                   3863:             } else {
                   3864:                 $docuname = $env{'user.name'};
                   3865:             }
                   3866:             if (exists($env{'form.group'})) {
                   3867:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3868:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3869:             }
                   3870:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3871:             if ($context eq 'canceloverwrite') {
                   3872:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3873:                 if (-e  $tempfile) {
                   3874:                     my @info = stat($tempfile);
                   3875:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3876:                         unlink($tempfile);
                   3877:                     }
                   3878:                 }
                   3879:                 return;
1.523     raeburn  3880:             }
                   3881:         }
1.1090    raeburn  3882:         # Create the directory if not present
1.741     raeburn  3883:         my @parts=split(/\//,$filepath);
                   3884:         my $fullpath = $perlvar{'lonDaemons'};
                   3885:         for (my $i=0;$i<@parts;$i++) {
                   3886:             $fullpath .= '/'.$parts[$i];
                   3887:             if ((-e $fullpath)!=1) {
                   3888:                 mkdir($fullpath,0777);
                   3889:             }
                   3890:         }
1.1172.2.96  raeburn  3891:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3892:         print $fh $env{'form.'.$formname};
                   3893:         close($fh);
1.1090    raeburn  3894:         if ($context eq 'existingfile') {
                   3895:             my @info = stat($fullpath.'/'.$fname);
                   3896:             return ($fullpath.'/'.$fname,$info[9]);
                   3897:         } else {
                   3898:             return $fullpath.'/'.$fname;
                   3899:         }
1.523     raeburn  3900:     }
1.995     raeburn  3901:     if ($subdir eq 'scantron') {
                   3902:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3903:     } else {
1.995     raeburn  3904:         $fname="$subdir/$fname";
                   3905:     }
1.1090    raeburn  3906:     if ($context eq 'coursedoc') {
1.638     albertel 3907: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3908: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3909:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3910:             return &finishuserfileupload($docuname,$docudom,
                   3911: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3912: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3913:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3914:         } else {
1.1172.2.21  raeburn  3915:             if ($env{'form.folder'}) {
                   3916:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3917:             }
1.638     albertel 3918:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3919: 				       $fname,$formname,$parser,
1.1095    raeburn  3920: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3921:         }
1.719     banghart 3922:     } elsif (defined($destuname)) {
                   3923:         my $docuname=$destuname;
                   3924:         my $docudom=$destudom;
1.860     raeburn  3925: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3926: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3927:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3928:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3929:     } else {
1.638     albertel 3930:         my $docuname=$env{'user.name'};
                   3931:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3932:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3933:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3934:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3935:         }
1.860     raeburn  3936: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3937: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3938:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3939:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3940:     }
1.271     www      3941: }
                   3942: 
                   3943: sub finishuserfileupload {
1.860     raeburn  3944:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3945:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3946:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3947:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3948:   
1.860     raeburn  3949:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3950:     $file=$fname;
                   3951:     if ($fname=~m|/|) {
                   3952:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3953: 	$path.=$fnamepath.'/';
                   3954:     }
1.259     www      3955:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3956:     my $count;
                   3957:     for ($count=4;$count<=$#parts;$count++) {
                   3958:         $filepath.="/$parts[$count]";
                   3959:         if ((-e $filepath)!=1) {
                   3960: 	    mkdir($filepath,0777);
                   3961:         }
                   3962:     }
1.984     neumanie 3963: 
1.258     www      3964: # Save the file
                   3965:     {
1.1172.2.96  raeburn  3966: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3967: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3968: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3969: 	    return '/adm/notfound.html';
                   3970: 	}
1.1090    raeburn  3971:         if ($context eq 'overwrite') {
1.1117    foxr     3972:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3973:             my $target = $filepath.'/'.$file;
                   3974:             if (-e $source) {
                   3975:                 my @info = stat($source);
                   3976:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3977:                     unless (&File::Copy::move($source,$target)) {
                   3978:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3979:                         return "Moving from $source failed";
                   3980:                     }
                   3981:                 } else {
                   3982:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3983:                 }
                   3984:             } else {
                   3985:                 return "Temporary file: $source missing";
                   3986:             }
                   3987:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3988: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3989: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3990: 	    return '/adm/notfound.html';
                   3991: 	}
1.570     albertel 3992: 	close(FH);
1.1051    raeburn  3993:         if ($resizewidth && $resizeheight) {
                   3994:             my $mm = new File::MMagic;
                   3995:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3996:             if ($mime_type =~ m{^image/}) {
                   3997: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3998:             }  
1.977     amueller 3999: 	}
1.258     www      4000:     }
1.1152    raeburn  4001:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4002:         if (ref($mimetype)) {
                   4003:             if ($$mimetype eq '') {
                   4004:                 my $mm = new File::MMagic;
                   4005:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4006:                 $$mimetype = $type;
                   4007:             }
                   4008:         }
                   4009:     }
1.1172.2.109  raeburn  4010:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4011:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4012:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4013:                                                        $allfiles,$codebase);
                   4014:             unless ($parse_result eq 'ok') {
                   4015:                 &logthis('Failed to parse '.$filepath.$file.
                   4016: 	   	         ' for embedded media: '.$parse_result); 
                   4017:             }
1.637     raeburn  4018:         }
1.1172.2.109  raeburn  4019:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4020:         my $format = $env{'form.scantron_format'};
                   4021:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4022:     }
1.860     raeburn  4023:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4024:         my $input = $filepath.'/'.$file;
                   4025:         my $output = $filepath.'/'.'tn-'.$file;
                   4026:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4027:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4028:         system({$args[0]} @args);
1.860     raeburn  4029:         if (-e $filepath.'/'.'tn-'.$file) {
                   4030:             $fetchthumb  = 1; 
                   4031:         }
                   4032:     }
1.858     raeburn  4033:  
1.259     www      4034: # Notify homeserver to grep it
                   4035: #
1.984     neumanie 4036:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4037:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4038:     if ($fetchresult eq 'ok') {
1.860     raeburn  4039:         if ($fetchthumb) {
                   4040:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4041:             if ($thumbresult ne 'ok') {
                   4042:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4043:                          $docuhome.': '.$thumbresult);
                   4044:             }
                   4045:         }
1.259     www      4046: #
1.258     www      4047: # Return the URL to it
1.494     albertel 4048:         return '/uploaded/'.$path.$file;
1.263     www      4049:     } else {
1.494     albertel 4050:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4051: 		 ': '.$fetchresult);
1.263     www      4052:         return '/adm/notfound.html';
1.858     raeburn  4053:     }
1.493     albertel 4054: }
                   4055: 
1.637     raeburn  4056: sub extract_embedded_items {
1.961     raeburn  4057:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4058:     my @state = ();
1.1164    raeburn  4059:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4060:     my %javafiles = (
                   4061:                       codebase => '',
                   4062:                       code => '',
                   4063:                       archive => ''
                   4064:                     );
                   4065:     my %mediafiles = (
                   4066:                       src => '',
                   4067:                       movie => '',
                   4068:                      );
1.648     raeburn  4069:     my $p;
                   4070:     if ($content) {
                   4071:         $p = HTML::LCParser->new($content);
                   4072:     } else {
1.961     raeburn  4073:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4074:     }
1.641     albertel 4075:     while (my $t=$p->get_token()) {
1.640     albertel 4076: 	if ($t->[0] eq 'S') {
                   4077: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4078: 	    push(@state, $tagname);
1.648     raeburn  4079:             if (lc($tagname) eq 'allow') {
                   4080:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4081:             }
1.640     albertel 4082: 	    if (lc($tagname) eq 'img') {
                   4083: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4084: 	    }
1.886     albertel 4085: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4086:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4087: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4088:                 }
1.886     albertel 4089: 	    }
1.645     raeburn  4090:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4091:                 my $src;
1.645     raeburn  4092:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4093:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4094:                 } else {
1.1164    raeburn  4095:                     if ($attr->{'src'} ne '') {
                   4096:                         $src = $attr->{'src'};
                   4097:                         &add_filetype($allfiles,$src,'src');
                   4098:                     }
                   4099:                 }
                   4100:                 my $text = $p->get_trimmed_text();
                   4101:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4102:                     my @swfargs = split(/,/,$1);
                   4103:                     foreach my $item (@swfargs) {
                   4104:                         $item =~ s/["']//g;
                   4105:                         $item =~ s/^\s+//;
                   4106:                         $item =~ s/\s+$//;
                   4107:                     }
                   4108:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4109:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4110:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4111:                         } else {
                   4112:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4113:                         }
                   4114:                     }
1.645     raeburn  4115:                 }
                   4116:             }
                   4117:             if (lc($tagname) eq 'link') {
                   4118:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4119:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4120:                 }
                   4121:             }
1.640     albertel 4122: 	    if (lc($tagname) eq 'object' ||
                   4123: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4124: 		foreach my $item (keys(%javafiles)) {
                   4125: 		    $javafiles{$item} = '';
                   4126: 		}
1.1164    raeburn  4127:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4128:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4129:                 }
1.640     albertel 4130: 	    }
                   4131: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4132: 		my $name = lc($attr->{'name'});
                   4133: 		foreach my $item (keys(%javafiles)) {
                   4134: 		    if ($name eq $item) {
                   4135: 			$javafiles{$item} = $attr->{'value'};
                   4136: 			last;
                   4137: 		    }
                   4138: 		}
1.1164    raeburn  4139:                 my $pathfrom;
1.640     albertel 4140: 		foreach my $item (keys(%mediafiles)) {
                   4141: 		    if ($name eq $item) {
1.1164    raeburn  4142:                         $pathfrom = $attr->{'value'};
                   4143:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4144: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4145: 			last;
                   4146: 		    }
                   4147: 		}
1.1164    raeburn  4148:                 if ($name eq 'flashvars') {
                   4149:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4150:                 }
                   4151:                 if ($pathfrom ne '') {
                   4152:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4153:                                          $pathfrom);
                   4154:                 }
1.640     albertel 4155: 	    }
                   4156: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4157: 		foreach my $item (keys(%javafiles)) {
                   4158: 		    if ($attr->{$item}) {
                   4159: 			$javafiles{$item} = $attr->{$item};
                   4160: 			last;
                   4161: 		    }
                   4162: 		}
                   4163: 		foreach my $item (keys(%mediafiles)) {
                   4164: 		    if ($attr->{$item}) {
                   4165: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4166: 			last;
                   4167: 		    }
                   4168: 		}
1.1164    raeburn  4169:                 if (lc($tagname) eq 'embed') {
                   4170:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4171:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4172:                                              $attr->{'src'});
                   4173:                     }
                   4174:                 }
1.640     albertel 4175: 	    }
1.1172.2.35  raeburn  4176:             if (lc($tagname) eq 'iframe') {
                   4177:                 my $src = $attr->{'src'} ;
                   4178:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4179:                     &add_filetype($allfiles,$src,'src');
                   4180:                 } elsif ($src =~ m{^/}) {
                   4181:                     if ($env{'request.course.id'}) {
                   4182:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4183:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4184:                         my $url = &hreflocation('',$fullpath);
                   4185:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4186:                             my $relpath = $1;
                   4187:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4188:                                 &add_filetype($allfiles,$1,'src');
                   4189:                             }
                   4190:                         }
                   4191:                     }
                   4192:                 }
                   4193:             }
1.1164    raeburn  4194:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4195:                 pop(@state);
1.1164    raeburn  4196:             }
1.640     albertel 4197: 	} elsif ($t->[0] eq 'E') {
                   4198: 	    my ($tagname) = ($t->[1]);
                   4199: 	    if ($javafiles{'codebase'} ne '') {
                   4200: 		$javafiles{'codebase'} .= '/';
                   4201: 	    }  
                   4202: 	    if (lc($tagname) eq 'applet' ||
                   4203: 		lc($tagname) eq 'object' ||
                   4204: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4205: 		) {
                   4206: 		foreach my $item (keys(%javafiles)) {
                   4207: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4208: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4209: 			&add_filetype($allfiles,$file,$item);
                   4210: 		    }
                   4211: 		}
                   4212: 	    } 
                   4213: 	    pop @state;
                   4214: 	}
                   4215:     }
1.1164    raeburn  4216:     foreach my $id (sort(keys(%flashvars))) {
                   4217:         if ($shockwave{$id} ne '') {
                   4218:             my @pairs = split(/\&/,$flashvars{$id});
                   4219:             foreach my $pair (@pairs) {
                   4220:                 my ($key,$value) = split(/\=/,$pair);
                   4221:                 if ($key eq 'thumb') {
                   4222:                     &add_filetype($allfiles,$value,$key);
                   4223:                 } elsif ($key eq 'content') {
                   4224:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4225:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4226:                     if ($ext ne '') {
                   4227:                         &add_filetype($allfiles,$path.$value,$ext);
                   4228:                     }
                   4229:                 }
                   4230:             }
                   4231:         }
                   4232:     }
1.637     raeburn  4233:     return 'ok';
                   4234: }
                   4235: 
1.639     albertel 4236: sub add_filetype {
                   4237:     my ($allfiles,$file,$type)=@_;
                   4238:     if (exists($allfiles->{$file})) {
                   4239: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4240: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4241: 	}
                   4242:     } else {
                   4243: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4244:     }
                   4245: }
                   4246: 
1.1164    raeburn  4247: sub embedded_dependency {
                   4248:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4249:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4250:         if (($identifier ne '') &&
                   4251:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4252:             ($pathfrom ne '')) {
                   4253:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4254:             foreach my $dep (@{$related->{$identifier}}) {
                   4255:                 &add_filetype($allfiles,$path.$dep,'object');
                   4256:             }
                   4257:         }
                   4258:     }
                   4259:     return;
                   4260: }
                   4261: 
1.1172.2.109  raeburn  4262: sub bubblesheet_converter {
                   4263:     my ($cdom,$fullpath,$config,$format) = @_;
                   4264:     if ((&domain($cdom) ne '') &&
                   4265:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4266:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4267:         my (%csvcols,%csvoptions);
                   4268:         if (ref($config->{'fields'}) eq 'HASH') {
                   4269:             %csvcols = %{$config->{'fields'}};
                   4270:         }
                   4271:         if (ref($config->{'options'}) eq 'HASH') {
                   4272:             %csvoptions = %{$config->{'options'}};
                   4273:         }
                   4274:         my %csvbynum = reverse(%csvcols);
                   4275:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4276:         if (keys(%scantronconf)) {
                   4277:             my %bynum = (
                   4278:                           $scantronconf{CODEstart} => 'CODEstart',
                   4279:                           $scantronconf{IDstart}   => 'IDstart',
                   4280:                           $scantronconf{PaperID}   => 'PaperID',
                   4281:                           $scantronconf{FirstName} => 'FirstName',
                   4282:                           $scantronconf{LastName}  => 'LastName',
                   4283:                           $scantronconf{Qstart}    => 'Qstart',
                   4284:                         );
                   4285:             my @ordered;
                   4286:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4287:                 push(@ordered,$bynum{$item});
                   4288:             }
                   4289:             my %mapstart = (
                   4290:                               CODEstart => 'CODE',
                   4291:                               IDstart   => 'ID',
                   4292:                               PaperID   => 'PaperID',
                   4293:                               FirstName => 'FirstName',
                   4294:                               LastName  => 'LastName',
                   4295:                               Qstart    => 'FirstQuestion',
                   4296:                            );
                   4297:             my %maplength = (
                   4298:                               CODEstart => 'CODElength',
                   4299:                               IDstart   => 'IDlength',
                   4300:                               PaperID   => 'PaperIDlength',
                   4301:                               FirstName => 'FirstNamelength',
                   4302:                               LastName  => 'LastNamelength',
                   4303:             );
                   4304:             if (open(my $fh,'<',$fullpath)) {
                   4305:                 my $output;
                   4306:                 my %lettdig = &letter_to_digits();
                   4307:                 my %diglett = reverse(%lettdig);
                   4308:                 my $numletts = scalar(keys(%lettdig));
                   4309:                 my $num = 0;
                   4310:                 while (my $line=<$fh>) {
                   4311:                     $num ++;
                   4312:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4313:                     $line =~ s{[\r\n]+$}{};
                   4314:                     my %found;
1.1172.2.143  raeburn  4315:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4316:                     my ($qstart,$record);
                   4317:                     for (my $i=0; $i<@values; $i++) {
                   4318:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4319:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4320:                             if ($values[$i] eq '') {
                   4321:                                 $values[$i] = $scantronconf{'Qoff'};
                   4322:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4323:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4324:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4325:                                 }
                   4326:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4327:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4328:                                     $values[$i] = $diglett{$values[$i]};
                   4329:                                 }
                   4330:                             } else {
                   4331:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4332:                                     my $digit;
                   4333:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4334:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4335:                                         if ($values[$i] eq 'J') {
                   4336:                                             $digit += $numletts;
                   4337:                                         }
                   4338:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4339:                                         $digit = $values[$i]-1;
                   4340:                                         if ($values[$i] eq '0') {
                   4341:                                             $digit += $numletts;
                   4342:                                         }
                   4343:                                     }
                   4344:                                     my $qval='';
                   4345:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4346:                                         if ($j == $digit) {
                   4347:                                             $qval .= $scantronconf{'Qon'};
                   4348:                                         } else {
                   4349:                                             $qval .= $scantronconf{'Qoff'};
                   4350:                                         }
                   4351:                                     }
                   4352:                                     $values[$i] = $qval;
                   4353:                                 }
                   4354:                             }
                   4355:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4356:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4357:                             }
                   4358:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4359:                             if ($numblank > 0) {
                   4360:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4361:                             }
                   4362:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4363:                                 $qstart = $i;
                   4364:                                 $found{$csvbynum{$i}} = $values[$i];
                   4365:                             } else {
                   4366:                                 $found{'FirstQuestion'} .= $values[$i];
                   4367:                             }
                   4368:                         } elsif (exists($csvbynum{$i})) {
                   4369:                             if ($csvoptions{'rem'}) {
                   4370:                                 $values[$i] =~ s/^\s+//;
                   4371:                             }
                   4372:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4373:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4374:                                     $values[$i] = '0'.$values[$i];
                   4375:                                 }
                   4376:                             }
                   4377:                             $found{$csvbynum{$i}} = $values[$i];
                   4378:                         }
                   4379:                     }
                   4380:                     foreach my $item (@ordered) {
                   4381:                         my $currlength = 1+length($record);
                   4382:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4383:                         if ($numspaces > 0) {
                   4384:                             $record .= (' ' x $numspaces);
                   4385:                         }
                   4386:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4387:                             unless ($item eq 'Qstart') {
                   4388:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4389:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4390:                                 }
                   4391:                             }
                   4392:                             $record .= $found{$mapstart{$item}};
                   4393:                         }
                   4394:                     }
                   4395:                     $output .= "$record\n";
                   4396:                 }
                   4397:                 close($fh);
                   4398:                 if ($output) {
                   4399:                     if (open(my $fh,'>',$fullpath)) {
                   4400:                         print $fh $output;
                   4401:                         close($fh);
                   4402:                     }
                   4403:                 }
                   4404:             }
                   4405:         }
                   4406:         return;
                   4407:     }
                   4408: }
                   4409: 
                   4410: sub letter_to_digits {
                   4411:     my %lettdig = (
                   4412:                     A => 1,
                   4413:                     B => 2,
                   4414:                     C => 3,
                   4415:                     D => 4,
                   4416:                     E => 5,
                   4417:                     F => 6,
                   4418:                     G => 7,
                   4419:                     H => 8,
                   4420:                     I => 9,
                   4421:                     J => 0,
                   4422:                   );
                   4423:     return %lettdig;
                   4424: }
                   4425: 
                   4426: sub get_scantron_config {
                   4427:     my ($which,$cdom) = @_;
                   4428:     my @lines = &get_scantronformat_file($cdom);
                   4429:     my %config;
                   4430:     #FIXME probably should move to XML it has already gotten a bit much now
                   4431:     foreach my $line (@lines) {
                   4432:         my ($name,$descrip)=split(/:/,$line);
                   4433:         if ($name ne $which ) { next; }
                   4434:         chomp($line);
                   4435:         my @config=split(/:/,$line);
                   4436:         $config{'name'}=$config[0];
                   4437:         $config{'description'}=$config[1];
                   4438:         $config{'CODElocation'}=$config[2];
                   4439:         $config{'CODEstart'}=$config[3];
                   4440:         $config{'CODElength'}=$config[4];
                   4441:         $config{'IDstart'}=$config[5];
                   4442:         $config{'IDlength'}=$config[6];
                   4443:         $config{'Qstart'}=$config[7];
                   4444:         $config{'Qlength'}=$config[8];
                   4445:         $config{'Qoff'}=$config[9];
                   4446:         $config{'Qon'}=$config[10];
                   4447:         $config{'PaperID'}=$config[11];
                   4448:         $config{'PaperIDlength'}=$config[12];
                   4449:         $config{'FirstName'}=$config[13];
                   4450:         $config{'FirstNamelength'}=$config[14];
                   4451:         $config{'LastName'}=$config[15];
                   4452:         $config{'LastNamelength'}=$config[16];
                   4453:         $config{'BubblesPerRow'}=$config[17];
                   4454:         last;
                   4455:     }
                   4456:     return %config;
                   4457: }
                   4458: 
                   4459: sub get_scantronformat_file {
                   4460:     my ($cdom) = @_;
                   4461:     if ($cdom eq '') {
                   4462:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4463:     }
                   4464:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4465:     my $gottab = 0;
                   4466:     my @lines;
                   4467:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4468:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4469:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4470:             if ($formatfile ne '-1') {
                   4471:                 @lines = split("\n",$formatfile,-1);
                   4472:                 $gottab = 1;
                   4473:             }
                   4474:         }
                   4475:     }
                   4476:     if (!$gottab) {
                   4477:         my $confname = $cdom.'-domainconfig';
                   4478:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4479:         my $formatfile = &getfile($default);
                   4480:         if ($formatfile ne '-1') {
                   4481:             @lines = split("\n",$formatfile,-1);
                   4482:             $gottab = 1;
                   4483:         }
                   4484:     }
                   4485:     if (!$gottab) {
                   4486:         my @domains = &current_machine_domains();
                   4487:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4488:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4489:                 @lines = <$fh>;
                   4490:                 close($fh);
                   4491:             }
                   4492:         } else {
                   4493:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4494:                 @lines = <$fh>;
                   4495:                 close($fh);
                   4496:             }
                   4497:         }
                   4498:     }
                   4499:     return @lines;
                   4500: }
                   4501: 
1.493     albertel 4502: sub removeuploadedurl {
1.984     neumanie 4503:     my ($url)=@_;	
                   4504:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4505:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4506: }
                   4507: 
                   4508: sub removeuserfile {
                   4509:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4510:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4511:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4512:     if ($result eq 'ok') {	
1.798     raeburn  4513:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4514:             my $metafile = $fname.'.meta';
                   4515:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4516: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4517:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4518:             my $sqlresult = 
1.823     albertel 4519:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4520:                                         'portfolio_metadata',$group,
                   4521:                                         'delete');
1.798     raeburn  4522:         }
                   4523:     }
                   4524:     return $result;
1.257     www      4525: }
1.15      www      4526: 
1.530     albertel 4527: sub mkdiruserfile {
                   4528:     my ($docuname,$docudom,$dir)=@_;
                   4529:     my $home=&homeserver($docuname,$docudom);
                   4530:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4531: }
                   4532: 
1.531     albertel 4533: sub renameuserfile {
                   4534:     my ($docuname,$docudom,$old,$new)=@_;
                   4535:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4536:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4537:                         &escape("$old").':'.&escape("$new"),$home);
                   4538:     if ($result eq 'ok') {
                   4539:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4540:             my $oldmeta = $old.'.meta';
                   4541:             my $newmeta = $new.'.meta';
                   4542:             my $metaresult = 
                   4543:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4544: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4545:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4546:             my $sqlresult = 
1.823     albertel 4547:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4548:                                         'portfolio_metadata',$group,
                   4549:                                         'delete');
1.798     raeburn  4550:         }
                   4551:     }
                   4552:     return $result;
1.531     albertel 4553: }
                   4554: 
1.14      www      4555: # ------------------------------------------------------------------------- Log
                   4556: 
                   4557: sub log {
                   4558:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4559:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4560: }
                   4561: 
                   4562: # ------------------------------------------------------------------ Course Log
1.352     www      4563: #
                   4564: # This routine flushes several buffers of non-mission-critical nature
                   4565: #
1.157     www      4566: 
                   4567: sub flushcourselogs {
1.352     www      4568:     &logthis('Flushing log buffers');
                   4569: #
                   4570: # course logs
                   4571: # This is a log of all transactions in a course, which can be used
                   4572: # for data mining purposes
                   4573: #
                   4574: # It also collects the courseid database, which lists last transaction
                   4575: # times and course titles for all courseids
                   4576: #
                   4577:     my %courseidbuffer=();
1.921     raeburn  4578:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4579:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4580: 		          &escape($courselogs{$crsid}),
                   4581: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4582: 	    delete $courselogs{$crsid};
                   4583:         } else {
                   4584:             &logthis('Failed to flush log buffer for '.$crsid);
                   4585:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4586:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4587:                         " exceeded maximum size, deleting.</font>");
                   4588:                delete $courselogs{$crsid};
                   4589:             }
1.352     www      4590:         }
1.920     raeburn  4591:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4592:             'description' => $coursedescrbuf{$crsid},
                   4593:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4594:             'type'        => $coursetypebuf{$crsid},
                   4595:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4596:         };
1.191     harris41 4597:     }
1.352     www      4598: #
                   4599: # Write course id database (reverse lookup) to homeserver of courses 
                   4600: # Is used in pickcourse
                   4601: #
1.840     albertel 4602:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4603:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4604:                                     $courseidbuffer{$crs_home},
                   4605:                                     $crs_home,'timeonly');
1.352     www      4606:     }
                   4607: #
                   4608: # File accesses
                   4609: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4610: #
1.449     matthew  4611:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4612:         if ($entry =~ /___count$/) {
                   4613:             my ($dom,$name);
1.807     albertel 4614:             ($dom,$name,undef)=
1.811     albertel 4615: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4616:             if (! defined($dom) || $dom eq '' || 
                   4617:                 ! defined($name) || $name eq '') {
1.620     albertel 4618:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4619: #
                   4620: # FIXME 11/29/2021
                   4621: # Typo in rev. 1.458 (2003/12/09)??
                   4622: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4623: #
                   4624: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4625: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4626: # in a nohist_accesscount.db file for the user rather than the course.
                   4627: #
                   4628: # That said there is a lot of noise in the data being stored.
                   4629: # So counts for prtspool/  and adm/ etc. are recorded.
                   4630: #
                   4631: # A review of which items ending '___count' are written to %accesshash should likely be
                   4632: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4633: #
                   4634: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4635: # accesses for things which are not published resources, regardless of course, and
                   4636: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4637: # anyone in the course for things which are not published resources.
                   4638: #
                   4639: # For an author, nohist_accesscount.db ends up having records for other items
                   4640: # mixed up with the legitimate access counts for the author's published resources.
                   4641: #
1.620     albertel 4642:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4643:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4644:             }
1.450     matthew  4645:             my $value = $accesshash{$entry};
                   4646:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4647:             my %temphash=($url => $value);
1.449     matthew  4648:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4649:             if ($result eq 'ok') {
                   4650:                 delete $accesshash{$entry};
                   4651:             }
                   4652:         } else {
1.811     albertel 4653:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4654:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4655:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4656:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4657:                 delete $accesshash{$entry};
                   4658:             }
1.185     www      4659:         }
1.191     harris41 4660:     }
1.352     www      4661: #
                   4662: # Roles
                   4663: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4664: #
1.800     albertel 4665:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4666:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4667: 	    split(/\:/,$entry);
                   4668:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4669:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4670:                 $rudom,$runame) eq 'ok') {
                   4671: 	    delete $userrolehash{$entry};
                   4672:         }
                   4673:     }
1.662     raeburn  4674: #
1.1172.2.90  raeburn  4675: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4676: #
                   4677:     my %domrolebuffer = ();
1.1000    raeburn  4678:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4679:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4680:         if ($domrolebuffer{$rudom}) {
                   4681:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4682:                       '='.&escape($domainrolehash{$entry});
                   4683:         } else {
                   4684:             $domrolebuffer{$rudom}.=&escape($entry).
                   4685:                       '='.&escape($domainrolehash{$entry});
                   4686:         }
                   4687:         delete $domainrolehash{$entry};
                   4688:     }
                   4689:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4690:         my %servers;
                   4691:         if (defined(&domain($dom,'primary'))) {
                   4692:             my $primary=&domain($dom,'primary');
                   4693:             my $hostname=&hostname($primary);
                   4694:             $servers{$primary} = $hostname;
                   4695:         } else {
                   4696:             %servers = &get_servers($dom,'library');
                   4697:         }
1.841     albertel 4698: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4699: 	    if (&reply('domroleput:'.$dom.':'.
                   4700: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4701: 	        last;
                   4702: 	    } else {
1.841     albertel 4703: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4704: 	    }
1.662     raeburn  4705:         }
                   4706:     }
1.186     www      4707:     $dumpcount++;
1.157     www      4708: }
                   4709: 
                   4710: sub courselog {
                   4711:     my $what=shift;
1.158     www      4712:     $what=time.':'.$what;
1.620     albertel 4713:     unless ($env{'request.course.id'}) { return ''; }
                   4714:     $coursedombuf{$env{'request.course.id'}}=
                   4715:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4716:     $coursenumbuf{$env{'request.course.id'}}=
                   4717:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4718:     $coursehombuf{$env{'request.course.id'}}=
                   4719:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4720:     $coursedescrbuf{$env{'request.course.id'}}=
                   4721:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4722:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4723:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4724:     $courseownerbuf{$env{'request.course.id'}}=
                   4725:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4726:     $coursetypebuf{$env{'request.course.id'}}=
                   4727:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4728:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4729: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4730:     } else {
1.620     albertel 4731: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4732:     }
1.620     albertel 4733:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4734: 	&flushcourselogs();
                   4735:     }
1.158     www      4736: }
                   4737: 
                   4738: sub courseacclog {
                   4739:     my $fnsymb=shift;
1.620     albertel 4740:     unless ($env{'request.course.id'}) { return ''; }
                   4741:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4742:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4743:         $what.=':POST';
1.583     matthew  4744:         # FIXME: Probably ought to escape things....
1.800     albertel 4745: 	foreach my $key (keys(%env)) {
                   4746:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4747:                 my $formitem = $1;
                   4748:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4749:                     $what.=':'.$formitem.'='.$env{$key};
                   4750:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4751:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4752:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4753:                     } else {
                   4754:                         $what.=':'.$formitem.'='.$env{$key};
                   4755:                     }
1.975     raeburn  4756:                 }
1.158     www      4757:             }
1.191     harris41 4758:         }
1.583     matthew  4759:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4760:         # FIXME: We should not be depending on a form parameter that someone
                   4761:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4762:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4763:             $what.= ':POST';
                   4764:             # FIXME: Probably ought to escape things....
                   4765:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4766:                                  'crsdiscuss') {
1.620     albertel 4767:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4768:             }
                   4769:         }
1.158     www      4770:     }
                   4771:     &courselog($what);
1.149     www      4772: }
                   4773: 
1.185     www      4774: sub countacc {
                   4775:     my $url=&declutter(shift);
1.458     matthew  4776:     return if (! defined($url) || $url eq '');
1.620     albertel 4777:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4778: #
                   4779: # Mark that this url was used in this course
                   4780: #
1.620     albertel 4781:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4782: #
                   4783: # Increase the access count for this resource in this child process
                   4784: #
1.281     www      4785:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4786:     $accesshash{$key}++;
1.185     www      4787: }
1.349     www      4788: 
1.361     www      4789: sub linklog {
                   4790:     my ($from,$to)=@_;
                   4791:     $from=&declutter($from);
                   4792:     $to=&declutter($to);
                   4793:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4794:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4795: }
1.1160    www      4796: 
                   4797: sub statslog {
                   4798:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4799:     if ($users<2) { return; }
                   4800:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4801:             'course'       => $env{'request.course.id'},
                   4802:             'sections'     => '"all"',
                   4803:             'num_students' => $users,
                   4804:             'part'         => $part,
                   4805:             'symb'         => $symb,
                   4806:             'mean_tries'   => $av_attempts,
                   4807:             'deg_of_diff'  => $degdiff});
                   4808:     foreach my $key (keys(%dynstore)) {
                   4809:         $accesshash{$key}=$dynstore{$key};
                   4810:     }
                   4811: }
1.361     www      4812:   
1.349     www      4813: sub userrolelog {
                   4814:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4815:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4816:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4817:        $userrolehash
                   4818:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4819:                     =$tend.':'.$tstart;
1.662     raeburn  4820:     }
1.1169    droeschl 4821:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4822:        $userrolehash
                   4823:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4824:                     =$tend.':'.$tstart;
                   4825:     }
1.1172.2.90  raeburn  4826:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4827:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4828:        $domainrolehash
                   4829:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4830:                     = $tend.':'.$tstart;
                   4831:     }
1.351     www      4832: }
                   4833: 
1.957     raeburn  4834: sub courserolelog {
                   4835:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4836:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4837:         my $cdom = $1;
                   4838:         my $cnum = $2;
                   4839:         my $sec = $3;
                   4840:         my $namespace = 'rolelog';
                   4841:         my %storehash = (
                   4842:                            role    => $trole,
                   4843:                            start   => $tstart,
                   4844:                            end     => $tend,
                   4845:                            selfenroll => $selfenroll,
                   4846:                            context    => $context,
                   4847:                         );
                   4848:         if ($trole eq 'gr') {
                   4849:             $namespace = 'groupslog';
                   4850:             $storehash{'group'} = $sec;
                   4851:         } else {
                   4852:             $storehash{'section'} = $sec;
                   4853:         }
                   4854:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4855:                    $domain,$cnum,$cdom);
                   4856:         if (($trole ne 'st') || ($sec ne '')) {
                   4857:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4858:         }
                   4859:     }
                   4860:     return;
                   4861: }
                   4862: 
1.1172.2.9  raeburn  4863: sub domainrolelog {
                   4864:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4865:     if ($area =~ m{^/($match_domain)/$}) {
                   4866:         my $cdom = $1;
                   4867:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4868:         my $namespace = 'rolelog';
                   4869:         my %storehash = (
                   4870:                            role    => $trole,
                   4871:                            start   => $tstart,
                   4872:                            end     => $tend,
                   4873:                            context => $context,
                   4874:                         );
                   4875:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4876:                    $domain,$domconfiguser,$cdom);
                   4877:     }
                   4878:     return;
                   4879: 
                   4880: }
                   4881: 
                   4882: sub coauthorrolelog {
                   4883:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4884:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4885:         my $audom = $1;
                   4886:         my $auname = $2;
                   4887:         my $namespace = 'rolelog';
                   4888:         my %storehash = (
                   4889:                            role    => $trole,
                   4890:                            start   => $tstart,
                   4891:                            end     => $tend,
                   4892:                            context => $context,
                   4893:                         );
                   4894:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4895:                    $domain,$auname,$audom);
                   4896:     }
                   4897:     return;
                   4898: }
                   4899: 
1.351     www      4900: sub get_course_adv_roles {
1.948     raeburn  4901:     my ($cid,$codes) = @_;
1.620     albertel 4902:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4903:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4904:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4905:     my %nothide=();
1.800     albertel 4906:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4907:         if ($user !~ /:/) {
                   4908: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4909:         } else {
                   4910:             $nothide{$user}=1;
                   4911:         }
1.470     www      4912:     }
1.1172.2.23  raeburn  4913:     my @possdoms = ($coursehash{'domain'});
                   4914:     if ($coursehash{'checkforpriv'}) {
                   4915:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4916:     }
1.351     www      4917:     my %returnhash=();
                   4918:     my %dumphash=
                   4919:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4920:     my $now=time;
1.997     raeburn  4921:     my %privileged;
1.1000    raeburn  4922:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4923: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4924:         if (($tstart) && ($tstart<0)) { next; }
                   4925:         if (($tend) && ($tend<$now)) { next; }
                   4926:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4927:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4928: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4929:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4930:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4931: 	if ($role eq 'cr') { next; }
1.948     raeburn  4932:         if ($codes) {
                   4933:             if ($section) { $role .= ':'.$section; }
                   4934:             if ($returnhash{$role}) {
                   4935:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4936:             } else {
                   4937:                 $returnhash{$role}=$username.':'.$domain;
                   4938:             }
1.351     www      4939:         } else {
1.988     raeburn  4940:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4941:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4942:             if ($returnhash{$key}) {
                   4943: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4944:             } else {
                   4945:                 $returnhash{$key}=$username.':'.$domain;
                   4946:             }
1.351     www      4947:         }
1.948     raeburn  4948:     }
1.400     www      4949:     return %returnhash;
                   4950: }
                   4951: 
                   4952: sub get_my_roles {
1.937     raeburn  4953:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4954:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4955:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4956:     my (%dumphash,%nothide);
1.1086    raeburn  4957:     if ($context eq 'userroles') {
1.1166    raeburn  4958:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4959:     } else {
1.1172.2.23  raeburn  4960:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4961:         if ($hidepriv) {
                   4962:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4963:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4964:                 if ($user !~ /:/) {
                   4965:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4966:                 } else {
                   4967:                     $nothide{$user} = 1;
                   4968:                 }
                   4969:             }
                   4970:         }
1.858     raeburn  4971:     }
1.400     www      4972:     my %returnhash=();
                   4973:     my $now=time;
1.999     raeburn  4974:     my %privileged;
1.800     albertel 4975:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4976:         my ($role,$tend,$tstart);
                   4977:         if ($context eq 'userroles') {
1.1149    raeburn  4978:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4979: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4980:         } else {
                   4981:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4982:         }
1.400     www      4983:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4984:         my $status = 'active';
1.939     raeburn  4985:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4986:             $status = 'previous';
                   4987:         } 
                   4988:         if (($tstart) && ($now<$tstart)) {
                   4989:             $status = 'future';
                   4990:         }
                   4991:         if (ref($types) eq 'ARRAY') {
                   4992:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4993:                 next;
                   4994:             } 
                   4995:         } else {
                   4996:             if ($status ne 'active') {
                   4997:                 next;
                   4998:             }
                   4999:         }
1.867     raeburn  5000:         my ($rolecode,$username,$domain,$section,$area);
                   5001:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5002:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5003:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5004:         } else {
                   5005:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5006:         }
1.832     raeburn  5007:         if (ref($roledoms) eq 'ARRAY') {
                   5008:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5009:                 next;
                   5010:             }
                   5011:         }
                   5012:         if (ref($roles) eq 'ARRAY') {
                   5013:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5014:                 if ($role =~ /^cr\//) {
                   5015:                     if (!grep(/^cr$/,@{$roles})) {
                   5016:                         next;
                   5017:                     }
1.1104    raeburn  5018:                 } elsif ($role =~ /^gr\//) {
                   5019:                     if (!grep(/^gr$/,@{$roles})) {
                   5020:                         next;
                   5021:                     }
1.922     raeburn  5022:                 } else {
                   5023:                     next;
                   5024:                 }
1.832     raeburn  5025:             }
1.867     raeburn  5026:         }
1.937     raeburn  5027:         if ($hidepriv) {
1.1172.2.23  raeburn  5028:             my @privroles = ('dc','su');
1.999     raeburn  5029:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5030:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5031:             } else {
1.1172.2.23  raeburn  5032:                 my $possdoms = [$domain];
                   5033:                 if (ref($roledoms) eq 'ARRAY') {
                   5034:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5035:                 }
1.1172.2.23  raeburn  5036:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5037:                     if (!$nothide{$username.':'.$domain}) {
                   5038:                         next;
                   5039:                     }
                   5040:                 }
1.937     raeburn  5041:             }
                   5042:         }
1.933     raeburn  5043:         if ($withsec) {
                   5044:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5045:                 $tstart.':'.$tend;
                   5046:         } else {
                   5047:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5048:         }
1.832     raeburn  5049:     }
1.373     www      5050:     return %returnhash;
1.399     www      5051: }
                   5052: 
1.1172.2.89  raeburn  5053: sub get_all_adhocroles {
                   5054:     my ($dom) = @_;
                   5055:     my @roles_by_num = ();
                   5056:     my %domdefaults = &get_domain_defaults($dom);
                   5057:     my (%description,%access_in_dom,%access_info);
                   5058:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5059:         my $count = 0;
                   5060:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5061:         my %ordered;
                   5062:         foreach my $role (sort(keys(%domcurrent))) {
                   5063:             my ($order,$desc,$access_in_dom);
                   5064:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5065:                 $order = $domcurrent{$role}{'order'};
                   5066:                 $desc = $domcurrent{$role}{'desc'};
                   5067:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5068:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5069:             }
                   5070:             if ($order eq '') {
                   5071:                 $order = $count;
                   5072:             }
                   5073:             $ordered{$order} = $role;
                   5074:             if ($desc ne '') {
                   5075:                 $description{$role} = $desc;
                   5076:             } else {
                   5077:                 $description{$role}= $role;
                   5078:             }
                   5079:             $count++;
                   5080:         }
                   5081:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5082:             push(@roles_by_num,$ordered{$item});
                   5083:         }
                   5084:     }
                   5085:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5086: }
                   5087: 
                   5088: sub get_my_adhocroles {
                   5089:     my ($cid,$checkreg) = @_;
                   5090:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5091:     if ($env{'request.course.id'} eq $cid) {
                   5092:         $cdom = $env{'course.'.$cid.'.domain'};
                   5093:         $cnum = $env{'course.'.$cid.'.num'};
                   5094:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5095:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5096:         $cdom = $1;
                   5097:         $cnum = $2;
                   5098:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5099:                                      $cdom,$cnum);
                   5100:     }
                   5101:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5102:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5103:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5104:         if ($rosterhash{$user} ne '') {
                   5105:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5106:             return ([],{}) if ($type eq 'auto');
                   5107:         }
                   5108:     }
                   5109:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5110:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5111:             my $then=$env{'user.login.time'};
                   5112:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5113:             if (!$update) {
                   5114:                 $update = $then;
                   5115:             }
                   5116:             my @liveroles;
                   5117:             foreach my $role ('dh','da') {
                   5118:                 if ($env{"user.role.$role./$cdom/"}) {
                   5119:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5120:                     my $limit = $update;
                   5121:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5122:                         $limit = $then;
                   5123:                     }
                   5124:                     my $activerole = 1;
                   5125:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5126:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5127:                     if ($activerole) {
                   5128:                         push(@liveroles,$role);
                   5129:                     }
                   5130:                 }
                   5131:             }
                   5132:             if (@liveroles) {
1.1172.2.89  raeburn  5133:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5134:                     my ($accessref,$accessinfo,%access_in_dom);
                   5135:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5136:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5137:                         if (@{$roles_by_num}) {
                   5138:                             my %settings;
                   5139:                             if ($env{'request.course.id'} eq $cid) {
                   5140:                                 foreach my $envkey (keys(%env)) {
                   5141:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5142:                                         $settings{$1} = $env{$envkey};
                   5143:                                     }
                   5144:                                 }
                   5145:                             } else {
                   5146:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5147:                             }
                   5148:                             my %setincrs;
                   5149:                             if ($settings{'internal.adhocaccess'}) {
                   5150:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5151:                             }
                   5152:                             my @statuses;
                   5153:                             if ($env{'environment.inststatus'}) {
                   5154:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5155:                             }
                   5156:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5157:                             if (ref($accessref) eq 'HASH') {
                   5158:                                 %access_in_dom = %{$accessref};
                   5159:                             }
                   5160:                             foreach my $role (@{$roles_by_num}) {
                   5161:                                 my ($curraccess,@okstatus,@personnel);
                   5162:                                 if ($setincrs{$role}) {
                   5163:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5164:                                     if ($curraccess eq 'status') {
                   5165:                                         @okstatus = split(/\&/,$rest);
                   5166:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5167:                                         @personnel = split(/\&/,$rest);
                   5168:                                     }
                   5169:                                 } else {
                   5170:                                     $curraccess = $access_in_dom{$role};
                   5171:                                     if (ref($accessinfo) eq 'HASH') {
                   5172:                                         if ($curraccess eq 'status') {
                   5173:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5174:                                                 @okstatus = @{$accessinfo->{$role}};
                   5175:                                             }
                   5176:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5177:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5178:                                                 @personnel = @{$accessinfo->{$role}};
                   5179:                                             }
                   5180:                                         }
                   5181:                                     }
                   5182:                                 }
                   5183:                                 if ($curraccess eq 'none') {
                   5184:                                     next;
                   5185:                                 } elsif ($curraccess eq 'all') {
                   5186:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5187:                                 } elsif ($curraccess eq 'dh') {
                   5188:                                     if (grep(/^dh$/,@liveroles)) {
                   5189:                                         push(@possroles,$role);
                   5190:                                     } else {
                   5191:                                         next;
                   5192:                                     }
                   5193:                                 } elsif ($curraccess eq 'da') {
                   5194:                                     if (grep(/^da$/,@liveroles)) {
                   5195:                                         push(@possroles,$role);
                   5196:                                     } else {
                   5197:                                         next;
                   5198:                                     }
1.1172.2.89  raeburn  5199:                                 } elsif ($curraccess eq 'status') {
                   5200:                                     if (@okstatus) {
                   5201:                                         if (!@statuses) {
                   5202:                                             if (grep(/^default$/,@okstatus)) {
                   5203:                                                 push(@possroles,$role);
                   5204:                                             }
                   5205:                                         } else {
                   5206:                                             foreach my $status (@okstatus) {
                   5207:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5208:                                                     push(@possroles,$role);
                   5209:                                                     last;
                   5210:                                                 }
                   5211:                                             }
                   5212:                                         }
                   5213:                                     }
                   5214:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5215:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5216:                                         if ($curraccess eq 'exc') {
                   5217:                                             push(@possroles,$role);
                   5218:                                         }
                   5219:                                     } elsif ($curraccess eq 'inc') {
                   5220:                                         push(@possroles,$role);
                   5221:                                     }
                   5222:                                 }
                   5223:                             }
                   5224:                         }
                   5225:                     }
                   5226:                 }
                   5227:             }
                   5228:         }
                   5229:     }
                   5230:     unless (ref($description) eq 'HASH') {
                   5231:         if (ref($roles_by_num) eq 'ARRAY') {
                   5232:             my %desc;
                   5233:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5234:             $description = \%desc;
                   5235:         } else {
                   5236:             $description = {};
                   5237:         }
                   5238:     }
                   5239:     return (\@possroles,$description);
                   5240: }
                   5241: 
1.399     www      5242: # ----------------------------------------------------- Frontpage Announcements
                   5243: #
                   5244: #
                   5245: 
                   5246: sub postannounce {
                   5247:     my ($server,$text)=@_;
1.844     albertel 5248:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5249:     unless ($text=~/\w/) { $text=''; }
                   5250:     return &reply('setannounce:'.&escape($text),$server);
                   5251: }
                   5252: 
                   5253: sub getannounce {
1.448     albertel 5254: 
1.1172.2.96  raeburn  5255:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5256: 	my $announcement='';
1.800     albertel 5257: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5258: 	close($fh);
1.399     www      5259: 	if ($announcement=~/\w/) { 
                   5260: 	    return 
                   5261:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5262:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5263: 	} else {
                   5264: 	    return '';
                   5265: 	}
                   5266:     } else {
                   5267: 	return '';
                   5268:     }
1.351     www      5269: }
1.353     www      5270: 
                   5271: # ---------------------------------------------------------- Course ID routines
                   5272: # Deal with domain's nohist_courseid.db files
                   5273: #
                   5274: 
                   5275: sub courseidput {
1.921     raeburn  5276:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5277:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5278:     my $outcome;
                   5279:     if ($caller eq 'timeonly') {
                   5280:         my $cids = '';
                   5281:         foreach my $item (keys(%$storehash)) {
                   5282:             $cids.=&escape($item).'&';
                   5283:         }
                   5284:         $cids=~s/\&$//;
                   5285:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5286:                           $coursehome);       
                   5287:     } else {
                   5288:         my $items = '';
                   5289:         foreach my $item (keys(%$storehash)) {
                   5290:             $items.= &escape($item).'='.
                   5291:                      &freeze_escape($$storehash{$item}).'&';
                   5292:         }
                   5293:         $items=~s/\&$//;
                   5294:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5295:                           $coursehome);
1.918     raeburn  5296:     }
                   5297:     if ($outcome eq 'unknown_cmd') {
                   5298:         my $what;
                   5299:         foreach my $cid (keys(%$storehash)) {
                   5300:             $what .= &escape($cid).'=';
1.921     raeburn  5301:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5302:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5303:             }
                   5304:             $what =~ s/\:$/&/;
                   5305:         }
                   5306:         $what =~ s/\&$//;  
                   5307:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5308:     } else {
                   5309:         return $outcome;
                   5310:     }
1.353     www      5311: }
                   5312: 
                   5313: sub courseiddump {
1.921     raeburn  5314:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5315:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5316:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5317:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5318:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5319:     my $as_hash = 1;
                   5320:     my %returnhash;
                   5321:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5322:     my %libserv = &all_library();
                   5323:     foreach my $tryserver (keys(%libserv)) {
                   5324:         if ( (  $hostidflag == 1 
                   5325: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5326: 	     || (!defined($hostidflag)) ) {
                   5327: 
1.918     raeburn  5328: 	    if (($domfilter eq '') ||
                   5329: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5330:                 my $rep;
                   5331:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5332:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5333:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5334:                                 &escape($descfilter), &escape($instcodefilter),
                   5335:                                 &escape($ownerfilter), &escape($coursefilter),
                   5336:                                 &escape($typefilter), &escape($regexp_ok),
                   5337:                                 $as_hash, &escape($selfenrollonly),
                   5338:                                 &escape($catfilter), $showhidden, $caller,
                   5339:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5340:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5341:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5342:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5343:                 } else {
                   5344:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5345:                              $sincefilter.':'.&escape($descfilter).':'.
                   5346:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5347:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5348:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5349:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5350:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5351:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5352:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5353:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5354:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5355:                 }
                   5356: 
1.918     raeburn  5357:                 my @pairs=split(/\&/,$rep);
                   5358:                 foreach my $item (@pairs) {
                   5359:                     my ($key,$value)=split(/\=/,$item,2);
                   5360:                     $key = &unescape($key);
                   5361:                     next if ($key =~ /^error: 2 /);
                   5362:                     my $result = &thaw_unescape($value);
                   5363:                     if (ref($result) eq 'HASH') {
                   5364:                         $returnhash{$key}=$result;
                   5365:                     } else {
1.921     raeburn  5366:                         my @responses = split(/:/,$value);
                   5367:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5368:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5369:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5370:                         }
1.1008    raeburn  5371:                     }
1.353     www      5372:                 }
                   5373:             }
                   5374:         }
                   5375:     }
                   5376:     return %returnhash;
                   5377: }
                   5378: 
1.1055    raeburn  5379: sub courselastaccess {
                   5380:     my ($cdom,$cnum,$hostidref) = @_;
                   5381:     my %returnhash;
                   5382:     if ($cdom && $cnum) {
                   5383:         my $chome = &homeserver($cnum,$cdom);
                   5384:         if ($chome ne 'no_host') {
                   5385:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5386:             &extract_lastaccess(\%returnhash,$rep);
                   5387:         }
                   5388:     } else {
                   5389:         if (!$cdom) { $cdom=''; }
                   5390:         my %libserv = &all_library();
                   5391:         foreach my $tryserver (keys(%libserv)) {
                   5392:             if (ref($hostidref) eq 'ARRAY') {
                   5393:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5394:             } 
                   5395:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5396:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5397:                 &extract_lastaccess(\%returnhash,$rep);
                   5398:             }
                   5399:         }
                   5400:     }
                   5401:     return %returnhash;
                   5402: }
                   5403: 
                   5404: sub extract_lastaccess {
                   5405:     my ($returnhash,$rep) = @_;
                   5406:     if (ref($returnhash) eq 'HASH') {
                   5407:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5408:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5409:                  $rep eq '') {
                   5410:             my @pairs=split(/\&/,$rep);
                   5411:             foreach my $item (@pairs) {
                   5412:                 my ($key,$value)=split(/\=/,$item,2);
                   5413:                 $key = &unescape($key);
                   5414:                 next if ($key =~ /^error: 2 /);
                   5415:                 $returnhash->{$key} = &thaw_unescape($value);
                   5416:             }
                   5417:         }
                   5418:     }
                   5419:     return;
                   5420: }
                   5421: 
1.658     raeburn  5422: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5423: 
                   5424: sub dcmailput {
1.685     raeburn  5425:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5426:     my $status = &Apache::lonnet::critical(
1.740     www      5427:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5428:        &escape($message),$server);
1.662     raeburn  5429:     return $status;
                   5430: }
                   5431: 
1.658     raeburn  5432: sub dcmaildump {
                   5433:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5434:     my %returnhash=();
1.846     albertel 5435: 
                   5436:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5437:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5438:                                                          &escape($enddate).':';
                   5439: 	my @esc_senders=map { &escape($_)} @$senders;
                   5440: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5441: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5442:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5443:             if (($key) && ($value)) {
                   5444:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5445:             }
                   5446:         }
                   5447:     }
                   5448:     return %returnhash;
                   5449: }
1.662     raeburn  5450: # ---------------------------------------------------------- Domain roles
                   5451: 
                   5452: sub get_domain_roles {
                   5453:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5454:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5455:         $startdate = '.';
                   5456:     }
1.1018    raeburn  5457:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5458:         $enddate = '.';
                   5459:     }
1.922     raeburn  5460:     my $rolelist;
                   5461:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5462:         $rolelist = join('&',@{$roles});
1.922     raeburn  5463:     }
1.662     raeburn  5464:     my %personnel = ();
1.841     albertel 5465: 
                   5466:     my %servers = &get_servers($dom,'library');
                   5467:     foreach my $tryserver (keys(%servers)) {
                   5468: 	%{$personnel{$tryserver}}=();
                   5469: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5470: 					    &escape($startdate).':'.
                   5471: 					    &escape($enddate).':'.
                   5472: 					    &escape($rolelist), $tryserver))) {
                   5473: 	    my ($key,$value) = split(/\=/,$line,2);
                   5474: 	    if (($key) && ($value)) {
                   5475: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5476: 	    }
                   5477: 	}
1.662     raeburn  5478:     }
                   5479:     return %personnel;
                   5480: }
1.658     raeburn  5481: 
1.1172.2.89  raeburn  5482: sub get_active_domroles {
                   5483:     my ($dom,$roles) = @_;
                   5484:     return () unless (ref($roles) eq 'ARRAY');
                   5485:     my $now = time;
                   5486:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5487:     my %domroles;
                   5488:     foreach my $server (keys(%dompersonnel)) {
                   5489:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5490:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5491:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5492:         }
                   5493:     }
                   5494:     return %domroles;
                   5495: }
                   5496: 
1.1057    www      5497: # ----------------------------------------------------------- Interval timing 
1.149     www      5498: 
1.1153    www      5499: {
                   5500: # Caches needed for speedup of navmaps
                   5501: # We don't want to cache this for very long at all (5 seconds at most)
                   5502: # 
                   5503: # The user for whom we cache
                   5504: my $cachedkey='';
                   5505: # The cached times for this user
                   5506: my %cachedtimes=();
                   5507: # When this was last done
1.1172.2.66  raeburn  5508: my $cachedtime='';
1.1153    www      5509: 
                   5510: sub load_all_first_access {
1.1154    raeburn  5511:     my ($uname,$udom)=@_;
1.1156    www      5512:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5513:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5514:         return;
                   5515:     }
                   5516:     $cachedtime=time;
                   5517:     $cachedkey=$uname.':'.$udom;
                   5518:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5519: }
                   5520: 
1.504     albertel 5521: sub get_first_access {
1.1162    raeburn  5522:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5523:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5524:     if ($argsymb) { $symb=$argsymb; }
                   5525:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5526:     if ($argmap) { $map = $argmap; }
1.926     albertel 5527:     if ($type eq 'course') {
                   5528: 	$res='course';
                   5529:     } elsif ($type eq 'map') {
1.588     albertel 5530: 	$res=&symbread($map);
                   5531:     } else {
                   5532: 	$res=$symb;
                   5533:     }
1.1153    www      5534:     &load_all_first_access($uname,$udom);
                   5535:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5536: }
                   5537: 
                   5538: sub set_first_access {
1.1162    raeburn  5539:     my ($type,$interval)=@_;
1.790     albertel 5540:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5541:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5542:     if ($type eq 'course') {
                   5543: 	$res='course';
                   5544:     } elsif ($type eq 'map') {
1.588     albertel 5545: 	$res=&symbread($map);
                   5546:     } else {
                   5547: 	$res=$symb;
                   5548:     }
1.1153    www      5549:     $cachedkey='';
1.1162    raeburn  5550:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5551:     if ($firstaccess) {
                   5552:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5553:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5554:                  "in $courseid");
                   5555:         return 'already_set';
                   5556:     } else {
1.1162    raeburn  5557:         my $start = time;
                   5558: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5559:                           $udom,$uname);
                   5560:         if ($putres eq 'ok') {
                   5561:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5562:                  $udom,$uname); 
                   5563:             &appenv(
                   5564:                      {
                   5565:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5566:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5567:                      }
                   5568:                   );
1.1172.2.97  raeburn  5569:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5570:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5571:             }
1.1172.2.102  raeburn  5572:         } elsif ($putres ne 'refused') {
                   5573:             &logthis("Result: $putres when attempting to set first access time ".
                   5574:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5575:         }
                   5576:         return $putres;
1.505     albertel 5577:     }
                   5578:     return 'already_set';
1.504     albertel 5579: }
1.1153    www      5580: }
1.1172.2.32  raeburn  5581: 
                   5582: sub checkout {
                   5583:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5584:     my $now=time;
                   5585:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5586:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5587:     my $infostr=&escape(
                   5588:                  'CHECKOUTTOKEN&'.
                   5589:                  $tuname.'&'.
                   5590:                  $tudom.'&'.
                   5591:                  $tcrsid.'&'.
                   5592:                  $symb.'&'.
1.1172.2.134  raeburn  5593:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5594:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5595:     if ($token=~/^error\:/) {
                   5596:         &logthis("<font color=\"blue\">WARNING: ".
                   5597:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5598:                  "</font>");
                   5599:         return '';
                   5600:     }
                   5601: 
                   5602:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5603:     $token=~tr/a-z/A-Z/;
                   5604: 
                   5605:     my %infohash=('resource.0.outtoken' => $token,
                   5606:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5607:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5608: 
                   5609:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5610:        return '';
                   5611:     } else {
                   5612:         &logthis("<font color=\"blue\">WARNING: ".
                   5613:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5614:                  "</font>");
                   5615:     }
                   5616: 
                   5617:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5618:                          &escape('Checkout '.$infostr.' - '.
                   5619:                                                  $token)) ne 'ok') {
                   5620:         return '';
                   5621:     } else {
                   5622:         &logthis("<font color=\"blue\">WARNING: ".
                   5623:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5624:                  "</font>");
                   5625:     }
                   5626:     return $token;
                   5627: }
                   5628: 
                   5629: # ------------------------------------------------------------ Check in an item
                   5630: 
                   5631: sub checkin {
                   5632:     my $token=shift;
                   5633:     my $now=time;
                   5634:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5635:     $lonhost=~tr/A-Z/a-z/;
                   5636:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5637:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5638:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5639:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5640:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5641: 
                   5642:     unless (($tuname) && ($tudom)) {
                   5643:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5644:         return '';
                   5645:     }
                   5646: 
                   5647:     unless (&allowed('mgr',$tcrsid)) {
                   5648:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5649:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5650:         return '';
                   5651:     }
                   5652: 
                   5653:     my %infohash=('resource.0.intoken' => $token,
                   5654:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5655:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5656: 
                   5657:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5658:        return '';
                   5659:     }
                   5660: 
                   5661:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5662:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5663:         return '';
                   5664:     }
                   5665: 
                   5666:     return ($symb,$tuname,$tudom,$tcrsid);
                   5667: }
                   5668: 
1.110     www      5669: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5670: 
                   5671: sub expirespread {
                   5672:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5673:     my $cid=$env{'request.course.id'}; 
1.110     www      5674:     if ($cid) {
                   5675:        my $now=time;
                   5676:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5677:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5678:                             $env{'course.'.$cid.'.num'}.
1.110     www      5679: 	        	    ':nohist_expirationdates:'.
                   5680:                             &escape($key).'='.$now,
1.620     albertel 5681:                             $env{'course.'.$cid.'.home'})
1.110     www      5682:     }
                   5683:     return 'ok';
1.14      www      5684: }
                   5685: 
1.109     www      5686: # ----------------------------------------------------- Devalidate Spreadsheets
                   5687: 
                   5688: sub devalidate {
1.325     www      5689:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5690:     my $cid=$env{'request.course.id'}; 
1.109     www      5691:     if ($cid) {
1.391     matthew  5692:         # delete the stored spreadsheets for
                   5693:         # - the student level sheet of this user in course's homespace
                   5694:         # - the assessment level sheet for this resource 
                   5695:         #   for this user in user's homespace
1.553     albertel 5696: 	# - current conditional state info
1.325     www      5697: 	my $key=$uname.':'.$udom.':';
1.109     www      5698:         my $status=
1.299     matthew  5699: 	    &del('nohist_calculatedsheets',
1.391     matthew  5700: 		 [$key.'studentcalc:'],
1.620     albertel 5701: 		 $env{'course.'.$cid.'.domain'},
                   5702: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5703: 		.' '.
                   5704: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5705: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5706:         unless ($status eq 'ok ok') {
                   5707:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5708:                     $uname.' at '.$udom.' for '.
1.109     www      5709: 		    $symb.': '.$status);
1.133     albertel 5710:         }
1.553     albertel 5711: 	&delenv('user.state.'.$cid);
1.109     www      5712:     }
                   5713: }
                   5714: 
1.265     albertel 5715: sub get_scalar {
                   5716:     my ($string,$end) = @_;
                   5717:     my $value;
                   5718:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5719: 	$value = $1;
                   5720:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5721: 	$value = $1;
                   5722:     }
                   5723:     return &unescape($value);
                   5724: }
                   5725: 
                   5726: sub array2str {
                   5727:   my (@array) = @_;
                   5728:   my $result=&arrayref2str(\@array);
                   5729:   $result=~s/^__ARRAY_REF__//;
                   5730:   $result=~s/__END_ARRAY_REF__$//;
                   5731:   return $result;
                   5732: }
                   5733: 
1.204     albertel 5734: sub arrayref2str {
                   5735:   my ($arrayref) = @_;
1.265     albertel 5736:   my $result='__ARRAY_REF__';
1.204     albertel 5737:   foreach my $elem (@$arrayref) {
1.265     albertel 5738:     if(ref($elem) eq 'ARRAY') {
                   5739:       $result.=&arrayref2str($elem).'&';
                   5740:     } elsif(ref($elem) eq 'HASH') {
                   5741:       $result.=&hashref2str($elem).'&';
                   5742:     } elsif(ref($elem)) {
                   5743:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5744:     } else {
                   5745:       $result.=&escape($elem).'&';
                   5746:     }
                   5747:   }
                   5748:   $result=~s/\&$//;
1.265     albertel 5749:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5750:   return $result;
                   5751: }
                   5752: 
1.168     albertel 5753: sub hash2str {
1.204     albertel 5754:   my (%hash) = @_;
                   5755:   my $result=&hashref2str(\%hash);
1.265     albertel 5756:   $result=~s/^__HASH_REF__//;
                   5757:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5758:   return $result;
                   5759: }
                   5760: 
                   5761: sub hashref2str {
                   5762:   my ($hashref)=@_;
1.265     albertel 5763:   my $result='__HASH_REF__';
1.800     albertel 5764:   foreach my $key (sort(keys(%$hashref))) {
                   5765:     if (ref($key) eq 'ARRAY') {
                   5766:       $result.=&arrayref2str($key).'=';
                   5767:     } elsif (ref($key) eq 'HASH') {
                   5768:       $result.=&hashref2str($key).'=';
                   5769:     } elsif (ref($key)) {
1.265     albertel 5770:       $result.='=';
1.800     albertel 5771:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5772:     } else {
1.1132    raeburn  5773: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5774:     }
                   5775: 
1.800     albertel 5776:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5777:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5778:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5779:       $result.=&hashref2str($hashref->{$key}).'&';
                   5780:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5781:        $result.='&';
1.800     albertel 5782:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5783:     } else {
1.800     albertel 5784:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5785:     }
                   5786:   }
1.168     albertel 5787:   $result=~s/\&$//;
1.265     albertel 5788:   $result .= '__END_HASH_REF__';
1.168     albertel 5789:   return $result;
                   5790: }
                   5791: 
                   5792: sub str2hash {
1.265     albertel 5793:     my ($string)=@_;
                   5794:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5795:     return %$hash;
                   5796: }
                   5797: 
                   5798: sub str2hashref {
1.168     albertel 5799:   my ($string) = @_;
1.265     albertel 5800: 
                   5801:   my %hash;
                   5802: 
                   5803:   if($string !~ /^__HASH_REF__/) {
                   5804:       if (! ($string eq '' || !defined($string))) {
                   5805: 	  $hash{'error'}='Not hash reference';
                   5806:       }
                   5807:       return (\%hash, $string);
                   5808:   }
                   5809: 
                   5810:   $string =~ s/^__HASH_REF__//;
                   5811: 
                   5812:   while($string !~ /^__END_HASH_REF__/) {
                   5813:       #key
                   5814:       my $key='';
                   5815:       if($string =~ /^__HASH_REF__/) {
                   5816:           ($key, $string)=&str2hashref($string);
                   5817:           if(defined($key->{'error'})) {
                   5818:               $hash{'error'}='Bad data';
                   5819:               return (\%hash, $string);
                   5820:           }
                   5821:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5822:           ($key, $string)=&str2arrayref($string);
                   5823:           if($key->[0] eq 'Array reference error') {
                   5824:               $hash{'error'}='Bad data';
                   5825:               return (\%hash, $string);
                   5826:           }
                   5827:       } else {
                   5828:           $string =~ s/^(.*?)=//;
1.267     albertel 5829: 	  $key=&unescape($1);
1.265     albertel 5830:       }
                   5831:       $string =~ s/^=//;
                   5832: 
                   5833:       #value
                   5834:       my $value='';
                   5835:       if($string =~ /^__HASH_REF__/) {
                   5836:           ($value, $string)=&str2hashref($string);
                   5837:           if(defined($value->{'error'})) {
                   5838:               $hash{'error'}='Bad data';
                   5839:               return (\%hash, $string);
                   5840:           }
                   5841:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5842:           ($value, $string)=&str2arrayref($string);
                   5843:           if($value->[0] eq 'Array reference error') {
                   5844:               $hash{'error'}='Bad data';
                   5845:               return (\%hash, $string);
                   5846:           }
                   5847:       } else {
                   5848: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5849:       }
                   5850:       $string =~ s/^&//;
                   5851: 
                   5852:       $hash{$key}=$value;
1.204     albertel 5853:   }
1.265     albertel 5854: 
                   5855:   $string =~ s/^__END_HASH_REF__//;
                   5856: 
                   5857:   return (\%hash, $string);
1.204     albertel 5858: }
                   5859: 
                   5860: sub str2array {
1.265     albertel 5861:     my ($string)=@_;
                   5862:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5863:     return @$array;
                   5864: }
                   5865: 
                   5866: sub str2arrayref {
1.204     albertel 5867:   my ($string) = @_;
1.265     albertel 5868:   my @array;
                   5869: 
                   5870:   if($string !~ /^__ARRAY_REF__/) {
                   5871:       if (! ($string eq '' || !defined($string))) {
                   5872: 	  $array[0]='Array reference error';
                   5873:       }
                   5874:       return (\@array, $string);
                   5875:   }
                   5876: 
                   5877:   $string =~ s/^__ARRAY_REF__//;
                   5878: 
                   5879:   while($string !~ /^__END_ARRAY_REF__/) {
                   5880:       my $value='';
                   5881:       if($string =~ /^__HASH_REF__/) {
                   5882:           ($value, $string)=&str2hashref($string);
                   5883:           if(defined($value->{'error'})) {
                   5884:               $array[0] ='Array reference error';
                   5885:               return (\@array, $string);
                   5886:           }
                   5887:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5888:           ($value, $string)=&str2arrayref($string);
                   5889:           if($value->[0] eq 'Array reference error') {
                   5890:               $array[0] ='Array reference error';
                   5891:               return (\@array, $string);
                   5892:           }
                   5893:       } else {
                   5894: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5895:       }
                   5896:       $string =~ s/^&//;
                   5897: 
                   5898:       push(@array, $value);
1.191     harris41 5899:   }
1.265     albertel 5900: 
                   5901:   $string =~ s/^__END_ARRAY_REF__//;
                   5902: 
                   5903:   return (\@array, $string);
1.168     albertel 5904: }
                   5905: 
1.167     albertel 5906: # -------------------------------------------------------------------Temp Store
                   5907: 
1.168     albertel 5908: sub tmpreset {
                   5909:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5910:   if (!$symb) {
                   5911:     $symb=&symbread();
1.620     albertel 5912:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5913:   }
                   5914:   $symb=escape($symb);
                   5915: 
1.620     albertel 5916:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5917:   $namespace=~s/\//\_/g;
                   5918:   $namespace=~s/\W//g;
                   5919: 
1.620     albertel 5920:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5921:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5922:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5923:       $stuname=&get_requestor_ip();
1.591     albertel 5924:   }
1.1117    foxr     5925:   my $path=LONCAPA::tempdir();
1.168     albertel 5926:   my %hash;
                   5927:   if (tie(%hash,'GDBM_File',
                   5928: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5929: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5930:     foreach my $key (keys(%hash)) {
1.180     albertel 5931:       if ($key=~ /:$symb/) {
1.168     albertel 5932: 	delete($hash{$key});
                   5933:       }
                   5934:     }
                   5935:   }
                   5936: }
                   5937: 
1.167     albertel 5938: sub tmpstore {
1.168     albertel 5939:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5940: 
                   5941:   if (!$symb) {
                   5942:     $symb=&symbread();
1.620     albertel 5943:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5944:   }
                   5945:   $symb=escape($symb);
                   5946: 
                   5947:   if (!$namespace) {
                   5948:     # I don't think we would ever want to store this for a course.
                   5949:     # it seems this will only be used if we don't have a course.
1.620     albertel 5950:     #$namespace=$env{'request.course.id'};
1.168     albertel 5951:     #if (!$namespace) {
1.620     albertel 5952:       $namespace=$env{'request.state'};
1.168     albertel 5953:     #}
                   5954:   }
                   5955:   $namespace=~s/\//\_/g;
                   5956:   $namespace=~s/\W//g;
1.620     albertel 5957:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5958:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5959:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5960:       $stuname=&get_requestor_ip();
1.591     albertel 5961:   }
1.168     albertel 5962:   my $now=time;
                   5963:   my %hash;
1.1117    foxr     5964:   my $path=LONCAPA::tempdir();
1.168     albertel 5965:   if (tie(%hash,'GDBM_File',
                   5966: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5967: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5968:     $hash{"version:$symb"}++;
                   5969:     my $version=$hash{"version:$symb"};
                   5970:     my $allkeys=''; 
                   5971:     foreach my $key (keys(%$storehash)) {
                   5972:       $allkeys.=$key.':';
1.591     albertel 5973:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5974:     }
                   5975:     $hash{"$version:$symb:timestamp"}=$now;
                   5976:     $allkeys.='timestamp';
                   5977:     $hash{"$version:keys:$symb"}=$allkeys;
                   5978:     if (untie(%hash)) {
                   5979:       return 'ok';
                   5980:     } else {
                   5981:       return "error:$!";
                   5982:     }
                   5983:   } else {
                   5984:     return "error:$!";
                   5985:   }
                   5986: }
1.167     albertel 5987: 
1.168     albertel 5988: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5989: 
1.168     albertel 5990: sub tmprestore {
                   5991:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5992: 
1.168     albertel 5993:   if (!$symb) {
                   5994:     $symb=&symbread();
1.620     albertel 5995:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5996:   }
                   5997:   $symb=escape($symb);
                   5998: 
1.620     albertel 5999:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6000: 
1.620     albertel 6001:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6002:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6003:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6004:       $stuname=&get_requestor_ip();
1.591     albertel 6005:   }
1.168     albertel 6006:   my %returnhash;
                   6007:   $namespace=~s/\//\_/g;
                   6008:   $namespace=~s/\W//g;
                   6009:   my %hash;
1.1117    foxr     6010:   my $path=LONCAPA::tempdir();
1.168     albertel 6011:   if (tie(%hash,'GDBM_File',
                   6012: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6013: 	  &GDBM_READER(),0640)) {
1.168     albertel 6014:     my $version=$hash{"version:$symb"};
                   6015:     $returnhash{'version'}=$version;
                   6016:     my $scope;
                   6017:     for ($scope=1;$scope<=$version;$scope++) {
                   6018:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6019:       my @keys=split(/:/,$vkeys);
                   6020:       my $key;
                   6021:       $returnhash{"$scope:keys"}=$vkeys;
                   6022:       foreach $key (@keys) {
1.591     albertel 6023: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6024: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6025:       }
                   6026:     }
1.168     albertel 6027:     if (!(untie(%hash))) {
                   6028:       return "error:$!";
                   6029:     }
                   6030:   } else {
                   6031:     return "error:$!";
                   6032:   }
                   6033:   return %returnhash;
1.167     albertel 6034: }
                   6035: 
1.9       www      6036: # ----------------------------------------------------------------------- Store
                   6037: 
                   6038: sub store {
1.1172.2.64  raeburn  6039:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6040:     my $home='';
                   6041: 
1.168     albertel 6042:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6043: 
1.213     www      6044:     $symb=&symbclean($symb);
1.122     albertel 6045:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6046: 
1.620     albertel 6047:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6048:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6049: 
                   6050:     &devalidate($symb,$stuname,$domain);
1.109     www      6051: 
                   6052:     $symb=escape($symb);
1.187     www      6053:     if (!$namespace) { 
1.620     albertel 6054:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6055:           return ''; 
                   6056:        } 
                   6057:     }
1.620     albertel 6058:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6059: 
1.1172.2.138  raeburn  6060:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6061:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6062: 
1.12      www      6063:     my $namevalue='';
1.800     albertel 6064:     foreach my $key (keys(%$storehash)) {
                   6065:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6066:     }
1.12      www      6067:     $namevalue=~s/\&$//;
1.187     www      6068:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6069:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6070: }
                   6071: 
1.47      www      6072: # -------------------------------------------------------------- Critical Store
                   6073: 
                   6074: sub cstore {
1.1172.2.64  raeburn  6075:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6076:     my $home='';
                   6077: 
1.168     albertel 6078:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6079: 
1.213     www      6080:     $symb=&symbclean($symb);
1.122     albertel 6081:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6082: 
1.620     albertel 6083:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6084:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6085: 
                   6086:     &devalidate($symb,$stuname,$domain);
1.109     www      6087: 
                   6088:     $symb=escape($symb);
1.187     www      6089:     if (!$namespace) { 
1.620     albertel 6090:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6091:           return ''; 
                   6092:        } 
                   6093:     }
1.620     albertel 6094:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6095: 
1.1172.2.138  raeburn  6096:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6097:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6098: 
1.47      www      6099:     my $namevalue='';
1.800     albertel 6100:     foreach my $key (keys(%$storehash)) {
                   6101:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6102:     }
1.47      www      6103:     $namevalue=~s/\&$//;
1.187     www      6104:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6105:     return critical
1.1172.2.64  raeburn  6106:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6107: }
                   6108: 
1.9       www      6109: # --------------------------------------------------------------------- Restore
                   6110: 
                   6111: sub restore {
1.124     www      6112:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6113:     my $home='';
                   6114: 
1.168     albertel 6115:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6116: 
1.122     albertel 6117:     if (!$symb) {
1.1172.2.26  raeburn  6118:         return if ($namespace eq 'courserequests');
                   6119:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6120:     } else {
1.1172.2.26  raeburn  6121:         unless ($namespace eq 'courserequests') {
                   6122:             $symb=&escape(&symbclean($symb));
                   6123:         }
1.122     albertel 6124:     }
1.188     www      6125:     if (!$namespace) { 
1.620     albertel 6126:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6127:           return ''; 
                   6128:        } 
                   6129:     }
1.620     albertel 6130:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6131:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6132:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6133:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6134: 
1.12      www      6135:     my %returnhash=();
1.800     albertel 6136:     foreach my $line (split(/\&/,$answer)) {
                   6137: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6138:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6139:     }
1.75      www      6140:     my $version;
                   6141:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6142:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6143:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6144:        }
1.75      www      6145:     }
1.13      www      6146:     return %returnhash;
1.34      www      6147: }
                   6148: 
                   6149: # ---------------------------------------------------------- Course Description
1.1118    foxr     6150: #
                   6151: #  
1.34      www      6152: 
                   6153: sub coursedescription {
1.731     albertel 6154:     my ($courseid,$args)=@_;
1.34      www      6155:     $courseid=~s/^\///;
1.49      www      6156:     $courseid=~s/\_/\//g;
1.34      www      6157:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6158:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6159:     my $normalid=$cdomain.'_'.$cnum;
                   6160:     # need to always cache even if we get errors otherwise we keep 
                   6161:     # trying and trying and trying to get the course description.
                   6162:     my %envhash=();
                   6163:     my %returnhash=();
1.731     albertel 6164:     
                   6165:     my $expiretime=600;
                   6166:     if ($env{'request.course.id'} eq $normalid) {
                   6167: 	$expiretime=120;
                   6168:     }
                   6169: 
                   6170:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6171:     if (!$args->{'freshen_cache'}
                   6172: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6173: 	foreach my $key (keys(%env)) {
                   6174: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6175: 	    my ($setting) = $1;
                   6176: 	    $returnhash{$setting} = $env{$key};
                   6177: 	}
                   6178: 	return %returnhash;
                   6179:     }
                   6180: 
1.1118    foxr     6181:     # get the data again
                   6182: 
1.731     albertel 6183:     if (!$args->{'one_time'}) {
                   6184: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6185:     }
1.811     albertel 6186: 
1.34      www      6187:     if ($chome ne 'no_host') {
1.302     albertel 6188:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6189:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6190: 	   my $username = $env{'user.name'}; # Defult username
                   6191: 	   if(defined $args->{'user'}) {
                   6192: 	       $username = $args->{'user'};
                   6193: 	   }
1.129     albertel 6194:            $returnhash{'home'}= $chome;
                   6195: 	   $returnhash{'domain'} = $cdomain;
                   6196: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6197:            if (!defined($returnhash{'type'})) {
                   6198:                $returnhash{'type'} = 'Course';
                   6199:            }
1.130     albertel 6200:            while (my ($name,$value) = each %returnhash) {
1.53      www      6201:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6202:            }
1.270     www      6203:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6204:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6205: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6206:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6207:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6208:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6209:        }
                   6210:     }
1.731     albertel 6211:     if (!$args->{'one_time'}) {
1.949     raeburn  6212: 	&appenv(\%envhash);
1.731     albertel 6213:     }
1.302     albertel 6214:     return %returnhash;
1.461     www      6215: }
                   6216: 
1.1080    raeburn  6217: sub update_released_required {
                   6218:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6219:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6220:         $cid = $env{'request.course.id'};
                   6221:         $cdom = $env{'course.'.$cid.'.domain'};
                   6222:         $cnum = $env{'course.'.$cid.'.num'};
                   6223:         $chome = $env{'course.'.$cid.'.home'};
                   6224:     }
                   6225:     if ($needsrelease) {
                   6226:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6227:         my $needsupdate;
                   6228:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6229:             $needsupdate = 1;
                   6230:         } else {
                   6231:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6232:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6233:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6234:                 $needsupdate = 1;
                   6235:             }
                   6236:         }
                   6237:         if ($needsupdate) {
                   6238:             my %needshash = (
                   6239:                              'internal.releaserequired' => $needsrelease,
                   6240:                             );
                   6241:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6242:             if ($putresult eq 'ok') {
                   6243:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6244:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6245:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6246:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6247:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6248:                 }
                   6249:             }
                   6250:         }
                   6251:     }
                   6252:     return;
                   6253: }
                   6254: 
1.461     www      6255: # -------------------------------------------------See if a user is privileged
                   6256: 
                   6257: sub privileged {
1.1172.2.23  raeburn  6258:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6259:     my $now = time;
1.1172.2.23  raeburn  6260:     my $roles;
                   6261:     if (ref($possroles) eq 'ARRAY') {
                   6262:         $roles = $possroles;
                   6263:     } else {
                   6264:         $roles = ['dc','su'];
                   6265:     }
                   6266:     if (ref($possdomains) eq 'ARRAY') {
                   6267:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6268:         foreach my $dom (@{$possdomains}) {
                   6269:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6270:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6271:                 foreach my $role (@{$roles}) {
                   6272:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6273:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6274:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6275:                             return 1 unless (($end && $end < $now) ||
                   6276:                                              ($start && $start > $now));
                   6277:                         }
                   6278:                     }
                   6279:                 }
                   6280:             }
                   6281:         }
                   6282:     } else {
                   6283:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6284:         my $now = time;
1.1170    droeschl 6285: 
1.1172.2.58  raeburn  6286:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6287:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6288:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6289:                 return 1 unless ($tend && $tend < $now)
                   6290:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6291:             }
1.1172.2.23  raeburn  6292:         }
                   6293:     }
1.461     www      6294:     return 0;
1.9       www      6295: }
1.1       albertel 6296: 
1.1172.2.23  raeburn  6297: sub privileged_by_domain {
                   6298:     my ($domains,$roles) = @_;
                   6299:     my %privileged = ();
                   6300:     my $cachetime = 60*60*24;
                   6301:     my $now = time;
                   6302:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6303:         return %privileged;
                   6304:     }
                   6305:     foreach my $dom (@{$domains}) {
                   6306:         next if (ref($privileged{$dom}) eq 'HASH');
                   6307:         my $needroles;
                   6308:         foreach my $role (@{$roles}) {
                   6309:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6310:             if (defined($cached)) {
                   6311:                 if (ref($result) eq 'HASH') {
                   6312:                     $privileged{$dom}{$role} = $result;
                   6313:                 }
                   6314:             } else {
                   6315:                 $needroles = 1;
                   6316:             }
                   6317:         }
                   6318:         if ($needroles) {
                   6319:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6320:             $privileged{$dom} = {};
                   6321:             foreach my $server (keys(%dompersonnel)) {
                   6322:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6323:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6324:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6325:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6326:                         next if ($end && $end < $now);
                   6327:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6328:                             $dompersonnel{$server}{$item};
                   6329:                     }
                   6330:                 }
                   6331:             }
                   6332:             if (ref($privileged{$dom}) eq 'HASH') {
                   6333:                 foreach my $role (@{$roles}) {
                   6334:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6335:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6336:                     } else {
                   6337:                         my %hash = ();
                   6338:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6339:                     }
                   6340:                 }
                   6341:             }
                   6342:         }
                   6343:     }
                   6344:     return %privileged;
                   6345: }
                   6346: 
1.103     harris41 6347: # -------------------------------------------------------- Get user privileges
1.11      www      6348: 
                   6349: sub rolesinit {
1.1169    droeschl 6350:     my ($domain, $username) = @_;
                   6351:     my %userroles = ('user.login.time' => time);
                   6352:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6353: 
                   6354:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6355:     # also, blocking can be triggered by an activating timer
                   6356:     # it's saved in the user's %env.
                   6357:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6358:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6359:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6360:         %timerintchk, %timerintenv);
                   6361: 
1.1162    raeburn  6362:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6363:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6364:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6365:     }
1.1169    droeschl 6366: 
1.1162    raeburn  6367:     foreach my $key (keys(%timerinterval)) {
                   6368:         my ($cid,$rest) = split(/\0/,$key);
                   6369:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6370:     }
1.1169    droeschl 6371: 
1.11      www      6372:     my %allroles=();
1.1162    raeburn  6373:     my %allgroups=();
1.11      www      6374: 
1.1172.2.58  raeburn  6375:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6376:         my $role = $rolesdump{$area};
                   6377:         $area =~ s/\_\w\w$//;
                   6378: 
                   6379:         my ($trole, $tend, $tstart, $group_privs);
                   6380: 
                   6381:         if ($role =~ /^cr/) {
                   6382:         # Custom role, defined by a user 
                   6383:         # e.g., user.role.cr/msu/smith/mynewrole
                   6384:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6385:                 $trole = $1;
                   6386:                 ($tend, $tstart) = split('_', $2);
                   6387:             } else {
                   6388:                 $trole = $role;
                   6389:             }
                   6390:         } elsif ($role =~ m|^gr/|) {
                   6391:         # Role of member in a group, defined within a course/community
                   6392:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6393:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6394:             next if $tstart eq '-1';
                   6395:             ($trole, $group_privs) = split(/\//, $trole);
                   6396:             $group_privs = &unescape($group_privs);
                   6397:         } else {
                   6398:         # Just a normal role, defined in roles.tab
                   6399:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6400:         }
                   6401: 
                   6402:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6403:                  $username);
                   6404:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6405: 
                   6406:         # role expired or not available yet?
                   6407:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6408:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6409: 
                   6410:         next if $area eq '' or $trole eq '';
                   6411: 
                   6412:         my $spec = "$trole.$area";
                   6413:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6414: 
                   6415:         if ($trole =~ /^cr\//) {
                   6416:         # Custom role, defined by a user
                   6417:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6418:         } elsif ($trole eq 'gr') {
                   6419:         # Role of a member in a group, defined within a course/community
                   6420:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6421:             next;
                   6422:         } else {
                   6423:         # Normal role, defined in roles.tab
                   6424:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6425:         }
                   6426: 
                   6427:         my $cid = $tdomain.'_'.$trest;
                   6428:         unless ($firstaccchk{$cid}) {
                   6429:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6430:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6431:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6432:                         $coursetimerstarts{$cid}{$item}; 
                   6433:                 }
                   6434:             }
                   6435:             $firstaccchk{$cid} = 1;
                   6436:         }
                   6437:         unless ($timerintchk{$cid}) {
                   6438:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6439:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6440:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6441:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6442:                 }
1.12      www      6443:             }
1.1169    droeschl 6444:             $timerintchk{$cid} = 1;
1.191     harris41 6445:         }
1.11      www      6446:     }
1.1169    droeschl 6447: 
1.1172.2.91  raeburn  6448:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6449:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6450:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6451:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6452: 
1.1162    raeburn  6453:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6454: }
                   6455: 
1.567     raeburn  6456: sub set_arearole {
1.1172.2.19  raeburn  6457:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6458:     unless ($nolog) {
1.567     raeburn  6459: # log the associated role with the area
1.1172.2.19  raeburn  6460:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6461:     }
1.743     albertel 6462:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6463: }
                   6464: 
                   6465: sub custom_roleprivs {
                   6466:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6467:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6468:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6469:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6470:         my ($rdummy,$roledef)=
                   6471:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6472:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6473:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6474:             if (defined($syspriv)) {
1.1043    raeburn  6475:                 if ($trest =~ /^$match_community$/) {
                   6476:                     $syspriv =~ s/bre\&S//; 
                   6477:                 }
1.567     raeburn  6478:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6479:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6480:             }
                   6481:             if ($tdomain ne '') {
                   6482:                 if (defined($dompriv)) {
                   6483:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6484:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6485:                 }
                   6486:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6487:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6488:                         my $rolename = $1;
                   6489:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6490:                     }
1.567     raeburn  6491:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6492:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6493:                 }
                   6494:             }
                   6495:         }
                   6496:     }
                   6497: }
                   6498: 
1.1172.2.89  raeburn  6499: sub course_adhocrole_privs {
                   6500:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6501:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6502:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6503:         my (%currprivs,%storeprivs);
                   6504:         foreach my $item (split(/:/,$coursepriv)) {
                   6505:             my ($priv,$restrict) = split(/\&/,$item);
                   6506:             $currprivs{$priv} = $restrict;
                   6507:         }
                   6508:         my (%possadd,%possremove,%full);
                   6509:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6510:             my ($priv,$restrict)=split(/\&/,$item);
                   6511:             $full{$priv} = $restrict;
                   6512:         }
                   6513:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6514:              next if ($item eq '');
                   6515:              my ($rule,$rest) = split(/=/,$item);
                   6516:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6517:              foreach my $priv (split(/:/,$rest)) {
                   6518:                  if ($priv ne '') {
                   6519:                      if ($rule eq 'off') {
                   6520:                          $possremove{$priv} = 1;
                   6521:                      } else {
                   6522:                          $possadd{$priv} = 1;
                   6523:                      }
                   6524:                  }
                   6525:              }
                   6526:          }
                   6527:          foreach my $priv (sort(keys(%full))) {
                   6528:              if (exists($currprivs{$priv})) {
                   6529:                  unless (exists($possremove{$priv})) {
                   6530:                      $storeprivs{$priv} = $currprivs{$priv};
                   6531:                  }
                   6532:              } elsif (exists($possadd{$priv})) {
                   6533:                  $storeprivs{$priv} = $full{$priv};
                   6534:              }
                   6535:          }
                   6536:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6537:      }
                   6538:      return $coursepriv;
                   6539: }
                   6540: 
1.678     raeburn  6541: sub group_roleprivs {
                   6542:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6543:     my $access = 1;
                   6544:     my $now = time;
                   6545:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6546:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6547:     if ($access) {
1.811     albertel 6548:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6549:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6550:     }
                   6551: }
1.567     raeburn  6552: 
                   6553: sub standard_roleprivs {
                   6554:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6555:     if (defined($pr{$trole.':s'})) {
                   6556:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6557:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6558:     }
                   6559:     if ($tdomain ne '') {
                   6560:         if (defined($pr{$trole.':d'})) {
                   6561:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6562:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6563:         }
                   6564:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6565:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6566:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6567:         }
                   6568:     }
                   6569: }
                   6570: 
                   6571: sub set_userprivs {
1.1064    raeburn  6572:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6573:     my $author=0;
                   6574:     my $adv=0;
1.1172.2.91  raeburn  6575:     my $rar=0;
1.678     raeburn  6576:     my %grouproles = ();
                   6577:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6578:         my @groupkeys; 
1.1000    raeburn  6579:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6580:             push(@groupkeys,$role);
                   6581:         }
                   6582:         if (ref($groups_roles) eq 'HASH') {
                   6583:             foreach my $key (keys(%{$groups_roles})) {
                   6584:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6585:                     push(@groupkeys,$key);
                   6586:                 }
                   6587:             }
                   6588:         }
                   6589:         if (@groupkeys > 0) {
                   6590:             foreach my $role (@groupkeys) {
                   6591:                 my ($trole,$area,$sec,$extendedarea);
                   6592:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6593:                     $trole = $1;
                   6594:                     $area = $2;
                   6595:                     $sec = $3;
                   6596:                     $extendedarea = $area.$sec;
                   6597:                     if (exists($$allgroups{$area})) {
                   6598:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6599:                             my $spec = $trole.'.'.$extendedarea;
                   6600:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6601:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6602:                         }
1.678     raeburn  6603:                     }
                   6604:                 }
                   6605:             }
                   6606:         }
                   6607:     }
1.800     albertel 6608:     foreach my $group (keys(%grouproles)) {
                   6609:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6610:     }
1.800     albertel 6611:     foreach my $role (keys(%{$allroles})) {
                   6612:         my %thesepriv;
1.941     raeburn  6613:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6614:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6615:             if ($item ne '') {
                   6616:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6617:                 if ($restrictions eq '') {
                   6618:                     $thesepriv{$privilege}='F';
                   6619:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6620:                     $thesepriv{$privilege}.=$restrictions;
                   6621:                 }
                   6622:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6623:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6624:             }
                   6625:         }
                   6626:         my $thesestr='';
1.1104    raeburn  6627:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6628: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6629: 	}
                   6630:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6631:     }
1.1172.2.91  raeburn  6632:     return ($author,$adv,$rar);
1.567     raeburn  6633: }
                   6634: 
1.994     raeburn  6635: sub role_status {
1.1104    raeburn  6636:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6637:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6638:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6639:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6640:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6641:             $$where = '/'.$two;
1.994     raeburn  6642:             $$trolecode=$$role.'.'.$$where;
                   6643:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6644:             $$tstatus='is';
1.1104    raeburn  6645:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6646:                 $$tstatus='future';
1.1034    raeburn  6647:                 if ($$tstart<$now) {
                   6648:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6649:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6650:                             my (%allroles,%allgroups,$group_privs,
                   6651:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6652:                             my %userroles = (
                   6653:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6654:                             );
1.1064    raeburn  6655:                             @rolecodes = ('cm'); 
1.1002    raeburn  6656:                             my $spec=$$role.'.'.$$where;
                   6657:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6658:                             if ($$role =~ /^cr\//) {
                   6659:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6660:                                 push(@rolecodes,'cr');
1.1002    raeburn  6661:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6662:                                 push(@rolecodes,$$role);
1.1002    raeburn  6663:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6664:                                                     $env{'user.name'});
1.1064    raeburn  6665:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6666:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6667:                                 $group_privs = &unescape($group_privs);
                   6668:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6669:                                 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  6670:                                 &get_groups_roles($tdomain,$trest,
                   6671:                                                   \%course_roles,\@rolecodes,
                   6672:                                                   \%groups_roles);
1.1002    raeburn  6673:                             } else {
1.1064    raeburn  6674:                                 push(@rolecodes,$$role);
1.1002    raeburn  6675:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6676:                             }
1.1172.2.91  raeburn  6677:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6678:                                                                    \%groups_roles);
1.1064    raeburn  6679:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6680:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6681:                         }
                   6682:                     }
1.1034    raeburn  6683:                     $$tstatus = 'is';
1.1002    raeburn  6684:                 }
1.994     raeburn  6685:             }
                   6686:             if ($$tend) {
1.1104    raeburn  6687:                 if ($$tend<$update) {
1.994     raeburn  6688:                     $$tstatus='expired';
                   6689:                 } elsif ($$tend<$now) {
                   6690:                     $$tstatus='will_not';
                   6691:                 }
                   6692:             }
                   6693:         }
                   6694:     }
                   6695: }
                   6696: 
1.1104    raeburn  6697: sub get_groups_roles {
                   6698:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6699:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6700:                   (ref($rolecodes) eq 'ARRAY') && 
                   6701:                   (ref($groups_roles) eq 'HASH')); 
                   6702:     if (keys(%{$cdom_courseroles}) > 0) {
                   6703:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6704:         if ($cdom ne '' && $cnum ne '') {
                   6705:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6706:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6707:                     my $crsrole = $1;
                   6708:                     my $crssec = $2;
                   6709:                     if ($crsrole =~ /^cr/) {
                   6710:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6711:                             push(@{$rolecodes},'cr');
                   6712:                         }
                   6713:                     } else {
                   6714:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6715:                             push(@{$rolecodes},$crsrole);
                   6716:                         }
                   6717:                     }
                   6718:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6719:                     if ($crssec ne '') {
                   6720:                         $rolekey .= "/$crssec";
                   6721:                     }
                   6722:                     $rolekey .= './';
                   6723:                     $groups_roles->{$rolekey} = $rolecodes;
                   6724:                 }
                   6725:             }
                   6726:         }
                   6727:     }
                   6728:     return;
                   6729: }
                   6730: 
                   6731: sub delete_env_groupprivs {
                   6732:     my ($where,$courseroles,$possroles) = @_;
                   6733:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6734:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6735:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6736:         %{$courseroles->{$udom}} =
                   6737:             &get_my_roles('','','userroles',['active'],
                   6738:                           $possroles,[$udom],1);
                   6739:     }
                   6740:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6741:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6742:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6743:             my $area = '/'.$cdom.'/'.$cnum;
                   6744:             my $privkey = "user.priv.$crsrole.$area";
                   6745:             if ($crssec ne '') {
                   6746:                 $privkey .= '/'.$crssec;
                   6747:             }
                   6748:             $privkey .= ".$area/$group";
                   6749:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6750:         }
                   6751:     }
                   6752:     return;
                   6753: }
                   6754: 
1.994     raeburn  6755: sub check_adhoc_privs {
1.1172.2.86  raeburn  6756:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6757:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6758:     if ($sec) {
                   6759:         $cckey .= '/'.$sec;
                   6760:     }
1.1172.2.9  raeburn  6761:     my $setprivs;
1.994     raeburn  6762:     if ($env{$cckey}) {
                   6763:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6764:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6765:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6766:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6767:             $setprivs = 1;
1.994     raeburn  6768:         }
                   6769:     } else {
1.1172.2.87  raeburn  6770:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6771:         $setprivs = 1;
1.994     raeburn  6772:     }
1.1172.2.9  raeburn  6773:     return $setprivs;
1.994     raeburn  6774: }
                   6775: 
                   6776: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6777: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6778:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6779:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6780:     if ($sec ne '') {
                   6781:         $area .= '/'.$sec;
                   6782:     }
1.994     raeburn  6783:     my $spec = $role.'.'.$area;
                   6784:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6785:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6786:     my %rolehash = ();
1.1172.2.89  raeburn  6787:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6788:         my $rolename = $1;
1.1172.2.84  raeburn  6789:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6790:         my %domdef = &get_domain_defaults($dcdom);
                   6791:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6792:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6793:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6794:             }
                   6795:         }
1.1172.2.84  raeburn  6796:     } else {
                   6797:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6798:     }
1.1172.2.91  raeburn  6799:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6800:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6801:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6802:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6803:         &appenv( {'request.role'        => $spec,
                   6804:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6805:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6806:                  }
                   6807:                );
                   6808:         my $tadv=0;
                   6809:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6810:         &appenv({'request.role.adv'    => $tadv});
                   6811:     }
1.994     raeburn  6812: }
                   6813: 
1.12      www      6814: # --------------------------------------------------------------- get interface
                   6815: 
                   6816: sub get {
1.131     albertel 6817:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6818:    my $items='';
1.800     albertel 6819:    foreach my $item (@$storearr) {
                   6820:        $items.=&escape($item).'&';
1.191     harris41 6821:    }
1.12      www      6822:    $items=~s/\&$//;
1.620     albertel 6823:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6824:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6825:    my $uhome=&homeserver($uname,$udomain);
                   6826: 
1.133     albertel 6827:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6828:    my @pairs=split(/\&/,$rep);
1.273     albertel 6829:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6830:      return @pairs;
                   6831:    }
1.15      www      6832:    my %returnhash=();
1.42      www      6833:    my $i=0;
1.800     albertel 6834:    foreach my $item (@$storearr) {
                   6835:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6836:       $i++;
1.191     harris41 6837:    }
1.15      www      6838:    return %returnhash;
1.27      www      6839: }
                   6840: 
                   6841: # --------------------------------------------------------------- del interface
                   6842: 
                   6843: sub del {
1.133     albertel 6844:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6845:    my $items='';
1.800     albertel 6846:    foreach my $item (@$storearr) {
                   6847:        $items.=&escape($item).'&';
1.191     harris41 6848:    }
1.984     neumanie 6849: 
1.27      www      6850:    $items=~s/\&$//;
1.620     albertel 6851:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6852:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6853:    my $uhome=&homeserver($uname,$udomain);
                   6854:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6855: }
                   6856: 
                   6857: # -------------------------------------------------------------- dump interface
                   6858: 
1.1172.2.22  raeburn  6859: sub unserialize {
                   6860:     my ($rep, $escapedkeys) = @_;
                   6861: 
                   6862:     return {} if $rep =~ /^error/;
                   6863: 
                   6864:     my %returnhash=();
                   6865:     foreach my $item (split(/\&/,$rep)) {
                   6866:         my ($key, $value) = split(/=/, $item, 2);
                   6867:         $key = unescape($key) unless $escapedkeys;
                   6868:         next if $key =~ /^error: 2 /;
                   6869:         $returnhash{$key} = &thaw_unescape($value);
                   6870:     }
                   6871:     return \%returnhash;
                   6872: }
                   6873: 
                   6874: # see Lond::dump_with_regexp
                   6875: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6876: sub dump {
1.1172.2.22  raeburn  6877:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6878:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6879:     if (!$uname) { $uname=$env{'user.name'}; }
                   6880:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6881: 
1.1172.2.55  raeburn  6882:     if ($regexp) {
                   6883:         $regexp=&escape($regexp);
                   6884:     } else {
                   6885:         $regexp='.';
                   6886:     }
1.1172.2.22  raeburn  6887:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6888:         # user is hosted on this machine
1.1172.2.55  raeburn  6889:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6890:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6891:         return %{&unserialize($reply, $escapedkeys)};
                   6892:     }
1.1166    raeburn  6893:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6894:     my @pairs=split(/\&/,$rep);
                   6895:     my %returnhash=();
1.1098    foxr     6896:     if (!($rep =~ /^error/ )) {
                   6897: 	foreach my $item (@pairs) {
                   6898: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6899:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6900: 	    next if ($key =~ /^error: 2 /);
                   6901: 	    $returnhash{$key}=&thaw_unescape($value);
                   6902: 	}
1.755     albertel 6903:     }
                   6904:     return %returnhash;
1.407     www      6905: }
                   6906: 
1.1098    foxr     6907: 
1.717     albertel 6908: # --------------------------------------------------------- dumpstore interface
                   6909: 
                   6910: sub dumpstore {
                   6911:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6912:    # same as dump but keys must be escaped. They may contain colon separated
                   6913:    # lists of values that may themself contain colons (e.g. symbs).
                   6914:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6915: }
                   6916: 
1.407     www      6917: # -------------------------------------------------------------- keys interface
                   6918: 
                   6919: sub getkeys {
                   6920:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6921:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6922:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6923:    my $uhome=&homeserver($uname,$udomain);
                   6924:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6925:    my @keyarray=();
1.800     albertel 6926:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6927:       next if ($key =~ /^error: 2 /);
1.800     albertel 6928:       push(@keyarray,&unescape($key));
1.407     www      6929:    }
                   6930:    return @keyarray;
1.318     matthew  6931: }
                   6932: 
1.319     matthew  6933: # --------------------------------------------------------------- currentdump
                   6934: sub currentdump {
1.328     matthew  6935:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6936:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6937:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6938:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6939:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6940:    my $rep;
                   6941: 
                   6942:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6943:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6944:                    $courseid)));
                   6945:    } else {
                   6946:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6947:    }
                   6948: 
1.318     matthew  6949:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6950:    #
1.318     matthew  6951:    my %returnhash=();
1.319     matthew  6952:    #
                   6953:    if ($rep eq "unknown_cmd") { 
                   6954:        # an old lond will not know currentdump
                   6955:        # Do a dump and make it look like a currentdump
1.822     albertel 6956:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6957:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6958:        my %hash = @tmp;
                   6959:        @tmp=();
1.424     matthew  6960:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6961:    } else {
                   6962:        my @pairs=split(/\&/,$rep);
1.800     albertel 6963:        foreach my $pair (@pairs) {
                   6964:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6965:            my ($symb,$param) = split(/:/,$key);
                   6966:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6967:                                                         &thaw_unescape($value);
1.319     matthew  6968:        }
1.191     harris41 6969:    }
1.12      www      6970:    return %returnhash;
1.424     matthew  6971: }
                   6972: 
                   6973: sub convert_dump_to_currentdump{
                   6974:     my %hash = %{shift()};
                   6975:     my %returnhash;
                   6976:     # Code ripped from lond, essentially.  The only difference
                   6977:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6978:     # we might run in to problems with parameter names =~ /^v\./
                   6979:     while (my ($key,$value) = each(%hash)) {
                   6980:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6981: 	$symb  = &unescape($symb);
                   6982: 	$param = &unescape($param);
1.424     matthew  6983:         next if ($v eq 'version' || $symb eq 'keys');
                   6984:         next if (exists($returnhash{$symb}) &&
                   6985:                  exists($returnhash{$symb}->{$param}) &&
                   6986:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6987:         $returnhash{$symb}->{$param}=$value;
                   6988:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6989:     }
                   6990:     #
                   6991:     # Remove all of the keys in the hashes which keep track of
                   6992:     # the version of the parameter.
                   6993:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6994:         # use a foreach because we are going to delete from the hash.
                   6995:         foreach my $key (keys(%$param_hash)) {
                   6996:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6997:         }
                   6998:     }
                   6999:     return \%returnhash;
1.12      www      7000: }
                   7001: 
1.627     albertel 7002: # ------------------------------------------------------ critical inc interface
                   7003: 
                   7004: sub cinc {
                   7005:     return &inc(@_,'critical');
                   7006: }
                   7007: 
1.449     matthew  7008: # --------------------------------------------------------------- inc interface
                   7009: 
                   7010: sub inc {
1.627     albertel 7011:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7013:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7014:     my $uhome=&homeserver($uname,$udomain);
                   7015:     my $items='';
                   7016:     if (! ref($store)) {
                   7017:         # got a single value, so use that instead
                   7018:         $items = &escape($store).'=&';
                   7019:     } elsif (ref($store) eq 'SCALAR') {
                   7020:         $items = &escape($$store).'=&';        
                   7021:     } elsif (ref($store) eq 'ARRAY') {
                   7022:         $items = join('=&',map {&escape($_);} @{$store});
                   7023:     } elsif (ref($store) eq 'HASH') {
                   7024:         while (my($key,$value) = each(%{$store})) {
                   7025:             $items.= &escape($key).'='.&escape($value).'&';
                   7026:         }
                   7027:     }
                   7028:     $items=~s/\&$//;
1.627     albertel 7029:     if ($critical) {
                   7030: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7031:     } else {
                   7032: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7033:     }
1.449     matthew  7034: }
                   7035: 
1.12      www      7036: # --------------------------------------------------------------- put interface
                   7037: 
                   7038: sub put {
1.134     albertel 7039:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7040:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7041:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7042:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7043:    my $items='';
1.800     albertel 7044:    foreach my $item (keys(%$storehash)) {
                   7045:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7046:    }
1.12      www      7047:    $items=~s/\&$//;
1.134     albertel 7048:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7049: }
                   7050: 
1.631     albertel 7051: # ------------------------------------------------------------ newput interface
                   7052: 
                   7053: sub newput {
                   7054:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7055:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7056:    if (!$uname) { $uname=$env{'user.name'}; }
                   7057:    my $uhome=&homeserver($uname,$udomain);
                   7058:    my $items='';
                   7059:    foreach my $key (keys(%$storehash)) {
                   7060:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7061:    }
                   7062:    $items=~s/\&$//;
                   7063:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7064: }
                   7065: 
                   7066: # ---------------------------------------------------------  putstore interface
                   7067: 
1.524     raeburn  7068: sub putstore {
1.1172.2.59  raeburn  7069:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7071:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7072:    my $uhome=&homeserver($uname,$udomain);
                   7073:    my $items='';
1.715     albertel 7074:    foreach my $key (keys(%$storehash)) {
                   7075:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7076:    }
1.715     albertel 7077:    $items=~s/\&$//;
1.716     albertel 7078:    my $esc_symb=&escape($symb);
                   7079:    my $esc_v=&escape($version);
1.715     albertel 7080:    my $reply =
1.716     albertel 7081:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7082: 	      $uhome);
1.1172.2.59  raeburn  7083:    if (($tolog) && ($reply eq 'ok')) {
                   7084:        my $namevalue='';
                   7085:        foreach my $key (keys(%{$storehash})) {
                   7086:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7087:        }
1.1172.2.134  raeburn  7088:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7089:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7090:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7091:                      '&version='.$esc_v.
                   7092:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7093:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7094:    }
1.715     albertel 7095:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7096:        # gfall back to way things use to be done
1.715     albertel 7097:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7098: 			    $uname);
1.524     raeburn  7099:    }
1.715     albertel 7100:    return $reply;
                   7101: }
                   7102: 
                   7103: sub old_putstore {
1.716     albertel 7104:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7105:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7106:     if (!$uname) { $uname=$env{'user.name'}; }
                   7107:     my $uhome=&homeserver($uname,$udomain);
                   7108:     my %newstorehash;
1.800     albertel 7109:     foreach my $item (keys(%$storehash)) {
                   7110: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7111: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7112:     }
                   7113:     my $items='';
                   7114:     my %allitems = ();
1.800     albertel 7115:     foreach my $item (keys(%newstorehash)) {
                   7116: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7117: 	    my $key = $1.':keys:'.$2;
                   7118: 	    $allitems{$key} .= $3.':';
                   7119: 	}
1.800     albertel 7120: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7121:     }
1.800     albertel 7122:     foreach my $item (keys(%allitems)) {
                   7123: 	$allitems{$item} =~ s/\:$//;
                   7124: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7125:     }
                   7126:     $items=~s/\&$//;
                   7127:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7128: }
                   7129: 
1.47      www      7130: # ------------------------------------------------------ critical put interface
                   7131: 
                   7132: sub cput {
1.134     albertel 7133:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7134:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7135:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7136:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7137:    my $items='';
1.800     albertel 7138:    foreach my $item (keys(%$storehash)) {
                   7139:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7140:    }
1.47      www      7141:    $items=~s/\&$//;
1.134     albertel 7142:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7143: }
                   7144: 
                   7145: # -------------------------------------------------------------- eget interface
                   7146: 
                   7147: sub eget {
1.133     albertel 7148:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7149:    my $items='';
1.800     albertel 7150:    foreach my $item (@$storearr) {
                   7151:        $items.=&escape($item).'&';
1.191     harris41 7152:    }
1.12      www      7153:    $items=~s/\&$//;
1.620     albertel 7154:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7155:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7156:    my $uhome=&homeserver($uname,$udomain);
                   7157:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7158:    my @pairs=split(/\&/,$rep);
                   7159:    my %returnhash=();
1.42      www      7160:    my $i=0;
1.800     albertel 7161:    foreach my $item (@$storearr) {
                   7162:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7163:       $i++;
1.191     harris41 7164:    }
1.12      www      7165:    return %returnhash;
                   7166: }
                   7167: 
1.667     albertel 7168: # ------------------------------------------------------------ tmpput interface
                   7169: sub tmpput {
1.802     raeburn  7170:     my ($storehash,$server,$context)=@_;
1.667     albertel 7171:     my $items='';
1.800     albertel 7172:     foreach my $item (keys(%$storehash)) {
                   7173: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7174:     }
                   7175:     $items=~s/\&$//;
1.802     raeburn  7176:     if (defined($context)) {
                   7177:         $items .= ':'.&escape($context);
                   7178:     }
1.667     albertel 7179:     return &reply("tmpput:$items",$server);
                   7180: }
                   7181: 
                   7182: # ------------------------------------------------------------ tmpget interface
                   7183: sub tmpget {
1.688     albertel 7184:     my ($token,$server)=@_;
                   7185:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7186:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7187:     my %returnhash;
1.1172.2.85  raeburn  7188:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7189:         return %returnhash;
                   7190:     }
1.667     albertel 7191:     foreach my $item (split(/\&/,$rep)) {
                   7192: 	my ($key,$value)=split(/=/,$item);
                   7193: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7194:     }
                   7195:     return %returnhash;
                   7196: }
                   7197: 
1.1113    raeburn  7198: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7199: sub tmpdel {
                   7200:     my ($token,$server)=@_;
                   7201:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7202:     return &reply("tmpdel:$token",$server);
                   7203: }
                   7204: 
1.1172.2.13  raeburn  7205: # ------------------------------------------------------------ get_timebased_id
                   7206: 
                   7207: sub get_timebased_id {
                   7208:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7209:         $maxtries) = @_;
                   7210:     my ($newid,$error,$dellock);
                   7211:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7212:         return ('','ok','invalid call to get suffix');
                   7213:     }
                   7214: 
                   7215: # set defaults for any optional args for which values were not supplied
                   7216:     if ($who eq '') {
                   7217:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7218:     }
                   7219:     if (!$locktries) {
                   7220:         $locktries = 3;
                   7221:     }
                   7222:     if (!$maxtries) {
                   7223:         $maxtries = 10;
                   7224:     }
                   7225: 
                   7226:     if (($cdom eq '') || ($cnum eq '')) {
                   7227:         if ($env{'request.course.id'}) {
                   7228:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7229:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7230:         }
                   7231:         if (($cdom eq '') || ($cnum eq '')) {
                   7232:             return ('','ok','call to get suffix not in course context');
                   7233:         }
                   7234:     }
                   7235: 
                   7236: # construct locking item
                   7237:     my $lockhash = {
                   7238:                       $prefix."\0".'locked_'.$keyid => $who,
                   7239:                    };
                   7240:     my $tries = 0;
                   7241: 
                   7242: # attempt to get lock on nohist_$namespace file
                   7243:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7244:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7245:         $tries ++;
                   7246:         sleep 1;
                   7247:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7248:     }
                   7249: 
                   7250: # attempt to get unique identifier, based on current timestamp
                   7251:     if ($gotlock eq 'ok') {
                   7252:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7253:         my $id = time;
                   7254:         $newid = $id;
1.1172.2.56  raeburn  7255:         if ($idtype eq 'addcode') {
                   7256:             $newid .= &sixnum_code();
                   7257:         }
1.1172.2.13  raeburn  7258:         my $idtries = 0;
                   7259:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7260:             if ($idtype eq 'concat') {
                   7261:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7262:             } elsif ($idtype eq 'addcode') {
                   7263:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7264:             } else {
                   7265:                 $newid ++;
                   7266:             }
                   7267:             $idtries ++;
                   7268:         }
                   7269:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7270:             my %new_item =  (
                   7271:                               $prefix."\0".$newid => $who,
                   7272:                             );
                   7273:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7274:                                                  $cdom,$cnum);
                   7275:             if ($putresult ne 'ok') {
                   7276:                 undef($newid);
                   7277:                 $error = 'error saving new item: '.$putresult;
                   7278:             }
                   7279:         } else {
1.1172.2.56  raeburn  7280:              undef($newid);
1.1172.2.13  raeburn  7281:              $error = ('error: no unique suffix available for the new item ');
                   7282:         }
                   7283: #  remove lock
                   7284:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7285:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7286:     } else {
                   7287:         $error = "error: could not obtain lockfile\n";
                   7288:         $dellock = 'ok';
1.1172.2.58  raeburn  7289:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7290:             $dellock = 'nolock';
                   7291:         }
1.1172.2.13  raeburn  7292:     }
                   7293:     return ($newid,$dellock,$error);
                   7294: }
                   7295: 
1.1172.2.56  raeburn  7296: sub sixnum_code {
                   7297:     my $code;
                   7298:     for (0..6) {
                   7299:         $code .= int( rand(9) );
                   7300:     }
                   7301:     return $code;
                   7302: }
                   7303: 
1.765     albertel 7304: # -------------------------------------------------- portfolio access checking
                   7305: 
                   7306: sub portfolio_access {
1.1172.2.77  raeburn  7307:     my ($requrl,$clientip) = @_;
1.765     albertel 7308:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7309:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7310:     if ($result) {
                   7311:         my %setters;
                   7312:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7313:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7314:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7315:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7316:                 return 'B';
                   7317:             }
                   7318:         } else {
1.1172.2.142  raeburn  7319:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7320:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7321:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7322:                 return 'B';
                   7323:             }
                   7324:         }
                   7325:     }
1.765     albertel 7326:     if ($result eq 'ok') {
1.766     albertel 7327:        return 'F';
1.765     albertel 7328:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7329:        return 'A';
1.765     albertel 7330:     }
1.766     albertel 7331:     return '';
1.765     albertel 7332: }
                   7333: 
                   7334: sub get_portfolio_access {
1.1172.2.77  raeburn  7335:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7336: 
                   7337:     if (!ref($access_hash)) {
                   7338: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7339: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7340: 						   $file_name);
                   7341: 	$access_hash = $access_controls{$file_name};
                   7342:     }
                   7343: 
1.1172.2.77  raeburn  7344:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7345:     my $now = time;
                   7346:     if (ref($access_hash) eq 'HASH') {
                   7347:         foreach my $key (keys(%{$access_hash})) {
                   7348:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7349:             if ($start > $now) {
                   7350:                 next;
                   7351:             }
                   7352:             if ($end && $end<$now) {
                   7353:                 next;
                   7354:             }
                   7355:             if ($scope eq 'public') {
                   7356:                 $public = $key;
                   7357:                 last;
                   7358:             } elsif ($scope eq 'guest') {
                   7359:                 $guest = $key;
                   7360:             } elsif ($scope eq 'domains') {
                   7361:                 push(@domains,$key);
                   7362:             } elsif ($scope eq 'users') {
                   7363:                 push(@users,$key);
                   7364:             } elsif ($scope eq 'course') {
                   7365:                 push(@courses,$key);
                   7366:             } elsif ($scope eq 'group') {
                   7367:                 push(@groups,$key);
1.1172.2.77  raeburn  7368:             } elsif ($scope eq 'ip') {
                   7369:                 push(@ips,$key);
1.765     albertel 7370:             }
                   7371:         }
                   7372:         if ($public) {
                   7373:             return 'ok';
1.1172.2.77  raeburn  7374:         } elsif (@ips > 0) {
                   7375:             my $allowed;
                   7376:             foreach my $ipkey (@ips) {
                   7377:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7378:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7379:                         $allowed = 1;
                   7380:                         last;
                   7381:                     }
                   7382:                 }
                   7383:             }
                   7384:             if ($allowed) {
                   7385:                 return 'ok';
                   7386:             }
1.765     albertel 7387:         }
                   7388:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7389:             if ($guest) {
                   7390:                 return $guest;
                   7391:             }
                   7392:         } else {
                   7393:             if (@domains > 0) {
                   7394:                 foreach my $domkey (@domains) {
                   7395:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7396:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7397:                             return 'ok';
                   7398:                         }
                   7399:                     }
                   7400:                 }
                   7401:             }
                   7402:             if (@users > 0) {
                   7403:                 foreach my $userkey (@users) {
1.865     raeburn  7404:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7405:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7406:                             if (ref($item) eq 'HASH') {
                   7407:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7408:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7409:                                     return 'ok';
                   7410:                                 }
                   7411:                             }
                   7412:                         }
                   7413:                     } 
1.765     albertel 7414:                 }
                   7415:             }
                   7416:             my %roleshash;
                   7417:             my @courses_and_groups = @courses;
                   7418:             push(@courses_and_groups,@groups); 
                   7419:             if (@courses_and_groups > 0) {
                   7420:                 my (%allgroups,%allroles); 
                   7421:                 my ($start,$end,$role,$sec,$group);
                   7422:                 foreach my $envkey (%env) {
1.1060    raeburn  7423:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7424:                         my $cid = $2.'_'.$3; 
                   7425:                         if ($1 eq 'gr') {
                   7426:                             $group = $4;
                   7427:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7428:                         } else {
                   7429:                             if ($4 eq '') {
                   7430:                                 $sec = 'none';
                   7431:                             } else {
                   7432:                                 $sec = $4;
                   7433:                             }
                   7434:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7435:                         }
1.811     albertel 7436:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7437:                         my $cid = $2.'_'.$3;
                   7438:                         if ($4 eq '') {
                   7439:                             $sec = 'none';
                   7440:                         } else {
                   7441:                             $sec = $4;
                   7442:                         }
                   7443:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7444:                     }
                   7445:                 }
                   7446:                 if (keys(%allroles) == 0) {
                   7447:                     return;
                   7448:                 }
                   7449:                 foreach my $key (@courses_and_groups) {
                   7450:                     my %content = %{$$access_hash{$key}};
                   7451:                     my $cnum = $content{'number'};
                   7452:                     my $cdom = $content{'domain'};
                   7453:                     my $cid = $cdom.'_'.$cnum;
                   7454:                     if (!exists($allroles{$cid})) {
                   7455:                         next;
                   7456:                     }    
                   7457:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7458:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7459:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7460:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7461:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7462:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7463:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7464:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7465:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7466:                                         if (grep/^all$/,@sections) {
                   7467:                                             return 'ok';
                   7468:                                         } else {
                   7469:                                             if (grep/^$sec$/,@sections) {
                   7470:                                                 return 'ok';
                   7471:                                             }
                   7472:                                         }
                   7473:                                     }
                   7474:                                 }
                   7475:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7476:                                     if (grep/^none$/,@groups) {
                   7477:                                         return 'ok';
                   7478:                                     }
                   7479:                                 } else {
                   7480:                                     if (grep/^all$/,@groups) {
                   7481:                                         return 'ok';
                   7482:                                     } 
                   7483:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7484:                                         if (grep/^$group$/,@groups) {
                   7485:                                             return 'ok';
                   7486:                                         }
                   7487:                                     }
                   7488:                                 } 
                   7489:                             }
                   7490:                         }
                   7491:                     }
                   7492:                 }
                   7493:             }
                   7494:             if ($guest) {
                   7495:                 return $guest;
                   7496:             }
                   7497:         }
                   7498:     }
                   7499:     return;
                   7500: }
                   7501: 
                   7502: sub course_group_datechecker {
                   7503:     my ($dates,$now,$status) = @_;
                   7504:     my ($start,$end) = split(/\./,$dates);
                   7505:     if (!$start && !$end) {
                   7506:         return 'ok';
                   7507:     }
                   7508:     if (grep/^active$/,@{$status}) {
                   7509:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7510:             return 'ok';
                   7511:         }
                   7512:     }
                   7513:     if (grep/^previous$/,@{$status}) {
                   7514:         if ($end > $now ) {
                   7515:             return 'ok';
                   7516:         }
                   7517:     }
                   7518:     if (grep/^future$/,@{$status}) {
                   7519:         if ($start > $now) {
                   7520:             return 'ok';
                   7521:         }
                   7522:     }
                   7523:     return; 
                   7524: }
                   7525: 
                   7526: sub parse_portfolio_url {
                   7527:     my ($url) = @_;
                   7528: 
                   7529:     my ($type,$udom,$unum,$group,$file_name);
                   7530:     
1.823     albertel 7531:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7532: 	$type = 1;
                   7533:         $udom = $1;
                   7534:         $unum = $2;
                   7535:         $file_name = $3;
1.823     albertel 7536:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7537: 	$type = 2;
                   7538:         $udom = $1;
                   7539:         $unum = $2;
                   7540:         $group = $3;
                   7541:         $file_name = $3.'/'.$4;
                   7542:     }
                   7543:     if (wantarray) {
                   7544: 	return ($type,$udom,$unum,$file_name,$group);
                   7545:     }
                   7546:     return $type;
                   7547: }
                   7548: 
                   7549: sub is_portfolio_url {
                   7550:     my ($url) = @_;
                   7551:     return scalar(&parse_portfolio_url($url));
                   7552: }
                   7553: 
1.798     raeburn  7554: sub is_portfolio_file {
                   7555:     my ($file) = @_;
1.820     raeburn  7556:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7557:         return 1;
                   7558:     }
                   7559:     return;
                   7560: }
                   7561: 
1.976     raeburn  7562: sub usertools_access {
1.1084    raeburn  7563:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7564:     my ($access,%tools);
                   7565:     if ($context eq '') {
                   7566:         $context = 'tools';
                   7567:     }
                   7568:     if ($context eq 'requestcourses') {
                   7569:         %tools = (
                   7570:                       official   => 1,
                   7571:                       unofficial => 1,
1.1006    raeburn  7572:                       community  => 1,
1.1172.2.37  raeburn  7573:                       textbook   => 1,
1.985     raeburn  7574:                  );
1.1172.2.9  raeburn  7575:     } elsif ($context eq 'requestauthor') {
                   7576:         %tools = (
                   7577:                       requestauthor => 1,
                   7578:                  );
1.985     raeburn  7579:     } else {
                   7580:         %tools = (
                   7581:                       aboutme   => 1,
                   7582:                       blog      => 1,
1.1172.2.6  raeburn  7583:                       webdav    => 1,
1.985     raeburn  7584:                       portfolio => 1,
                   7585:                  );
                   7586:     }
1.976     raeburn  7587:     return if (!defined($tools{$tool}));
                   7588: 
1.1172.2.35  raeburn  7589:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7590:         $udom = $env{'user.domain'};
                   7591:         $uname = $env{'user.name'};
                   7592:     }
                   7593: 
1.978     raeburn  7594:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7595:         if ($action ne 'reload') {
1.985     raeburn  7596:             if ($context eq 'requestcourses') {
                   7597:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7598:             } elsif ($context eq 'requestauthor') {
                   7599:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7600:             } else {
                   7601:                 return $env{'environment.availabletools.'.$tool};
                   7602:             }
                   7603:         }
1.976     raeburn  7604:     }
                   7605: 
1.1172.2.9  raeburn  7606:     my ($toolstatus,$inststatus,$envkey);
                   7607:     if ($context eq 'requestauthor') {
                   7608:         $envkey = $context;
                   7609:     } else {
                   7610:         $envkey = $context.'.'.$tool;
                   7611:     }
1.976     raeburn  7612: 
1.985     raeburn  7613:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7614:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7615:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7616:         $inststatus = $env{'environment.inststatus'};
                   7617:     } else {
1.1084    raeburn  7618:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7619:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7620:             $inststatus = $userenvref->{'inststatus'};
                   7621:         } else {
1.1172.2.9  raeburn  7622:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7623:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7624:             $inststatus = $userenv{'inststatus'};
                   7625:         }
1.976     raeburn  7626:     }
                   7627: 
                   7628:     if ($toolstatus ne '') {
                   7629:         if ($toolstatus) {
                   7630:             $access = 1;
                   7631:         } else {
                   7632:             $access = 0;
                   7633:         }
                   7634:         return $access;
                   7635:     }
                   7636: 
1.1084    raeburn  7637:     my ($is_adv,%domdef);
                   7638:     if (ref($is_advref) eq 'HASH') {
                   7639:         $is_adv = $is_advref->{'is_adv'};
                   7640:     } else {
                   7641:         $is_adv = &is_advanced_user($udom,$uname);
                   7642:     }
                   7643:     if (ref($domdefref) eq 'HASH') {
                   7644:         %domdef = %{$domdefref};
                   7645:     } else {
                   7646:         %domdef = &get_domain_defaults($udom);
                   7647:     }
1.976     raeburn  7648:     if (ref($domdef{$tool}) eq 'HASH') {
                   7649:         if ($is_adv) {
                   7650:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7651:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7652:                     $access = 1;
                   7653:                 } else {
                   7654:                     $access = 0;
                   7655:                 }
                   7656:                 return $access;
                   7657:             }
                   7658:         }
                   7659:         if ($inststatus ne '') {
                   7660:             my ($hasaccess,$hasnoaccess);
                   7661:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7662:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7663:                     if ($domdef{$tool}{$affiliation}) {
                   7664:                         $hasaccess = 1;
                   7665:                     } else {
                   7666:                         $hasnoaccess = 1;
                   7667:                     }
                   7668:                 }
                   7669:             }
                   7670:             if ($hasaccess || $hasnoaccess) {
                   7671:                 if ($hasaccess) {
                   7672:                     $access = 1;
                   7673:                 } elsif ($hasnoaccess) {
                   7674:                     $access = 0; 
                   7675:                 }
                   7676:                 return $access;
                   7677:             }
                   7678:         } else {
                   7679:             if ($domdef{$tool}{'default'} ne '') {
                   7680:                 if ($domdef{$tool}{'default'}) {
                   7681:                     $access = 1;
                   7682:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7683:                     $access = 0;
                   7684:                 }
                   7685:                 return $access;
                   7686:             }
                   7687:         }
                   7688:     } else {
1.1172.2.6  raeburn  7689:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7690:             $access = 1;
                   7691:         } else {
                   7692:             $access = 0;
                   7693:         }
1.976     raeburn  7694:         return $access;
                   7695:     }
                   7696: }
                   7697: 
1.1050    raeburn  7698: sub is_course_owner {
                   7699:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7700:     if (($udom eq '') || ($uname eq '')) {
                   7701:         $udom = $env{'user.domain'};
                   7702:         $uname = $env{'user.name'};
                   7703:     }
                   7704:     unless (($udom eq '') || ($uname eq '')) {
                   7705:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7706:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7707:                 return 1;
                   7708:             } else {
                   7709:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7710:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7711:                     return 1;
                   7712:                 }
                   7713:             }
                   7714:         }
                   7715:     }
                   7716:     return;
                   7717: }
                   7718: 
1.976     raeburn  7719: sub is_advanced_user {
                   7720:     my ($udom,$uname) = @_;
1.1085    raeburn  7721:     if ($udom ne '' && $uname ne '') {
                   7722:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7723:             if (wantarray) {
                   7724:                 return ($env{'user.adv'},$env{'user.author'});
                   7725:             } else {
                   7726:                 return $env{'user.adv'};
                   7727:             }
1.1085    raeburn  7728:         }
                   7729:     }
1.976     raeburn  7730:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7731:     my %allroles;
1.1128    raeburn  7732:     my ($is_adv,$is_author);
1.976     raeburn  7733:     foreach my $role (keys(%roleshash)) {
                   7734:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7735:         my $area = '/'.$tdomain.'/'.$trest;
                   7736:         if ($sec ne '') {
                   7737:             $area .= '/'.$sec;
                   7738:         }
                   7739:         if (($area ne '') && ($trole ne '')) {
                   7740:             my $spec=$trole.'.'.$area;
                   7741:             if ($trole =~ /^cr\//) {
                   7742:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7743:             } elsif ($trole ne 'gr') {
                   7744:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7745:             }
1.1128    raeburn  7746:             if ($trole eq 'au') {
                   7747:                 $is_author = 1;
                   7748:             }
1.976     raeburn  7749:         }
                   7750:     }
                   7751:     foreach my $role (keys(%allroles)) {
                   7752:         last if ($is_adv);
                   7753:         foreach my $item (split(/:/,$allroles{$role})) {
                   7754:             if ($item ne '') {
                   7755:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7756:                 if ($privilege eq 'adv') {
                   7757:                     $is_adv = 1;
                   7758:                     last;
                   7759:                 }
                   7760:             }
                   7761:         }
                   7762:     }
1.1128    raeburn  7763:     if (wantarray) {
                   7764:         return ($is_adv,$is_author);
                   7765:     }
1.976     raeburn  7766:     return $is_adv;
                   7767: }
1.798     raeburn  7768: 
1.1035    raeburn  7769: sub check_can_request {
1.1036    raeburn  7770:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7771:     my $canreq = 0;
                   7772:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7773:     my @options = ('approval','validate','autolimit');
                   7774:     my $optregex = join('|',@options);
                   7775:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7776:         foreach my $type (@{$types}) {
                   7777:             if (&usertools_access($env{'user.name'},
                   7778:                                   $env{'user.domain'},
                   7779:                                   $type,undef,'requestcourses')) {
                   7780:                 $canreq ++;
1.1036    raeburn  7781:                 if (ref($request_domains) eq 'HASH') {
                   7782:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7783:                 }
1.1035    raeburn  7784:                 if ($dom eq $env{'user.domain'}) {
                   7785:                     $can_request->{$type} = 1;
                   7786:                 }
                   7787:             }
                   7788:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7789:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7790:                 if (@curr > 0) {
1.1036    raeburn  7791:                     foreach my $item (@curr) {
                   7792:                         if (ref($request_domains) eq 'HASH') {
                   7793:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7794:                             if ($otherdom ne '') {
                   7795:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7796:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7797:                                         push(@{$request_domains->{$type}},$otherdom);
                   7798:                                     }
                   7799:                                 } else {
                   7800:                                     push(@{$request_domains->{$type}},$otherdom);
                   7801:                                 }
                   7802:                             }
                   7803:                         }
                   7804:                     }
                   7805:                     unless($dom eq $env{'user.domain'}) {
                   7806:                         $canreq ++;
1.1035    raeburn  7807:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7808:                             $can_request->{$type} = 1;
                   7809:                         }
                   7810:                     }
                   7811:                 }
                   7812:             }
                   7813:         }
                   7814:     }
                   7815:     return $canreq;
                   7816: }
                   7817: 
1.341     www      7818: # ---------------------------------------------- Custom access rule evaluation
                   7819: 
                   7820: sub customaccess {
                   7821:     my ($priv,$uri)=@_;
1.807     albertel 7822:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7823:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7824:     $udom = &LONCAPA::clean_domain($udom);
                   7825:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7826:     my $access=0;
1.800     albertel 7827:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7828: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7829: 	if ($type eq 'user') {
                   7830: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7831: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7832: 		if ($tdom) {
                   7833: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7834: 		}
1.896     albertel 7835: 		if ($tuname) {
                   7836: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7837: 		}
                   7838: 		$access=($effect eq 'allow');
                   7839: 		last;
                   7840: 	    }
                   7841: 	} else {
                   7842: 	    if ($role) {
                   7843: 		if ($role ne $urole) { next; }
                   7844: 	    }
                   7845: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7846: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7847: 		if ($tdom) {
                   7848: 		    if ($tdom ne $udom) { next; }
                   7849: 		}
                   7850: 		if ($tcrs) {
                   7851: 		    if ($tcrs ne $ucrs) { next; }
                   7852: 		}
                   7853: 		if ($tsec) {
                   7854: 		    if ($tsec ne $usec) { next; }
                   7855: 		}
                   7856: 		$access=($effect eq 'allow');
                   7857: 		last;
                   7858: 	    }
                   7859: 	    if ($realm eq '' && $role eq '') {
                   7860: 		$access=($effect eq 'allow');
                   7861: 	    }
1.402     bowersj2 7862: 	}
1.341     www      7863:     }
                   7864:     return $access;
                   7865: }
                   7866: 
1.103     harris41 7867: # ------------------------------------------------- Check for a user privilege
1.12      www      7868: 
                   7869: sub allowed {
1.1172.2.126  raeburn  7870:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7871:     my $ver_orguri=$uri;
1.439     www      7872:     $uri=&deversion($uri);
1.152     www      7873:     my $orguri=$uri;
1.52      www      7874:     $uri=&declutter($uri);
1.809     raeburn  7875: 
1.810     raeburn  7876:     if ($priv eq 'evb') {
                   7877: # Evade communication block restrictions for specified role in a course
                   7878:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7879:             return $1;
                   7880:         } else {
                   7881:             return;
                   7882:         }
                   7883:     }
                   7884: 
1.620     albertel 7885:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7886: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7887:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7888: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7889: 	&& ($priv eq 'bre')) {
1.14      www      7890: 	return 'F';
1.159     www      7891:     }
                   7892: 
1.545     banghart 7893: # Free bre access to user's own portfolio contents
1.714     raeburn  7894:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7895:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7896: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7897:         my %setters;
1.1172.2.142  raeburn  7898:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   7899:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7900:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7901:             return 'B';
                   7902:         } else {
                   7903:             return 'F';
                   7904:         }
1.545     banghart 7905:     }
                   7906: 
1.762     raeburn  7907: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7908:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7909:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7910:         if (exists($env{'request.course.id'})) {
                   7911:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7912:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7913:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7914:                 my $courseprivid=$env{'request.course.id'};
                   7915:                 $courseprivid=~s/\_/\//;
                   7916:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7917:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7918:                     return $1; 
1.762     raeburn  7919:                 } else {
                   7920:                     if ($env{'request.course.sec'}) {
                   7921:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7922:                     }
                   7923:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7924:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7925:                         return $2;
                   7926:                     }
1.714     raeburn  7927:                 }
                   7928:             }
                   7929:         }
                   7930:     }
                   7931: 
1.159     www      7932: # Free bre to public access
                   7933: 
                   7934:     if ($priv eq 'bre') {
1.238     www      7935:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7936: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7937:            return 'F'; 
                   7938:         }
1.238     www      7939:         if ($copyright eq 'priv') {
                   7940:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7941: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7942: 		return '';
                   7943:             }
                   7944:         }
                   7945:         if ($copyright eq 'domain') {
                   7946:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7947: 	    unless (($env{'user.domain'} eq $1) ||
                   7948:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7949: 		return '';
                   7950:             }
1.262     matthew  7951:         }
1.620     albertel 7952:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7953:             # Library role, so allow browsing of resources in this domain.
                   7954:             return 'F';
1.238     www      7955:         }
1.341     www      7956:         if ($copyright eq 'custom') {
                   7957: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7958:         }
1.14      www      7959:     }
1.264     matthew  7960:     # Domain coordinator is trying to create a course
1.620     albertel 7961:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7962:         # uri is the requested domain in this case.
                   7963:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7964:         # a role of dc for the domain in question.
1.620     albertel 7965:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7966:     }
1.29      www      7967: 
1.52      www      7968:     my $thisallowed='';
                   7969:     my $statecond=0;
                   7970:     my $courseprivid='';
                   7971: 
1.1039    raeburn  7972:     my $ownaccess;
1.1043    raeburn  7973:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7974:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7975:         if ($uri eq '') {
                   7976:             $ownaccess = 1;
                   7977:         } else {
                   7978:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7979:                 my $udom = $env{'user.domain'};
                   7980:                 my $uname = $env{'user.name'};
                   7981:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7982:                     $ownaccess = 1;
1.1040    raeburn  7983:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7984:                     unless ($uri =~ m{\.\./}) {
                   7985:                         $ownaccess = 1;
                   7986:                     }
                   7987:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7988:                     my $now = time;
                   7989:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7990:                         my $adom = $1;
                   7991:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7992:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  7993:                                 my ($start,$end) = split(/\./,$env{$key});
                   7994:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  7995:                                     $ownaccess = 1;
                   7996:                                     last;
                   7997:                                 }
                   7998:                             }
                   7999:                         }
                   8000:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8001:                         my $adom = $1;
                   8002:                         my $aname = $2;
1.1042    raeburn  8003:                         foreach my $role ('ca','aa') { 
                   8004:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8005:                                 my ($start,$end) =
1.1172.2.142  raeburn  8006:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8007:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8008:                                     $ownaccess = 1;
                   8009:                                     last;
                   8010:                                 }
1.1039    raeburn  8011:                             }
                   8012:                         }
                   8013:                     }
                   8014:                 }
                   8015:             }
                   8016:         }
                   8017:     }
                   8018: 
1.52      www      8019: # Course
                   8020: 
1.620     albertel 8021:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8022:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8023:             $thisallowed.=$1;
                   8024:         }
1.52      www      8025:     }
1.29      www      8026: 
1.52      www      8027: # Domain
                   8028: 
1.620     albertel 8029:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8030:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8031:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8032:             $thisallowed.=$1;
                   8033:         }
1.12      www      8034:     }
1.52      www      8035: 
1.1141    raeburn  8036: # User who is not author or co-author might still be able to edit
                   8037: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8038:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8039:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8040:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8041:             $thisallowed.=$1;
                   8042:         }
                   8043:     }
                   8044: 
1.52      www      8045: # Course: uri itself is a course
1.66      www      8046:     my $courseuri=$uri;
                   8047:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8048:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8049: 
1.620     albertel 8050:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8051:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8052:         if ($priv eq 'mip') {
                   8053:             my $rem = $1;
                   8054:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8055:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8056:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8057:                 if ($cdom ne '') {
                   8058:                     my %passwdconf = &get_passwdconf($cdom);
                   8059:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8060:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8061:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8062:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8063:                                 unless (@inststatuses) {
                   8064:                                     @inststatuses = ('default');
                   8065:                                 }
                   8066:                                 foreach my $status (@inststatuses) {
                   8067:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8068:                                         $thisallowed.=$rem;
                   8069:                                     }
                   8070:                                 }
                   8071:                             }
                   8072:                         }
                   8073:                     }
                   8074:                 }
                   8075:             }
                   8076:         } else {
                   8077:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8078:                 $thisallowed.=$1;
                   8079:             }
1.1039    raeburn  8080:         }
1.12      www      8081:     }
1.29      www      8082: 
1.665     albertel 8083: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8084: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8085:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8086: 	$thisallowed='';
1.671     raeburn  8087:         my ($match)=&is_on_map($uri);
                   8088:         if ($match) {
                   8089:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8090:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8091:                 my $value = $1;
                   8092:                 if ($noblockcheck) {
                   8093:                     $thisallowed.=$value;
1.1162    raeburn  8094:                 } else {
1.1172.2.126  raeburn  8095:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8096:                     if (@blockers > 0) {
                   8097:                         $thisallowed = 'B';
                   8098:                     } else {
                   8099:                         $thisallowed.=$value;
                   8100:                     }
1.1162    raeburn  8101:                 }
1.671     raeburn  8102:             }
                   8103:         } else {
1.705     albertel 8104:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8105:             if ($refuri) {
                   8106:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8107:                     $thisallowed='F';
1.671     raeburn  8108:                 } else {
                   8109:                     $refuri=&declutter($refuri);
                   8110:                     my ($match) = &is_on_map($refuri);
                   8111:                     if ($match) {
1.1172.2.65  raeburn  8112:                         if ($noblockcheck) {
1.1162    raeburn  8113:                             $thisallowed='F';
1.1172.2.65  raeburn  8114:                         } else {
1.1172.2.127  raeburn  8115:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8116:                             if (@blockers > 0) {
                   8117:                                 $thisallowed = 'B';
                   8118:                             } else {
                   8119:                                 $thisallowed='F';
                   8120:                             }
1.1162    raeburn  8121:                         }
1.671     raeburn  8122:                     }
1.669     raeburn  8123:                 }
1.671     raeburn  8124:             }
                   8125:         }
1.314     www      8126:     }
1.492     albertel 8127: 
1.766     albertel 8128:     if ($priv eq 'bre'
                   8129: 	&& $thisallowed ne 'F' 
                   8130: 	&& $thisallowed ne '2'
                   8131: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8132: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8133:     }
                   8134:     
1.52      www      8135: # Full access at system, domain or course-wide level? Exit.
1.29      www      8136:     if ($thisallowed=~/F/) {
                   8137: 	return 'F';
                   8138:     }
                   8139: 
1.52      www      8140: # If this is generating or modifying users, exit with special codes
1.29      www      8141: 
1.643     www      8142:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8143: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8144: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8145: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8146: 	    unless ($auname) { return $thisallowed; }
                   8147: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8148: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8149: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8150: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8151: 	}
1.52      www      8152: 	return $thisallowed;
                   8153:     }
                   8154: #
1.103     harris41 8155: # Gathered so far: system, domain and course wide privileges
1.52      www      8156: #
                   8157: # Course: See if uri or referer is an individual resource that is part of 
                   8158: # the course
                   8159: 
1.620     albertel 8160:     if ($env{'request.course.id'}) {
1.232     www      8161: 
1.1172.2.115  raeburn  8162: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8163: 
                   8164:         if ($priv eq 'mip') {
                   8165:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8166:                 return $thisallowed;
                   8167:             } else {
                   8168:                 return '';
                   8169:             }
                   8170:         }
                   8171: 
1.620     albertel 8172:        $courseprivid=$env{'request.course.id'};
                   8173:        if ($env{'request.course.sec'}) {
                   8174:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8175:        }
                   8176:        $courseprivid=~s/\_/\//;
                   8177:        my $checkreferer=1;
1.232     www      8178:        my ($match,$cond)=&is_on_map($uri);
                   8179:        if ($match) {
                   8180:            $statecond=$cond;
1.620     albertel 8181:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8182:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8183:                my $value = $1;
                   8184:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8185:                    if ($noblockcheck) {
1.1162    raeburn  8186:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8187:                    } else {
1.1172.2.126  raeburn  8188:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8189:                        if (@blockers > 0) {
                   8190:                            $thisallowed = 'B';
                   8191:                        } else {
                   8192:                            $thisallowed.=$value;
                   8193:                        }
1.1162    raeburn  8194:                    }
                   8195:                } else {
                   8196:                    $thisallowed.=$value;
                   8197:                }
1.52      www      8198:                $checkreferer=0;
                   8199:            }
1.29      www      8200:        }
1.1172.2.126  raeburn  8201: 
1.148     www      8202:        if ($checkreferer) {
1.620     albertel 8203: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8204:             unless ($refuri) {
1.800     albertel 8205:                 foreach my $key (keys(%env)) {
                   8206: 		    if ($key=~/^httpref\..*\*/) {
                   8207: 			my $pattern=$key;
1.156     www      8208:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8209:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8210:                         $pattern=~s/\//\\\//g;
1.152     www      8211:                         if ($orguri=~/$pattern/) {
1.800     albertel 8212: 			    $refuri=$env{$key};
1.148     www      8213:                         }
                   8214:                     }
1.191     harris41 8215:                 }
1.148     www      8216:             }
1.232     www      8217: 
1.148     www      8218:          if ($refuri) { 
1.152     www      8219: 	  $refuri=&declutter($refuri);
1.232     www      8220:           my ($match,$cond)=&is_on_map($refuri);
                   8221:             if ($match) {
                   8222:               my $refstatecond=$cond;
1.620     albertel 8223:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8224:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8225:                   my $value = $1;
                   8226:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8227:                       if ($noblockcheck) {
1.1162    raeburn  8228:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8229:                       } else {
1.1172.2.127  raeburn  8230:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8231:                           if (@blockers > 0) {
                   8232:                               $thisallowed = 'B';
                   8233:                           } else {
                   8234:                               $thisallowed.=$value;
                   8235:                           }
1.1162    raeburn  8236:                       }
                   8237:                   } else {
                   8238:                       $thisallowed.=$value;
                   8239:                   }
1.53      www      8240:                   $uri=$refuri;
                   8241:                   $statecond=$refstatecond;
1.52      www      8242:               }
                   8243:           }
1.148     www      8244:         }
1.29      www      8245:        }
1.52      www      8246:    }
1.29      www      8247: 
1.52      www      8248: #
1.103     harris41 8249: # Gathered now: all privileges that could apply, and condition number
1.52      www      8250: # 
                   8251: #
                   8252: # Full or no access?
                   8253: #
1.29      www      8254: 
1.52      www      8255:     if ($thisallowed=~/F/) {
                   8256: 	return 'F';
                   8257:     }
1.29      www      8258: 
1.52      www      8259:     unless ($thisallowed) {
                   8260:         return '';
                   8261:     }
1.29      www      8262: 
1.52      www      8263: # Restrictions exist, deal with them
                   8264: #
                   8265: #   C:according to course preferences
                   8266: #   R:according to resource settings
                   8267: #   L:unless locked
                   8268: #   X:according to user session state
                   8269: #
                   8270: 
                   8271: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8272: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8273: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8274: # courses, and 2 minutes for current course, in which user has st or ta role
                   8275: # which is neither expired nor a future role (unless current course).
1.52      www      8276: 
1.1172.2.142  raeburn  8277:     my ($needlockcheck,$now,$crsonly);
1.52      www      8278:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8279:         $now = time;
                   8280:         if ($priv eq 'bre') {
                   8281:             if ($uri ne '') {
                   8282:                 if ($orguri =~ m{^/+res/}) {
                   8283:                     if ($uri =~ m{^lib/templates/}) {
                   8284:                         if ($env{'request.course.id'}) {
                   8285:                             $crsonly = 1;
                   8286:                             $needlockcheck = 1;
                   8287:                         }
                   8288:                     } else {
                   8289:                         $needlockcheck = 1;
                   8290:                     }
                   8291:                 } elsif ($env{'request.course.id'}) {
                   8292:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8293:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8294:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8295:                         $crsonly = 1;
                   8296:                     }
                   8297:                     $needlockcheck = 1;
                   8298:                 }
                   8299:             }
                   8300:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8301:             $needlockcheck = 1;
                   8302:         }
                   8303:     }
                   8304:     if ($needlockcheck) {
                   8305:         foreach my $envkey (keys(%env)) {
1.54      www      8306:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8307:                my $courseid=$2;
                   8308:                my $roleid=$1.'.'.$2;
1.92      www      8309:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8310:                unless ($env{'request.role'} eq $roleid) {
                   8311:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8312:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8313:                }
1.54      www      8314:                my $expiretime=600;
1.620     albertel 8315:                if ($env{'request.role'} eq $roleid) {
1.54      www      8316: 		  $expiretime=120;
                   8317:                }
                   8318: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8319:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8320:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8321: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8322:                }
1.620     albertel 8323:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8324:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8325: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8326:                        &log($env{'user.domain'},$env{'user.name'},
                   8327:                             $env{'user.home'},
1.57      www      8328:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8329:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8330:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8331: 		       return '';
                   8332:                    }
                   8333:                }
1.620     albertel 8334:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8335:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8336: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8337:                        &log($env{'user.domain'},$env{'user.name'},
                   8338:                             $env{'user.home'},
1.57      www      8339:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8340:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8341:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8342: 		       return '';
                   8343:                    }
                   8344:                }
                   8345: 	   }
1.29      www      8346:        }
1.52      www      8347:     }
1.1172.2.126  raeburn  8348: 
1.52      www      8349: #
                   8350: # Rest of the restrictions depend on selected course
                   8351: #
                   8352: 
1.620     albertel 8353:     unless ($env{'request.course.id'}) {
1.766     albertel 8354: 	if ($thisallowed eq 'A') {
                   8355: 	    return 'A';
1.814     raeburn  8356:         } elsif ($thisallowed eq 'B') {
                   8357:             return 'B';
1.766     albertel 8358: 	} else {
                   8359: 	    return '1';
                   8360: 	}
1.52      www      8361:     }
1.29      www      8362: 
1.52      www      8363: #
                   8364: # Now user is definitely in a course
                   8365: #
1.53      www      8366: 
                   8367: 
                   8368: # Course preferences
                   8369: 
                   8370:    if ($thisallowed=~/C/) {
1.620     albertel 8371:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8372:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8373:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8374: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8375: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8376: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8377: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8378: 			$env{'request.course.id'});
                   8379: 	   }
1.237     www      8380:            return '';
                   8381:        }
                   8382: 
1.620     albertel 8383:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8384: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8385: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8386: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8387: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8388: 			$env{'request.course.id'});
                   8389: 	   }
1.54      www      8390:            return '';
                   8391:        }
1.53      www      8392:    }
                   8393: 
                   8394: # Resource preferences
                   8395: 
                   8396:    if ($thisallowed=~/R/) {
1.620     albertel 8397:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8398:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8399: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8400: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8401: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8402: 	   }
                   8403: 	   return '';
1.54      www      8404:        }
1.53      www      8405:    }
1.30      www      8406: 
1.246     www      8407: # Restricted by state or randomout?
1.30      www      8408: 
1.52      www      8409:    if ($thisallowed=~/X/) {
1.620     albertel 8410:       if ($env{'acc.randomout'}) {
1.579     albertel 8411: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8412:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8413:             return ''; 
                   8414:          }
1.247     www      8415:       }
                   8416:       if (&condval($statecond)) {
1.52      www      8417: 	 return '2';
                   8418:       } else {
                   8419:          return '';
                   8420:       }
                   8421:    }
1.30      www      8422: 
1.766     albertel 8423:     if ($thisallowed eq 'A') {
                   8424: 	return 'A';
1.814     raeburn  8425:     } elsif ($thisallowed eq 'B') {
                   8426:         return 'B';
1.766     albertel 8427:     }
1.52      www      8428:    return 'F';
1.232     www      8429: }
1.1162    raeburn  8430: 
1.1172.2.13  raeburn  8431: # ------------------------------------------- Check construction space access
                   8432: 
                   8433: sub constructaccess {
                   8434:     my ($url,$setpriv)=@_;
                   8435: 
                   8436: # We do not allow editing of previous versions of files
                   8437:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8438: 
                   8439: # Get username and domain from URL
                   8440:     my ($ownername,$ownerdomain,$ownerhome);
                   8441: 
                   8442:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8443:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8444: 
                   8445: # The URL does not really point to any authorspace, forget it
                   8446:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8447: 
                   8448: # Now we need to see if the user has access to the authorspace of
                   8449: # $ownername at $ownerdomain
                   8450: 
                   8451:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8452: # Real author for this?
                   8453:        $ownerhome = $env{'user.home'};
                   8454:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8455:           return ($ownername,$ownerdomain,$ownerhome);
                   8456:        }
                   8457:     } else {
                   8458: # Co-author for this?
                   8459:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8460:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8461:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8462:             return ($ownername,$ownerdomain,$ownerhome);
                   8463:         }
                   8464:     }
                   8465: 
                   8466: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8467: # we might as well leave
                   8468:    unless ($setpriv) { return ''; }
                   8469: 
                   8470: # Backdoor access?
                   8471:     my $allowed=&allowed('eco',$ownerdomain);
                   8472: # Nope
                   8473:     unless ($allowed) { return ''; }
                   8474: # Looks like we may have access, but could be locked by the owner of the construction space
                   8475:     if ($allowed eq 'U') {
                   8476:         my %blocked=&get('environment',['domcoord.author'],
                   8477:                          $ownerdomain,$ownername);
                   8478: # Is blocked by owner
                   8479:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8480:     }
                   8481:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8482: # Grant temporary access
                   8483:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8484:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8485:         if (!$update) { $update = $then; }
                   8486:         my $refresh=$env{'user.refresh.time'};
                   8487:         if (!$refresh) { $refresh = $update; }
                   8488:         my $now = time;
                   8489:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8490:                            $now,'ca','constructaccess');
                   8491:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8492:         return($ownername,$ownerdomain,$ownerhome);
                   8493:     }
                   8494: # No business here
                   8495:     return '';
                   8496: }
                   8497: 
1.1172.2.66  raeburn  8498: # ----------------------------------------------------------- Content Blocking
                   8499: 
                   8500: {
                   8501: # Caches for faster Course Contents display where content blocking
                   8502: # is in operation (i.e., interval param set) for timed quiz.
                   8503: #
                   8504: # User for whom data are being temporarily cached.
                   8505: my $cacheduser='';
1.1172.2.126  raeburn  8506: # Course for which data are being temporarily cached.
                   8507: my $cachedcid='';
1.1172.2.66  raeburn  8508: # Cached blockers for this user (a hash of blocking items).
                   8509: my %cachedblockers=();
                   8510: # When the data were last cached.
                   8511: my $cachedlast='';
                   8512: 
                   8513: sub load_all_blockers {
1.1172.2.128  raeburn  8514:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8515:     if (($uname ne '') && ($udom ne '')) {
                   8516:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8517:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8518:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8519:             return;
                   8520:         }
                   8521:     }
                   8522:     $cachedlast=time;
                   8523:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8524:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8525:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8526:     return;
1.1172.2.66  raeburn  8527: }
                   8528: 
1.1162    raeburn  8529: sub get_comm_blocks {
                   8530:     my ($cdom,$cnum) = @_;
                   8531:     if ($cdom eq '' || $cnum eq '') {
                   8532:         return unless ($env{'request.course.id'});
                   8533:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8534:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8535:     }
                   8536:     my %commblocks;
                   8537:     my $hashid=$cdom.'_'.$cnum;
                   8538:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8539:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8540:         %commblocks = %{$blocksref};
                   8541:     } else {
                   8542:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8543:         my $cachetime = 600;
                   8544:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8545:     }
                   8546:     return %commblocks;
                   8547: }
                   8548: 
1.1172.2.66  raeburn  8549: sub get_commblock_resources {
                   8550:     my ($blocks) = @_;
                   8551:     my %blockers = ();
                   8552:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8553:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8554:     if ($env{'request.course.sec'}) {
                   8555:         $courseurl .= '/'.$env{'request.course.sec'};
                   8556:     }
                   8557:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8558:     my %commblocks;
                   8559:     if (ref($blocks) eq 'HASH') {
                   8560:         %commblocks = %{$blocks};
                   8561:     } else {
                   8562:         %commblocks = &get_comm_blocks();
                   8563:     }
1.1172.2.66  raeburn  8564:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8565:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8566:     return %blockers unless (ref($navmap));
                   8567:     my $now = time;
1.1162    raeburn  8568:     foreach my $block (keys(%commblocks)) {
                   8569:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8570:             my ($start,$end) = ($1,$2);
                   8571:             if ($start <= $now && $end >= $now) {
                   8572:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8573:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8574:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8575:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8576:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8577:                             }
                   8578:                         }
                   8579:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8580:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8581:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8582:                             }
                   8583:                         }
                   8584:                     }
                   8585:                 }
                   8586:             }
                   8587:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8588:             my $item = $1;
                   8589:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8590:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8591:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8592:                     my $type = 'map';
                   8593:                     if ($item eq 'course') {
                   8594:                         $type = 'course';
                   8595:                         @interval=&EXT("resource.0.interval");
                   8596:                     } else {
                   8597:                         if ($item =~ /___\d+___/) {
                   8598:                             $type = 'resource';
                   8599:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8600:                         } else {
1.1172.2.142  raeburn  8601:                             $mapname = &deversion($item);
                   8602:                             if (ref($navmap)) {
                   8603:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8604:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8605:                             }
                   8606:                         }
1.1172.2.66  raeburn  8607:                     }
                   8608:                     if ($interval[0] =~ /^\d+$/) {
                   8609:                         my $first_access;
                   8610:                         if ($type eq 'resource') {
                   8611:                             $first_access=&get_first_access($interval[1],$item);
                   8612:                         } elsif ($type eq 'map') {
                   8613:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8614:                         } else {
                   8615:                             $first_access=&get_first_access($interval[1]);
                   8616:                         }
                   8617:                         if ($first_access) {
                   8618:                             my $timesup = $first_access+$interval[0];
                   8619:                             if ($timesup > $now) {
                   8620:                                 my $activeblock;
1.1172.2.142  raeburn  8621:                                 if ($type eq 'resource') {
                   8622:                                     if (ref($navmap)) {
                   8623:                                         my $res = $navmap->getBySymb($item);
                   8624:                                         if ($res->answerable()) {
                   8625:                                             $activeblock = 1;
                   8626:                                         }
                   8627:                                     }
                   8628:                                 } elsif ($type eq 'map') {
                   8629:                                     my $mapsymb = &symbread($mapname,1);
                   8630:                                     if (($mapsymb) && (ref($navmap))) {
                   8631:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8632:                                         if (ref($mapres)) {
                   8633:                                             my $first = $mapres->map_start();
                   8634:                                             my $finish = $mapres->map_finish();
                   8635:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8636:                                             if (ref($it)) {
                   8637:                                                 my $res;
                   8638:                                                 while ($res = $it->next(undef,1)) {
                   8639:                                                     next unless (ref($res));
                   8640:                                                     my $symb = $res->symb();
                   8641:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8642:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8643:                                                     if ($interval[1] eq 'map') {
                   8644:                                                         if ($res->answerable()) {
                   8645:                                                             $activeblock = 1;
                   8646:                                                             last;
                   8647:                                                         }
                   8648:                                                     }
                   8649:                                                 }
                   8650:                                             }
                   8651:                                         }
1.1172.2.66  raeburn  8652:                                     }
                   8653:                                 }
                   8654:                                 if ($activeblock) {
                   8655:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8656:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8657:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8658:                                          }
                   8659:                                     }
                   8660:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8661:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8662:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8663:                                         }
1.1162    raeburn  8664:                                     }
                   8665:                                 }
                   8666:                             }
                   8667:                         }
                   8668:                     }
                   8669:                 }
                   8670:             }
                   8671:         }
                   8672:     }
1.1172.2.66  raeburn  8673:     return %blockers;
1.1162    raeburn  8674: }
                   8675: 
1.1172.2.66  raeburn  8676: sub has_comm_blocking {
1.1172.2.128  raeburn  8677:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8678:     my @blockers;
                   8679:     return unless ($env{'request.course.id'});
                   8680:     return unless ($priv eq 'bre');
                   8681:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8682:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8683:     if ($env{'request.course.sec'}) {
                   8684:         $courseurl .= '/'.$env{'request.course.sec'};
                   8685:     }
                   8686:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8687:     my %blockinfo;
                   8688:     if (ref($blocks) eq 'HASH') {
                   8689:         %blockinfo = &get_commblock_resources($blocks);
                   8690:     } else {
                   8691:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8692:         %blockinfo = %cachedblockers;
                   8693:     }
                   8694:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8695:     my (%possibles,@symbs);
                   8696:     if (!$symb) {
1.1172.2.128  raeburn  8697:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8698:     }
1.1172.2.66  raeburn  8699:     if ($symb) {
                   8700:         @symbs = ($symb);
                   8701:     } elsif (keys(%possibles)) {
                   8702:         @symbs = keys(%possibles);
                   8703:     }
                   8704:     my $noblock;
                   8705:     foreach my $symb (@symbs) {
                   8706:         last if ($noblock);
                   8707:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8708:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8709:             if ($block =~ /^firstaccess____(.+)$/) {
                   8710:                 my $item = $1;
1.1172.2.126  raeburn  8711:                 unless ($blocked) {
                   8712:                     if (($item eq $map) || ($item eq $symb)) {
                   8713:                         $noblock = 1;
                   8714:                         last;
                   8715:                     }
1.1172.2.66  raeburn  8716:                 }
1.1162    raeburn  8717:             }
1.1172.2.128  raeburn  8718:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8719:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8720:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8721:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8722:                             push(@blockers,$block);
                   8723:                         }
                   8724:                     }
                   8725:                 }
1.1172.2.128  raeburn  8726:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8727:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8728:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8729:                             push(@blockers,$block);
                   8730:                         }
1.1172.2.66  raeburn  8731:                     }
                   8732:                 }
1.1162    raeburn  8733:             }
                   8734:         }
                   8735:     }
1.1172.2.126  raeburn  8736:     unless ($noblock) {
                   8737:         return @blockers;
                   8738:     }
                   8739:     return;
1.1172.2.66  raeburn  8740: }
1.1162    raeburn  8741: }
                   8742: 
1.1172.2.66  raeburn  8743: # -------------------------------- Deversion and split uri into path an filename
                   8744: 
1.1133    foxr     8745: #
1.1172.2.66  raeburn  8746: #   Removes the version from a URI and
1.1133    foxr     8747: #   splits it in to its filename and path to the filename.
                   8748: #   Seems like File::Basename could have done this more clearly.
                   8749: #   Parameters:
                   8750: #      $uri   - input URI
                   8751: #   Returns:
                   8752: #     Two element list consisting of 
                   8753: #     $pathname  - the URI up to and excluding the trailing /
                   8754: #     $filename  - The part of the URI following the last /
                   8755: #  NOTE:
                   8756: #    Another realization of this is simply:
                   8757: #    use File::Basename;
                   8758: #    ...
                   8759: #    $uri = shift;
                   8760: #    $filename = basename($uri);
                   8761: #    $path     = dirname($uri);
                   8762: #    return ($filename, $path);
                   8763: #
                   8764: #     The implementation below is probably faster however.
                   8765: #
1.710     albertel 8766: sub split_uri_for_cond {
                   8767:     my $uri=&deversion(&declutter(shift));
                   8768:     my @uriparts=split(/\//,$uri);
                   8769:     my $filename=pop(@uriparts);
                   8770:     my $pathname=join('/',@uriparts);
                   8771:     return ($pathname,$filename);
                   8772: }
1.232     www      8773: # --------------------------------------------------- Is a resource on the map?
                   8774: 
                   8775: sub is_on_map {
1.710     albertel 8776:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8777:     #Trying to find the conditional for the file
1.620     albertel 8778:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8779: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8780:     if ($match) {
1.289     bowersj2 8781: 	return (1,$1);
                   8782:     } else {
1.434     www      8783: 	return (0,0);
1.289     bowersj2 8784:     }
1.12      www      8785: }
                   8786: 
1.427     www      8787: # --------------------------------------------------------- Get symb from alias
                   8788: 
                   8789: sub get_symb_from_alias {
                   8790:     my $symb=shift;
                   8791:     my ($map,$resid,$url)=&decode_symb($symb);
                   8792: # Already is a symb
                   8793:     if ($url) { return $symb; }
                   8794: # Must be an alias
                   8795:     my $aliassymb='';
                   8796:     my %bighash;
1.620     albertel 8797:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8798:                             &GDBM_READER(),0640)) {
                   8799:         my $rid=$bighash{'mapalias_'.$symb};
                   8800: 	if ($rid) {
                   8801: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8802: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8803: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8804: 	}
                   8805:         untie %bighash;
                   8806:     }
                   8807:     return $aliassymb;
                   8808: }
                   8809: 
1.12      www      8810: # ----------------------------------------------------------------- Define Role
                   8811: 
                   8812: sub definerole {
                   8813:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8814:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8815:     foreach my $role (split(':',$sysrole)) {
                   8816: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8817:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8818:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8819: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8820:                return "refused:s:$crole&$cqual"; 
                   8821:             }
                   8822:         }
1.191     harris41 8823:     }
1.800     albertel 8824:     foreach my $role (split(':',$domrole)) {
                   8825: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8826:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8827:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8828: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8829:                return "refused:d:$crole&$cqual"; 
                   8830:             }
                   8831:         }
1.191     harris41 8832:     }
1.800     albertel 8833:     foreach my $role (split(':',$courole)) {
                   8834: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8835:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8836:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8837: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8838:                return "refused:c:$crole&$cqual"; 
                   8839:             }
                   8840:         }
1.191     harris41 8841:     }
1.1172.2.84  raeburn  8842:     my $uhome;
                   8843:     if (($uname ne '') && ($udom ne '')) {
                   8844:         $uhome = &homeserver($uname,$udom);
                   8845:         return $uhome if ($uhome eq 'no_host');
                   8846:     } else {
                   8847:         $uname = $env{'user.name'};
                   8848:         $udom = $env{'user.domain'};
                   8849:         $uhome = $env{'user.home'};
                   8850:     }
1.620     albertel 8851:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8852:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8853:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8854:     return reply($command,$uhome);
1.12      www      8855:   } else {
                   8856:     return 'refused';
                   8857:   }
1.105     harris41 8858: }
                   8859: 
                   8860: # ---------------- Make a metadata query against the network of library servers
                   8861: 
                   8862: sub metadata_query {
1.1172.2.33  raeburn  8863:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8864:     my %rhash;
1.845     albertel 8865:     my %libserv = &all_library();
1.244     matthew  8866:     my @server_list = (defined($server_array) ? @$server_array
                   8867:                                               : keys(%libserv) );
                   8868:     for my $server (@server_list) {
1.1172.2.33  raeburn  8869:         my $domains = '';
                   8870:         if (ref($domains_hash) eq 'HASH') {
                   8871:             $domains = $domains_hash->{$server};    
                   8872:         }
1.118     harris41 8873: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8874: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8875: 	    $rhash{$server}=$reply;
                   8876: 	}
                   8877: 	else {
                   8878: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8879: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8880: 			     $server);
                   8881: 	    $rhash{$server}=$reply;
                   8882: 	}
1.112     harris41 8883:     }
1.118     harris41 8884:     return \%rhash;
1.240     www      8885: }
                   8886: 
                   8887: # ----------------------------------------- Send log queries and wait for reply
                   8888: 
                   8889: sub log_query {
                   8890:     my ($uname,$udom,$query,%filters)=@_;
                   8891:     my $uhome=&homeserver($uname,$udom);
                   8892:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8893:     my $uhost=&hostname($uhome);
1.800     albertel 8894:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8895:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8896:                        $uhome);
1.479     albertel 8897:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8898:     return get_query_reply($queryid);
                   8899: }
                   8900: 
1.818     raeburn  8901: # -------------------------- Update MySQL table for portfolio file
                   8902: 
                   8903: sub update_portfolio_table {
1.821     raeburn  8904:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8905:     if ($group ne '') {
                   8906:         $file_name =~s /^\Q$group\E//;
                   8907:     }
1.818     raeburn  8908:     my $homeserver = &homeserver($uname,$udom);
                   8909:     my $queryid=
1.821     raeburn  8910:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8911:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8912:     my $reply = &get_query_reply($queryid);
                   8913:     return $reply;
                   8914: }
                   8915: 
1.899     raeburn  8916: # -------------------------- Update MySQL allusers table
                   8917: 
                   8918: sub update_allusers_table {
                   8919:     my ($uname,$udom,$names) = @_;
                   8920:     my $homeserver = &homeserver($uname,$udom);
                   8921:     my $queryid=
                   8922:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8923:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8924:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8925:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8926:                'generation='.&escape($names->{'generation'}).'%%'.
                   8927:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8928:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8929:     return;
1.899     raeburn  8930: }
                   8931: 
1.508     raeburn  8932: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8933: 
                   8934: sub fetch_enrollment_query {
1.511     raeburn  8935:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8936:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8937:     my $maxtries = 1;
1.508     raeburn  8938:     if ($context eq 'automated') {
                   8939:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8940:         $sleep = 2;
                   8941:         $loopmax = 100;
1.547     raeburn  8942:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8943:     } else {
                   8944:         $homeserver = &homeserver($cnum,$dom);
                   8945:     }
1.838     albertel 8946:     my $host=&hostname($homeserver);
1.506     raeburn  8947:     my $cmd = '';
1.1000    raeburn  8948:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8949:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8950:     }
                   8951:     $cmd =~ s/%%$//;
                   8952:     $cmd = &escape($cmd);
                   8953:     my $query = 'fetchenrollment';
1.620     albertel 8954:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8955:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8956:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8957:         return 'error: '.$queryid;
                   8958:     }
1.1172.2.93  raeburn  8959:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8960:     my $tries = 1;
                   8961:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8962:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8963:         $tries ++;
                   8964:     }
1.526     raeburn  8965:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8966:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8967:     } else {
1.901     albertel 8968:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8969:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8970:             foreach my $line (@responses) {
                   8971:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8972:                 $$replyref{$key} = $value;
                   8973:             }
                   8974:         } else {
1.1117    foxr     8975:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8976:             foreach my $line (@responses) {
                   8977:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8978:                 $$replyref{$key} = $value;
                   8979:                 if ($value > 0) {
1.800     albertel 8980:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8981:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8982:                         my $destname = $pathname.'/'.$filename;
                   8983:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8984:                         if ($xml_classlist =~ /^error/) {
                   8985:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8986:                         } else {
1.1172.2.96  raeburn  8987:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8988:                                 print FILE &unescape($xml_classlist);
                   8989:                                 close(FILE);
1.526     raeburn  8990:                             } else {
                   8991:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8992:                             }
                   8993:                         }
                   8994:                     }
                   8995:                 }
                   8996:             }
                   8997:         }
                   8998:         return 'ok';
                   8999:     }
                   9000:     return 'error';
                   9001: }
                   9002: 
1.242     www      9003: sub get_query_reply {
1.1172.2.79  raeburn  9004:     my ($queryid,$sleep,$loopmax) = @_;
                   9005:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9006:         $sleep = 0.2;
                   9007:     }
                   9008:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9009:         $loopmax = 100;
                   9010:     }
1.1117    foxr     9011:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9012:     my $reply='';
1.1172.2.79  raeburn  9013:     for (1..$loopmax) {
                   9014: 	sleep($sleep);
1.240     www      9015:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9016: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9017: 		$reply = join('',<$fh>);
                   9018: 		close($fh);
1.240     www      9019: 	   } else { return 'error: reply_file_error'; }
1.242     www      9020:            return &unescape($reply);
                   9021: 	}
1.240     www      9022:     }
1.242     www      9023:     return 'timeout:'.$queryid;
1.240     www      9024: }
                   9025: 
                   9026: sub courselog_query {
1.241     www      9027: #
                   9028: # possible filters:
                   9029: # url: url or symb
                   9030: # username
                   9031: # domain
                   9032: # action: view, submit, grade
                   9033: # start: timestamp
                   9034: # end: timestamp
                   9035: #
1.240     www      9036:     my (%filters)=@_;
1.620     albertel 9037:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9038:     if ($filters{'url'}) {
                   9039: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9040:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9041:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9042:     }
1.620     albertel 9043:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9044:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9045:     return &log_query($cname,$cdom,'courselog',%filters);
                   9046: }
                   9047: 
                   9048: sub userlog_query {
1.858     raeburn  9049: #
                   9050: # possible filters:
                   9051: # action: log check role
                   9052: # start: timestamp
                   9053: # end: timestamp
                   9054: #
1.240     www      9055:     my ($uname,$udom,%filters)=@_;
                   9056:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9057: }
                   9058: 
1.506     raeburn  9059: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9060: 
                   9061: sub auto_run {
1.508     raeburn  9062:     my ($cnum,$cdom) = @_;
1.876     raeburn  9063:     my $response = 0;
                   9064:     my $settings;
                   9065:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9066:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9067:         $settings = $domconfig{'autoenroll'};
                   9068:         if ($settings->{'run'} eq '1') {
                   9069:             $response = 1;
                   9070:         }
                   9071:     } else {
1.934     raeburn  9072:         my $homeserver;
                   9073:         if (&is_course($cdom,$cnum)) {
                   9074:             $homeserver = &homeserver($cnum,$cdom);
                   9075:         } else {
                   9076:             $homeserver = &domain($cdom,'primary');
                   9077:         }
                   9078:         if ($homeserver ne 'no_host') {
                   9079:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9080:         }
1.876     raeburn  9081:     }
1.506     raeburn  9082:     return $response;
                   9083: }
1.776     albertel 9084: 
1.506     raeburn  9085: sub auto_get_sections {
1.508     raeburn  9086:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9087:     my $homeserver;
                   9088:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9089:         $homeserver = &homeserver($cnum,$cdom);
                   9090:     }
                   9091:     if (!defined($homeserver)) { 
                   9092:         if ($cdom =~ /^$match_domain$/) {
                   9093:             $homeserver = &domain($cdom,'primary');
                   9094:         }
                   9095:     }
                   9096:     my @secs;
                   9097:     if (defined($homeserver)) {
                   9098:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9099:         unless ($response eq 'refused') {
                   9100:             @secs = split(/:/,$response);
                   9101:         }
1.506     raeburn  9102:     }
                   9103:     return @secs;
                   9104: }
1.776     albertel 9105: 
1.506     raeburn  9106: sub auto_new_course {
1.1099    raeburn  9107:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9108:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9109:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9110:     return $response;
                   9111: }
1.776     albertel 9112: 
1.506     raeburn  9113: sub auto_validate_courseID {
1.508     raeburn  9114:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9115:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9116:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9117:     return $response;
                   9118: }
1.776     albertel 9119: 
1.1007    raeburn  9120: sub auto_validate_instcode {
1.1020    raeburn  9121:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9122:     my ($homeserver,$response);
                   9123:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9124:         $homeserver = &homeserver($cnum,$cdom);
                   9125:     }
                   9126:     if (!defined($homeserver)) {
                   9127:         if ($cdom =~ /^$match_domain$/) {
                   9128:             $homeserver = &domain($cdom,'primary');
                   9129:         }
                   9130:     }
1.1065    raeburn  9131:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9132:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9133:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9134:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9135: }
                   9136: 
1.1172.2.141  raeburn  9137: sub auto_validate_inst_crosslist {
                   9138:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9139:     my ($homeserver,$response);
                   9140:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9141:         $homeserver = &homeserver($cnum,$cdom);
                   9142:     }
                   9143:     if (!defined($homeserver)) {
                   9144:         if ($cdom =~ /^$match_domain$/) {
                   9145:             $homeserver = &domain($cdom,'primary');
                   9146:         }
                   9147:     }
                   9148:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9149:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9150:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9151:                          &escape($coowner),$homeserver);
                   9152:     }
                   9153:     return $response;
                   9154: }
                   9155: 
1.506     raeburn  9156: sub auto_create_password {
1.873     raeburn  9157:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9158:     my ($homeserver,$response);
1.506     raeburn  9159:     my $create_passwd = 0;
                   9160:     my $authchk = '';
1.873     raeburn  9161:     if ($udom =~ /^$match_domain$/) {
                   9162:         $homeserver = &domain($udom,'primary');
                   9163:     }
                   9164:     if ($homeserver eq '') {
                   9165:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9166:             $homeserver = &homeserver($cnum,$cdom);
                   9167:         }
                   9168:     }
                   9169:     if ($homeserver eq '') {
                   9170:         $authchk = 'nodomain';
1.506     raeburn  9171:     } else {
1.873     raeburn  9172:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9173:         if ($response eq 'refused') {
                   9174:             $authchk = 'refused';
                   9175:         } else {
1.901     albertel 9176:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9177:         }
1.506     raeburn  9178:     }
                   9179:     return ($authparam,$create_passwd,$authchk);
                   9180: }
                   9181: 
1.706     raeburn  9182: sub auto_photo_permission {
                   9183:     my ($cnum,$cdom,$students) = @_;
                   9184:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9185:     my ($outcome,$perm_reqd,$conditions) = 
                   9186: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9187:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9188: 	return (undef,undef);
                   9189:     }
1.706     raeburn  9190:     return ($outcome,$perm_reqd,$conditions);
                   9191: }
                   9192: 
                   9193: sub auto_checkphotos {
                   9194:     my ($uname,$udom,$pid) = @_;
                   9195:     my $homeserver = &homeserver($uname,$udom);
                   9196:     my ($result,$resulttype);
                   9197:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9198: 				   &escape($uname).':'.&escape($pid),
                   9199: 				   $homeserver));
1.709     albertel 9200:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9201: 	return (undef,undef);
                   9202:     }
1.706     raeburn  9203:     if ($outcome) {
                   9204:         ($result,$resulttype) = split(/:/,$outcome);
                   9205:     } 
                   9206:     return ($result,$resulttype);
                   9207: }
                   9208: 
                   9209: sub auto_photochoice {
                   9210:     my ($cnum,$cdom) = @_;
                   9211:     my $homeserver = &homeserver($cnum,$cdom);
                   9212:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9213: 						       &escape($cdom),
                   9214: 						       $homeserver)));
1.709     albertel 9215:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9216: 	return (undef,undef);
                   9217:     }
1.706     raeburn  9218:     return ($update,$comment);
                   9219: }
                   9220: 
                   9221: sub auto_photoupdate {
                   9222:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9223:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9224:     my $host=&hostname($homeserver);
1.706     raeburn  9225:     my $cmd = '';
                   9226:     my $maxtries = 1;
1.800     albertel 9227:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9228:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9229:     }
                   9230:     $cmd =~ s/%%$//;
                   9231:     $cmd = &escape($cmd);
                   9232:     my $query = 'institutionalphotos';
                   9233:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9234:     unless ($queryid=~/^\Q$host\E\_/) {
                   9235:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9236:         return 'error: '.$queryid;
                   9237:     }
                   9238:     my $reply = &get_query_reply($queryid);
                   9239:     my $tries = 1;
                   9240:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9241:         $reply = &get_query_reply($queryid);
                   9242:         $tries ++;
                   9243:     }
                   9244:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9245:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9246:     } else {
                   9247:         my @responses = split(/:/,$reply);
                   9248:         my $outcome = shift(@responses); 
                   9249:         foreach my $item (@responses) {
                   9250:             my ($key,$value) = split(/=/,$item);
                   9251:             $$photo{$key} = $value;
                   9252:         }
                   9253:         return $outcome;
                   9254:     }
                   9255:     return 'error';
                   9256: }
                   9257: 
1.521     raeburn  9258: sub auto_instcode_format {
1.793     albertel 9259:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9260: 	$cat_order) = @_;
1.521     raeburn  9261:     my $courses = '';
1.772     raeburn  9262:     my @homeservers;
1.521     raeburn  9263:     if ($caller eq 'global') {
1.841     albertel 9264: 	my %servers = &get_servers($codedom,'library');
                   9265: 	foreach my $tryserver (keys(%servers)) {
                   9266: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9267: 		push(@homeservers,$tryserver);
                   9268: 	    }
1.584     raeburn  9269:         }
1.1022    raeburn  9270:     } elsif ($caller eq 'requests') {
                   9271:         if ($codedom =~ /^$match_domain$/) {
                   9272:             my $chome = &domain($codedom,'primary');
                   9273:             unless ($chome eq 'no_host') {
                   9274:                 push(@homeservers,$chome);
                   9275:             }
                   9276:         }
1.521     raeburn  9277:     } else {
1.772     raeburn  9278:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9279:     }
1.793     albertel 9280:     foreach my $code (keys(%{$instcodes})) {
                   9281:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9282:     }
                   9283:     chop($courses);
1.772     raeburn  9284:     my $ok_response = 0;
                   9285:     my $response;
                   9286:     while (@homeservers > 0 && $ok_response == 0) {
                   9287:         my $server = shift(@homeservers); 
                   9288:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9289:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9290:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9291: 		split(/:/,$response);
1.772     raeburn  9292:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9293:             push(@{$codetitles},&str2array($codetitles_str));
                   9294:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9295:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9296:             $ok_response = 1;
                   9297:         }
                   9298:     }
                   9299:     if ($ok_response) {
1.521     raeburn  9300:         return 'ok';
1.772     raeburn  9301:     } else {
                   9302:         return $response;
1.521     raeburn  9303:     }
                   9304: }
                   9305: 
1.792     raeburn  9306: sub auto_instcode_defaults {
                   9307:     my ($domain,$returnhash,$code_order) = @_;
                   9308:     my @homeservers;
1.841     albertel 9309: 
                   9310:     my %servers = &get_servers($domain,'library');
                   9311:     foreach my $tryserver (keys(%servers)) {
                   9312: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9313: 	    push(@homeservers,$tryserver);
                   9314: 	}
1.792     raeburn  9315:     }
1.841     albertel 9316: 
1.792     raeburn  9317:     my $response;
1.841     albertel 9318:     foreach my $server (@homeservers) {
1.792     raeburn  9319:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9320:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9321: 	
                   9322: 	foreach my $pair (split(/\&/,$response)) {
                   9323: 	    my ($name,$value)=split(/\=/,$pair);
                   9324: 	    if ($name eq 'code_order') {
                   9325: 		@{$code_order} = split(/\&/,&unescape($value));
                   9326: 	    } else {
                   9327: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9328: 	    }
                   9329: 	}
                   9330: 	return 'ok';
1.792     raeburn  9331:     }
1.841     albertel 9332: 
                   9333:     return $response;
1.1003    raeburn  9334: }
                   9335: 
                   9336: sub auto_possible_instcodes {
1.1007    raeburn  9337:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9338:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9339:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9340:         return;
                   9341:     }
1.1003    raeburn  9342:     my (@homeservers,$uhome);
                   9343:     if (defined(&domain($domain,'primary'))) {
                   9344:         $uhome=&domain($domain,'primary');
                   9345:         push(@homeservers,&domain($domain,'primary'));
                   9346:     } else {
                   9347:         my %servers = &get_servers($domain,'library');
                   9348:         foreach my $tryserver (keys(%servers)) {
                   9349:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9350:                 push(@homeservers,$tryserver);
                   9351:             }
                   9352:         }
                   9353:     }
                   9354:     my $response;
                   9355:     foreach my $server (@homeservers) {
                   9356:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9357:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9358:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9359:             split(':',$response);
                   9360:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9361:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9362:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9363:             my ($name,$value)=split('=',$item);
                   9364:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9365:         }
                   9366:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9367:             my ($name,$value)=split('=',$item);
                   9368:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9369:         }
                   9370:         return 'ok';
                   9371:     }
                   9372:     return $response;
                   9373: }
1.792     raeburn  9374: 
1.1010    raeburn  9375: sub auto_courserequest_checks {
                   9376:     my ($dom) = @_;
1.1020    raeburn  9377:     my ($homeserver,%validations);
                   9378:     if ($dom =~ /^$match_domain$/) {
                   9379:         $homeserver = &domain($dom,'primary');
                   9380:     }
                   9381:     unless ($homeserver eq 'no_host') {
                   9382:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9383:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9384:             my @items = split(/&/,$response);
                   9385:             foreach my $item (@items) {
                   9386:                 my ($key,$value) = split('=',$item);
                   9387:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9388:             }
                   9389:         }
                   9390:     }
1.1010    raeburn  9391:     return %validations; 
                   9392: }
                   9393: 
1.1020    raeburn  9394: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9395:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9396:     my ($homeserver,$response);
                   9397:     if ($dom =~ /^$match_domain$/) {
                   9398:         $homeserver = &domain($dom,'primary');
                   9399:     }
1.1172.2.43  raeburn  9400:     unless ($homeserver eq 'no_host') {
                   9401:         my $customdata;
                   9402:         if (ref($custominfo) eq 'HASH') {
                   9403:             $customdata = &freeze_escape($custominfo);
                   9404:         }
1.1020    raeburn  9405:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9406:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9407:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9408:                                     $customdata,$homeserver));
1.1020    raeburn  9409:     }
                   9410:     return $response;
                   9411: }
                   9412: 
1.777     albertel 9413: sub auto_validate_class_sec {
1.918     raeburn  9414:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9415:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9416:     my $ownerlist;
                   9417:     if (ref($owners) eq 'ARRAY') {
                   9418:         $ownerlist = join(',',@{$owners});
                   9419:     } else {
                   9420:         $ownerlist = $owners;
                   9421:     }
1.773     raeburn  9422:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9423:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9424:     return $response;
                   9425: }
                   9426: 
1.1172.2.141  raeburn  9427: sub auto_instsec_reformat {
                   9428:     my ($cdom,$action,$instsecref) = @_;
                   9429:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9430:     my @homeservers;
                   9431:     if (defined(&domain($cdom,'primary'))) {
                   9432:         push(@homeservers,&domain($cdom,'primary'));
                   9433:     } else {
                   9434:         my %servers = &get_servers($cdom,'library');
                   9435:         foreach my $tryserver (keys(%servers)) {
                   9436:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9437:                 push(@homeservers,$tryserver);
                   9438:             }
                   9439:         }
                   9440:     }
                   9441:     my $response;
                   9442:     my %reformatted = %{$instsecref};
                   9443:     foreach my $server (@homeservers) {
                   9444:         if (ref($instsecref) eq 'HASH') {
                   9445:             my $info = &freeze_escape($instsecref);
                   9446:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9447:                                 $action.':'.$info,$server);
                   9448:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9449:             my @items = split(/&/,$response);
                   9450:             foreach my $item (@items) {
                   9451:                 my ($key,$value) = split(/=/,$item);
                   9452:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9453:             }
                   9454:         }
                   9455:     }
                   9456:     return %reformatted;
                   9457: }
                   9458: 
1.1172.2.94  raeburn  9459: sub auto_validate_instclasses {
                   9460:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9461:     my ($homeserver,%validations);
                   9462:     $homeserver = &homeserver($cnum,$cdom);
                   9463:     unless ($homeserver eq 'no_host') {
                   9464:         my $ownerlist;
                   9465:         if (ref($owners) eq 'ARRAY') {
                   9466:             $ownerlist = join(',',@{$owners});
                   9467:         } else {
                   9468:             $ownerlist = $owners;
                   9469:         }
                   9470:         if (ref($classesref) eq 'HASH') {
                   9471:             my $classes = &freeze_escape($classesref);
                   9472:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9473:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9474:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9475:                 my @items = split(/&/,$response);
                   9476:                 foreach my $item (@items) {
                   9477:                     my ($key,$value) = split('=',$item);
                   9478:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9479:                 }
                   9480:             }
                   9481:         }
                   9482:     }
                   9483:     return %validations;
                   9484: }
                   9485: 
1.1172.2.38  raeburn  9486: sub auto_crsreq_update {
                   9487:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9488:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9489:     my ($homeserver,%crsreqresponse);
                   9490:     if ($cdom =~ /^$match_domain$/) {
                   9491:         $homeserver = &domain($cdom,'primary');
                   9492:     }
                   9493:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9494:         my $info;
                   9495:         if (ref($inbound) eq 'HASH') {
                   9496:             $info = &freeze_escape($inbound);
                   9497:         }
                   9498:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9499:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9500:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9501:                             &escape($title).':'.&escape($code).':'.
                   9502:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9503:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9504:             my @items = split(/&/,$response);
                   9505:             foreach my $item (@items) {
                   9506:                 my ($key,$value) = split('=',$item);
                   9507:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9508:             }
                   9509:         }
                   9510:     }
                   9511:     return \%crsreqresponse;
                   9512: }
                   9513: 
1.1172.2.78  raeburn  9514: sub auto_export_grades {
                   9515:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9516:     my ($homeserver,%exportresponse);
                   9517:     if ($cdom =~ /^$match_domain$/) {
                   9518:         $homeserver = &domain($cdom,'primary');
                   9519:     }
                   9520:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9521:         my $info;
                   9522:         if (ref($inforef) eq 'HASH') {
                   9523:             $info = &freeze_escape($inforef);
                   9524:         }
                   9525:         if (ref($gradesref) eq 'HASH') {
                   9526:             my $grades = &freeze_escape($gradesref);
                   9527:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9528:                                 $info.':'.$grades,$homeserver);
                   9529:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9530:                 my @items = split(/&/,$response);
                   9531:                 foreach my $item (@items) {
                   9532:                     my ($key,$value) = split('=',$item);
                   9533:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9534:                 }
                   9535:             }
                   9536:         }
                   9537:     }
                   9538:     return \%exportresponse;
                   9539: }
                   9540: 
1.1172.2.68  raeburn  9541: sub check_instcode_cloning {
                   9542:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9543:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9544:         return;
                   9545:     }
                   9546:     my $canclone;
                   9547:     if (@{$code_order} > 0) {
                   9548:         my $instcoderegexp ='^';
                   9549:         my @clonecodes = split(/\&/,$cloner);
                   9550:         foreach my $item (@{$code_order}) {
                   9551:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9552:                 foreach my $pair (@clonecodes) {
                   9553:                     my ($key,$val) = split(/\=/,$pair,2);
                   9554:                     $val = &unescape($val);
                   9555:                     if ($key eq $item) {
                   9556:                         $instcoderegexp .= '('.$val.')';
                   9557:                         last;
                   9558:                     }
                   9559:                 }
                   9560:             } else {
                   9561:                 $instcoderegexp .= $codedefaults->{$item};
                   9562:             }
                   9563:         }
                   9564:         $instcoderegexp .= '$';
                   9565:         my (@from,@to);
                   9566:         eval {
                   9567:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9568:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9569:         };
                   9570:         if ((@from > 0) && (@to > 0)) {
                   9571:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9572:             if (!@diffs) {
                   9573:                 $canclone = 1;
                   9574:             }
                   9575:         }
                   9576:     }
                   9577:     return $canclone;
                   9578: }
                   9579: 
                   9580: sub default_instcode_cloning {
                   9581:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9582:     my (%codedefaults,@code_order,$canclone);
                   9583:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9584:         %codedefaults = %{$codedefaultsref};
                   9585:         @code_order = @{$codeorderref};
                   9586:     } elsif ($clonedom) {
                   9587:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9588:     }
                   9589:     if (($domdefclone) && (@code_order)) {
                   9590:         my @clonecodes = split(/\+/,$domdefclone);
                   9591:         my $instcoderegexp ='^';
                   9592:         foreach my $item (@code_order) {
                   9593:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9594:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9595:             } else {
                   9596:                 $instcoderegexp .= $codedefaults{$item};
                   9597:             }
                   9598:         }
                   9599:         $instcoderegexp .= '$';
                   9600:         my (@from,@to);
                   9601:         eval {
                   9602:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9603:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9604:         };
                   9605:         if ((@from > 0) && (@to > 0)) {
                   9606:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9607:             if (!@diffs) {
                   9608:                 $canclone = 1;
                   9609:             }
                   9610:         }
                   9611:     }
                   9612:     return $canclone;
                   9613: }
                   9614: 
1.679     raeburn  9615: # ------------------------------------------------------- Course Group routines
                   9616: 
                   9617: sub get_coursegroups {
1.809     raeburn  9618:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9619:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9620: }
                   9621: 
1.679     raeburn  9622: sub modify_coursegroup {
                   9623:     my ($cdom,$cnum,$groupsettings) = @_;
                   9624:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9625: }
                   9626: 
1.809     raeburn  9627: sub toggle_coursegroup_status {
                   9628:     my ($cdom,$cnum,$group,$action) = @_;
                   9629:     my ($from_namespace,$to_namespace);
                   9630:     if ($action eq 'delete') {
                   9631:         $from_namespace = 'coursegroups';
                   9632:         $to_namespace = 'deleted_groups';
                   9633:     } else {
                   9634:         $from_namespace = 'deleted_groups';
                   9635:         $to_namespace = 'coursegroups';
                   9636:     }
                   9637:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9638:     if (my $tmp = &error(%curr_group)) {
                   9639:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9640:         return ('read error',$tmp);
                   9641:     } else {
                   9642:         my %savedsettings = %curr_group; 
1.809     raeburn  9643:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9644:         my $deloutcome;
                   9645:         if ($result eq 'ok') {
1.809     raeburn  9646:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9647:         } else {
                   9648:             return ('write error',$result);
                   9649:         }
                   9650:         if ($deloutcome eq 'ok') {
                   9651:             return 'ok';
                   9652:         } else {
                   9653:             return ('delete error',$deloutcome);
                   9654:         }
                   9655:     }
                   9656: }
                   9657: 
1.679     raeburn  9658: sub modify_group_roles {
1.957     raeburn  9659:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9660:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9661:     my $role = 'gr/'.&escape($userprivs);
                   9662:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9663:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9664:     if ($result eq 'ok') {
                   9665:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9666:     }
1.679     raeburn  9667:     return $result;
                   9668: }
                   9669: 
                   9670: sub modify_coursegroup_membership {
                   9671:     my ($cdom,$cnum,$membership) = @_;
                   9672:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9673:     return $result;
                   9674: }
                   9675: 
1.682     raeburn  9676: sub get_active_groups {
                   9677:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9678:     my $now = time;
                   9679:     my %groups = ();
                   9680:     foreach my $key (keys(%env)) {
1.811     albertel 9681:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9682:             my ($start,$end) = split(/\./,$env{$key});
                   9683:             if (($end!=0) && ($end<$now)) { next; }
                   9684:             if (($start!=0) && ($start>$now)) { next; }
                   9685:             if ($1 eq $cdom && $2 eq $cnum) {
                   9686:                 $groups{$3} = $env{$key} ;
                   9687:             }
                   9688:         }
                   9689:     }
                   9690:     return %groups;
                   9691: }
                   9692: 
1.683     raeburn  9693: sub get_group_membership {
                   9694:     my ($cdom,$cnum,$group) = @_;
                   9695:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9696: }
                   9697: 
                   9698: sub get_users_groups {
                   9699:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9700:     my @usersgroups;
1.683     raeburn  9701:     my $cachetime=1800;
                   9702: 
                   9703:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9704:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9705:     if (defined($cached)) {
1.734     albertel 9706:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9707:     } else {  
                   9708:         $grouplist = '';
1.816     raeburn  9709:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9710:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9711:         my $access_end = $env{'course.'.$courseid.
                   9712:                               '.default_enrollment_end_date'};
                   9713:         my $now = time;
                   9714:         foreach my $key (keys(%roleshash)) {
                   9715:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9716:                 my $group = $1;
                   9717:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9718:                     my $start = $2;
                   9719:                     my $end = $1;
                   9720:                     if ($start == -1) { next; } # deleted from group
                   9721:                     if (($start!=0) && ($start>$now)) { next; }
                   9722:                     if (($end!=0) && ($end<$now)) {
                   9723:                         if ($access_end && $access_end < $now) {
                   9724:                             if ($access_end - $end < 86400) {
                   9725:                                 push(@usersgroups,$group);
1.733     raeburn  9726:                             }
                   9727:                         }
1.817     raeburn  9728:                         next;
1.733     raeburn  9729:                     }
1.817     raeburn  9730:                     push(@usersgroups,$group);
1.683     raeburn  9731:                 }
                   9732:             }
                   9733:         }
1.817     raeburn  9734:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9735:         $grouplist = join(':',@usersgroups);
                   9736:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9737:     }
1.733     raeburn  9738:     return @usersgroups;
1.683     raeburn  9739: }
                   9740: 
                   9741: sub devalidate_getgroups_cache {
                   9742:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9743:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9744: 
1.683     raeburn  9745:     my $hashid="$udom:$uname:$courseid";
                   9746:     &devalidate_cache_new('getgroups',$hashid);
                   9747: }
                   9748: 
1.12      www      9749: # ------------------------------------------------------------------ Plain Text
                   9750: 
                   9751: sub plaintext {
1.988     raeburn  9752:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9753:     if ($short =~ m{^cr/}) {
1.758     albertel 9754: 	return (split('/',$short))[-1];
                   9755:     }
1.742     raeburn  9756:     if (!defined($cid)) {
                   9757:         $cid = $env{'request.course.id'};
                   9758:     }
                   9759:     my %rolenames = (
1.1008    raeburn  9760:                       Course    => 'std',
                   9761:                       Community => 'alt1',
1.742     raeburn  9762:                     );
1.1037    raeburn  9763:     if ($cid ne '') {
                   9764:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9765:             unless ($forcedefault) {
                   9766:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9767:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9768:                 return &Apache::lonlocal::mt($roletext);
                   9769:             }
                   9770:         }
                   9771:     }
                   9772:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9773:         (defined($rolenames{$type})) && 
                   9774:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9775:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9776:     } elsif ($cid ne '') {
                   9777:         my $crstype = $env{'course.'.$cid.'.type'};
                   9778:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9779:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9780:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9781:         }
1.742     raeburn  9782:     }
1.1037    raeburn  9783:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9784: }
                   9785: 
                   9786: # ----------------------------------------------------------------- Assign Role
                   9787: 
                   9788: sub assignrole {
1.957     raeburn  9789:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9790:         $context)=@_;
1.21      www      9791:     my $mrole;
                   9792:     if ($role =~ /^cr\//) {
1.393     www      9793:         my $cwosec=$url;
1.811     albertel 9794:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9795: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9796:            my $refused = 1;
                   9797:            if ($context eq 'requestcourses') {
                   9798:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9799:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9800:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9801:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9802:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9803:                            if ($crsenv{'internal.courseowner'} eq
                   9804:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9805:                                $refused = '';
                   9806:                            }
                   9807:                        }
                   9808:                    }
                   9809:                }
                   9810:            }
                   9811:            if ($refused) {
                   9812:                &logthis('Refused custom assignrole: '.
                   9813:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9814:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9815:                return 'refused';
                   9816:            }
1.104     www      9817:         }
1.21      www      9818:         $mrole='cr';
1.678     raeburn  9819:     } elsif ($role =~ /^gr\//) {
                   9820:         my $cwogrp=$url;
1.811     albertel 9821:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9822:         unless (&allowed('mdg',$cwogrp)) {
                   9823:             &logthis('Refused group assignrole: '.
                   9824:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9825:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9826:             return 'refused';
                   9827:         }
                   9828:         $mrole='gr';
1.21      www      9829:     } else {
1.82      www      9830:         my $cwosec=$url;
1.811     albertel 9831:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9832:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9833:             my $refused;
                   9834:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9835:                 if (!(&allowed('c'.$role,$url))) {
                   9836:                     $refused = 1;
                   9837:                 }
                   9838:             } else {
                   9839:                 $refused = 1;
                   9840:             }
1.947     raeburn  9841:             if ($refused) {
1.1045    raeburn  9842:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9843:                 if (!$selfenroll && $context eq 'course') {
                   9844:                     my %crsenv;
                   9845:                     if ($role eq 'cc' || $role eq 'co') {
                   9846:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9847:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9848:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9849:                                 if ($crsenv{'internal.courseowner'} eq 
                   9850:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9851:                                     $refused = '';
                   9852:                                 }
                   9853:                             }
                   9854:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9855:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9856:                                 if ($crsenv{'internal.courseowner'} eq 
                   9857:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9858:                                     $refused = '';
                   9859:                                 }
                   9860:                             }
                   9861:                         }
                   9862:                     }
                   9863:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9864:                     $refused = '';
1.1017    raeburn  9865:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9866:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9867:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9868:                         my $wrongcc;
                   9869:                         if ($cnum =~ /^$match_community$/) {
                   9870:                             $wrongcc = 1 if ($role eq 'cc');
                   9871:                         } else {
                   9872:                             $wrongcc = 1 if ($role eq 'co');
                   9873:                         }
                   9874:                         unless ($wrongcc) {
                   9875:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9876:                             if ($crsenv{'internal.courseowner'} eq 
                   9877:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9878:                                 $refused = '';
                   9879:                             }
1.1017    raeburn  9880:                         }
                   9881:                     }
1.1172.2.9  raeburn  9882:                 } elsif ($context eq 'requestauthor') {
                   9883:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9884:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9885:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9886:                             $refused = '';
                   9887:                         } else {
                   9888:                             my %domdefaults = &get_domain_defaults($udom);
                   9889:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9890:                                 my $checkbystatus;
                   9891:                                 if ($env{'user.adv'}) {
                   9892:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9893:                                     if ($disposition eq 'automatic') {
                   9894:                                         $refused = '';
                   9895:                                     } elsif ($disposition eq '') {
                   9896:                                         $checkbystatus = 1;
                   9897:                                     }
                   9898:                                 } else {
                   9899:                                     $checkbystatus = 1;
                   9900:                                 }
                   9901:                                 if ($checkbystatus) {
                   9902:                                     if ($env{'environment.inststatus'}) {
                   9903:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9904:                                         foreach my $type (@inststatuses) {
                   9905:                                             if (($type ne '') &&
                   9906:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9907:                                                 $refused = '';
                   9908:                                             }
                   9909:                                         }
                   9910:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9911:                                         $refused = '';
                   9912:                                     }
                   9913:                                 }
                   9914:                             }
                   9915:                         }
                   9916:                     }
1.1017    raeburn  9917:                 }
                   9918:                 if ($refused) {
1.947     raeburn  9919:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9920:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9921: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9922:                     return 'refused';
                   9923:                 }
1.932     raeburn  9924:             }
1.1131    raeburn  9925:         } elsif ($role eq 'au') {
                   9926:             if ($url ne '/'.$udom.'/') {
                   9927:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9928:                          ' to assign author role for '.$uname.':'.$udom.
                   9929:                          ' in domain: '.$url.' refused (wrong domain).');
                   9930:                 return 'refused';
                   9931:             }
1.104     www      9932:         }
1.21      www      9933:         $mrole=$role;
                   9934:     }
1.620     albertel 9935:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9936:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9937:     if ($end) { $command.='_'.$end; }
1.21      www      9938:     if ($start) {
                   9939: 	if ($end) { 
1.81      www      9940:            $command.='_'.$start; 
1.21      www      9941:         } else {
1.81      www      9942:            $command.='_0_'.$start;
1.21      www      9943:         }
                   9944:     }
1.739     raeburn  9945:     my $origstart = $start;
                   9946:     my $origend = $end;
1.957     raeburn  9947:     my $delflag;
1.357     www      9948: # actually delete
                   9949:     if ($deleteflag) {
1.373     www      9950: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9951: # modify command to delete the role
1.620     albertel 9952:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9953:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9954: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9955: # set start and finish to negative values for userrolelog
                   9956:            $start=-1;
                   9957:            $end=-1;
1.957     raeburn  9958:            $delflag = 1;
1.357     www      9959:         }
                   9960:     }
                   9961: # send command
1.349     www      9962:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9963: # log new user role if status is ok
1.349     www      9964:     if ($answer eq 'ok') {
1.663     raeburn  9965: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9966:         if (($role eq 'cc') || ($role eq 'in') ||
                   9967:             ($role eq 'ep') || ($role eq 'ad') ||
                   9968:             ($role eq 'ta') || ($role eq 'st') ||
                   9969:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9970:             ($role eq 'co')) {
1.1172.2.13  raeburn  9971: # for course roles, perform group memberships changes triggered by role change.
                   9972:             unless ($role =~ /^gr/) {
                   9973:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9974:                                                  $origstart,$selfenroll,$context);
                   9975:             }
1.1172.2.9  raeburn  9976:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9977:                            $selfenroll,$context);
                   9978:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9979:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9980:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9981:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9982:                            $context);
                   9983:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9984:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9985:                              $context);
                   9986:         }
1.1053    raeburn  9987:         if ($role eq 'cc') {
                   9988:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9989:         }
1.349     www      9990:     }
                   9991:     return $answer;
1.169     harris41 9992: }
                   9993: 
1.1053    raeburn  9994: sub autoupdate_coowners {
                   9995:     my ($url,$end,$start,$uname,$udom) = @_;
                   9996:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9997:     if (($cdom ne '') && ($cnum ne '')) {
                   9998:         my $now = time;
                   9999:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10000:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10001:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10002:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10003:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10004:             if ($instcode ne '') {
1.1056    raeburn  10005:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10006:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10007:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10008:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10009:                         unless ($result eq 'valid') {
                   10010:                             if ($xlists ne '') {
                   10011:                                 foreach my $xlist (split(',',$xlists)) {
                   10012:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10013:                                     $result =
                   10014:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10015:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10016:                                     last if ($result eq 'valid');
                   10017:                                 }
                   10018:                             }
                   10019:                         }
1.1056    raeburn  10020:                         if ($result eq 'valid') {
                   10021:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10022:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10023:                                     push(@newcoowners,$coowner);
                   10024:                                 }
                   10025:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10026:                                     push(@newcoowners,$uname.':'.$udom);
                   10027:                                 }
                   10028:                                 @newcoowners = sort(@newcoowners);
                   10029:                             } else {
                   10030:                                 push(@newcoowners,$uname.':'.$udom);
                   10031:                             }
1.1172.2.141  raeburn  10032:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10033:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10034:                                 unless ($coowner eq $uname.':'.$udom) {
                   10035:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10036:                                 }
                   10037:                             }
1.1172.2.141  raeburn  10038:                             unless (@newcoowners > 0) {
                   10039:                                 $delcoowners = 1;
                   10040:                                 $coowners = '';
                   10041:                             }
1.1053    raeburn  10042:                         }
                   10043:                         if (@newcoowners || $delcoowners) {
                   10044:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10045:                                             $delcoowners,@newcoowners);
                   10046:                         }
                   10047:                     }
                   10048:                 }
                   10049:             }
                   10050:         }
                   10051:     }
                   10052: }
                   10053: 
                   10054: sub store_coowners {
                   10055:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10056:     my $cid = $cdom.'_'.$cnum;
                   10057:     my ($coowners,$delresult,$putresult);
                   10058:     if (@newcoowners) {
                   10059:         $coowners = join(',',@newcoowners);
                   10060:         my %coownershash = (
                   10061:                             'internal.co-owners' => $coowners,
                   10062:                            );
                   10063:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10064:         if ($putresult eq 'ok') {
                   10065:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10066:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10067:             }
                   10068:         }
                   10069:     }
                   10070:     if ($delcoowners) {
                   10071:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10072:         if ($delresult eq 'ok') {
                   10073:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10074:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10075:             }
                   10076:         }
                   10077:     }
                   10078:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10079:         my %crsinfo =
                   10080:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10081:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10082:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10083:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10084:         }
                   10085:     }
                   10086: }
                   10087: 
1.169     harris41 10088: # -------------------------------------------------- Modify user authentication
1.197     www      10089: # Overrides without validation
                   10090: 
1.169     harris41 10091: sub modifyuserauth {
                   10092:     my ($udom,$uname,$umode,$upass)=@_;
                   10093:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10094:     my $allowed;
                   10095:     if (&allowed('mau',$udom)) {
                   10096:         $allowed = 1;
                   10097:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10098:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10099:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10100:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10101:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10102:         if (($cdom ne '') && ($cnum ne '')) {
                   10103:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10104:             if ($is_owner) {
                   10105:                 $allowed = 1;
                   10106:             }
                   10107:         }
                   10108:     }
                   10109:     unless ($allowed) { return 'refused'; }
1.197     www      10110:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10111:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10112:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10113:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10114: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10115:     my $ip = &get_requestor_ip();
1.620     albertel 10116:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10117:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10118:          '(Remote '.$ip.'): '.$reply);
1.197     www      10119:     &log($udom,,$uname,$uhome,
1.620     albertel 10120:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10121:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10122:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10123:     unless ($reply eq 'ok') {
1.197     www      10124:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10125: 	return 'error: '.$reply;
                   10126:     }   
1.170     harris41 10127:     return 'ok';
1.80      www      10128: }
                   10129: 
1.81      www      10130: # --------------------------------------------------------------- Modify a user
1.80      www      10131: 
1.81      www      10132: sub modifyuser {
1.206     matthew  10133:     my ($udom,    $uname, $uid,
                   10134:         $umode,   $upass, $first,
                   10135:         $middle,  $last,  $gene,
1.1058    raeburn  10136:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10137:     $udom= &LONCAPA::clean_domain($udom);
                   10138:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10139:     my $showcandelete = 'none';
                   10140:     if (ref($candelete) eq 'ARRAY') {
                   10141:         if (@{$candelete} > 0) {
                   10142:             $showcandelete = join(', ',@{$candelete});
                   10143:         }
                   10144:     }
1.81      www      10145:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10146:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10147: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10148:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10149:                                      ' desiredhome not specified'). 
1.620     albertel 10150:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10151:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10152:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10153:     my $newuser;
                   10154:     if ($uhome eq 'no_host') {
                   10155:         $newuser = 1;
                   10156:     }
1.80      www      10157: # ----------------------------------------------------------------- Create User
1.406     albertel 10158:     if (($uhome eq 'no_host') && 
                   10159: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10160:         my $unhome='';
1.844     albertel 10161:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10162:             $unhome = $desiredhome;
1.620     albertel 10163: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10164: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10165:         } else { # load balancing routine for determining $unhome
1.81      www      10166:             my $loadm=10000000;
1.841     albertel 10167: 	    my %servers = &get_servers($udom,'library');
                   10168: 	    foreach my $tryserver (keys(%servers)) {
                   10169: 		my $answer=reply('load',$tryserver);
                   10170: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10171: 		    $loadm=$answer;
                   10172: 		    $unhome=$tryserver;
                   10173: 		}
1.80      www      10174: 	    }
                   10175:         }
                   10176:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10177: 	    return 'error: unable to find a home server for '.$uname.
                   10178:                    ' in domain '.$udom;
1.80      www      10179:         }
                   10180:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10181:                          &escape($upass),$unhome);
                   10182: 	unless ($reply eq 'ok') {
                   10183:             return 'error: '.$reply;
                   10184:         }   
1.230     stredwic 10185:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10186:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10187: 	    return 'error: unable verify users home machine.';
1.80      www      10188:         }
1.209     matthew  10189:     }   # End of creation of new user
1.80      www      10190: # ---------------------------------------------------------------------- Add ID
                   10191:     if ($uid) {
                   10192:        $uid=~tr/A-Z/a-z/;
                   10193:        my %uidhash=&idrget($udom,$uname);
1.196     www      10194:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10195:          && (!$forceid)) {
1.80      www      10196: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10197: 	      return 'error: user id "'.$uid.'" does not match '.
                   10198:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10199:           }
                   10200:        } else {
                   10201: 	  &idput($udom,($uname => $uid));
                   10202:        }
                   10203:     }
                   10204: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10205:     my @tmp=&get('environment',
1.899     raeburn  10206: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10207:                     'permanentemail','inststatus'],
1.134     albertel 10208: 		   $udom,$uname);
1.1075    raeburn  10209:     my (%names,%oldnames);
1.313     matthew  10210:     if ($tmp[0] =~ m/^error:.*/) { 
                   10211:         %names=(); 
                   10212:     } else {
                   10213:         %names = @tmp;
1.1075    raeburn  10214:         %oldnames = %names;
1.313     matthew  10215:     }
1.388     www      10216: #
1.1058    raeburn  10217: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10218: # of users did not contain them), do not overwrite existing values
                   10219: # unless field is in $candelete array ref.  
                   10220: #
                   10221: 
                   10222:     my @fields = ('firstname','middlename','lastname','generation',
                   10223:                   'permanentemail','id');
                   10224:     my %newvalues;
                   10225:     if (ref($candelete) eq 'ARRAY') {
                   10226:         foreach my $field (@fields) {
                   10227:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10228:                 if ($field eq 'firstname') {
                   10229:                     $names{$field} = $first;
                   10230:                 } elsif ($field eq 'middlename') {
                   10231:                     $names{$field} = $middle;
                   10232:                 } elsif ($field eq 'lastname') {
                   10233:                     $names{$field} = $last;
                   10234:                 } elsif ($field eq 'generation') { 
                   10235:                     $names{$field} = $gene;
                   10236:                 } elsif ($field eq 'permanentemail') {
                   10237:                     $names{$field} = $email;
                   10238:                 } elsif ($field eq 'id') {
                   10239:                     $names{$field}  = $uid;
                   10240:                 }
                   10241:             }
                   10242:         }
                   10243:     }
1.388     www      10244:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10245:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10246:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10247:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10248:     if ($email) {
                   10249:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10250:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10251:     }
1.899     raeburn  10252:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10253:     if (defined($inststatus)) {
                   10254:         $names{'inststatus'} = '';
                   10255:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10256:         if (ref($usertypes) eq 'HASH') {
                   10257:             my @okstatuses; 
                   10258:             foreach my $item (split(/:/,$inststatus)) {
                   10259:                 if (defined($usertypes->{$item})) {
                   10260:                     push(@okstatuses,$item);  
                   10261:                 }
                   10262:             }
                   10263:             if (@okstatuses) {
                   10264:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10265:             }
                   10266:         }
                   10267:     }
1.1075    raeburn  10268:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10269:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10270:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10271:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10272:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10273:     } else {
                   10274:         $logmsg .= ' during self creation';
                   10275:     }
1.1075    raeburn  10276:     my $changed;
                   10277:     if ($newuser) {
                   10278:         $changed = 1;
                   10279:     } else {
                   10280:         foreach my $field (@fields) {
                   10281:             if ($names{$field} ne $oldnames{$field}) {
                   10282:                 $changed = 1;
                   10283:                 last;
                   10284:             }
                   10285:         }
                   10286:     }
                   10287:     unless ($changed) {
                   10288:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10289:         &logthis($logmsg);
                   10290:         return 'ok';
                   10291:     }
                   10292:     my $reply = &put('environment', \%names, $udom,$uname);
                   10293:     if ($reply ne 'ok') { 
                   10294:         return 'error: '.$reply;
                   10295:     }
1.1087    raeburn  10296:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10297:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10298:     }
1.1075    raeburn  10299:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10300:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10301:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10302:     &logthis($logmsg);
1.134     albertel 10303:     return 'ok';
1.80      www      10304: }
                   10305: 
1.81      www      10306: # -------------------------------------------------------------- Modify student
1.80      www      10307: 
1.81      www      10308: sub modifystudent {
                   10309:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10310:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10311:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10312:     if (!$cid) {
1.620     albertel 10313: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10314: 	    return 'not_in_class';
                   10315: 	}
1.80      www      10316:     }
                   10317: # --------------------------------------------------------------- Make the user
1.81      www      10318:     my $reply=&modifyuser
1.209     matthew  10319: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10320:          $desiredhome,$email,$inststatus);
1.80      www      10321:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10322:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10323:     # student's environment
1.297     matthew  10324:     $uid = undef if (!$forceid);
1.455     albertel 10325:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10326: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10327:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10328:     return $reply;
                   10329: }
                   10330: 
                   10331: sub modify_student_enrollment {
1.1172.2.23  raeburn  10332:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10333:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10334:     my ($cdom,$cnum,$chome);
                   10335:     if (!$cid) {
1.620     albertel 10336: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10337: 	    return 'not_in_class';
                   10338: 	}
1.620     albertel 10339: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10340: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10341:     } else {
                   10342: 	($cdom,$cnum)=split(/_/,$cid);
                   10343:     }
1.620     albertel 10344:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10345:     if (!$chome) {
1.457     raeburn  10346: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10347:     }
1.455     albertel 10348:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10349:     # Make sure the user exists
1.81      www      10350:     my $uhome=&homeserver($uname,$udom);
                   10351:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10352: 	return 'error: no such user';
                   10353:     }
1.297     matthew  10354:     # Get student data if we were not given enough information
                   10355:     if (!defined($first)  || $first  eq '' || 
                   10356:         !defined($last)   || $last   eq '' || 
                   10357:         !defined($uid)    || $uid    eq '' || 
                   10358:         !defined($middle) || $middle eq '' || 
                   10359:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10360:         # They did not supply us with enough data to enroll the student, so
                   10361:         # we need to pick up more information.
1.297     matthew  10362:         my %tmp = &get('environment',
1.294     matthew  10363:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10364:                        ,$udom,$uname);
                   10365: 
1.800     albertel 10366:         #foreach my $key (keys(%tmp)) {
                   10367:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10368:         #}
1.294     matthew  10369:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10370:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10371:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10372:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10373:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10374:     }
1.556     albertel 10375:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10376:     my $user = "$uname:$udom";
                   10377:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10378:     my $reply=cput('classlist',
1.1148    raeburn  10379: 		   {$user => 
1.1172.2.76  raeburn  10380: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10381: 		   $cdom,$cnum);
1.1148    raeburn  10382:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10383:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10384:     } else { 
1.81      www      10385: 	return 'error: '.$reply;
                   10386:     }
1.297     matthew  10387:     # Add student role to user
1.83      www      10388:     my $uurl='/'.$cid;
1.81      www      10389:     $uurl=~s/\_/\//g;
                   10390:     if ($usec) {
                   10391: 	$uurl.='/'.$usec;
                   10392:     }
1.1148    raeburn  10393:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10394:                              $selfenroll,$context);
                   10395:     if ($result ne 'ok') {
                   10396:         if ($old_entry{$user} ne '') {
                   10397:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10398:         } else {
                   10399:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10400:         }
                   10401:     }
                   10402:     return $result; 
1.21      www      10403: }
                   10404: 
1.556     albertel 10405: sub format_name {
                   10406:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10407:     my $name;
                   10408:     if ($first ne 'lastname') {
                   10409: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10410:     } else {
                   10411: 	if ($lastname=~/\S/) {
                   10412: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10413: 	    $name=~s/\s+,/,/;
                   10414: 	} else {
                   10415: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10416: 	}
                   10417:     }
                   10418:     $name=~s/^\s+//;
                   10419:     $name=~s/\s+$//;
                   10420:     $name=~s/\s+/ /g;
                   10421:     return $name;
                   10422: }
                   10423: 
1.84      www      10424: # ------------------------------------------------- Write to course preferences
                   10425: 
                   10426: sub writecoursepref {
                   10427:     my ($courseid,%prefs)=@_;
                   10428:     $courseid=~s/^\///;
                   10429:     $courseid=~s/\_/\//g;
                   10430:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10431:     my $chome=homeserver($cnum,$cdomain);
                   10432:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10433: 	return 'error: no such course';
                   10434:     }
                   10435:     my $cstring='';
1.800     albertel 10436:     foreach my $pref (keys(%prefs)) {
                   10437: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10438:     }
1.84      www      10439:     $cstring=~s/\&$//;
                   10440:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10441: }
                   10442: 
                   10443: # ---------------------------------------------------------- Make/modify course
                   10444: 
                   10445: sub createcourse {
1.741     raeburn  10446:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10447:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10448:     $url=&declutter($url);
                   10449:     my $cid='';
1.1028    raeburn  10450:     if ($context eq 'requestcourses') {
                   10451:         my $can_create = 0;
                   10452:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10453:         if ($udom eq $ownerdom) {
                   10454:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10455:                                   $context)) {
                   10456:                 $can_create = 1;
                   10457:             }
                   10458:         } else {
                   10459:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10460:                                            $category);
                   10461:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10462:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10463:                 if (@curr > 0) {
                   10464:                     my @options = qw(approval validate autolimit);
                   10465:                     my $optregex = join('|',@options);
                   10466:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10467:                         $can_create = 1;
                   10468:                     }
                   10469:                 }
                   10470:             }
                   10471:         }
                   10472:         if ($can_create) {
                   10473:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10474:                 unless (&allowed('ccc',$udom)) {
                   10475:                     return 'refused'; 
                   10476:                 }
1.1017    raeburn  10477:             }
                   10478:         } else {
                   10479:             return 'refused';
                   10480:         }
1.1028    raeburn  10481:     } elsif (!&allowed('ccc',$udom)) {
                   10482:         return 'refused';
1.84      www      10483:     }
1.1011    raeburn  10484: # --------------------------------------------------------------- Get Unique ID
                   10485:     my $uname;
                   10486:     if ($cnum =~ /^$match_courseid$/) {
                   10487:         my $chome=&homeserver($cnum,$udom,'true');
                   10488:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10489:             $uname = $cnum;
                   10490:         } else {
1.1038    raeburn  10491:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10492:         }
                   10493:     } else {
1.1038    raeburn  10494:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10495:     }
                   10496:     return $uname if ($uname =~ /^error/);
                   10497: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10498:     if (!defined($course_server)) {
                   10499:         if (defined(&domain($udom,'primary'))) {
                   10500:             $course_server = &domain($udom,'primary');
                   10501:         } else {
                   10502:             $course_server = $env{'user.home'}; 
                   10503:         }
                   10504:     }
                   10505:     my %host_servers =
                   10506:         &Apache::lonnet::get_servers($udom,'library');
                   10507:     unless ($host_servers{$course_server}) {
                   10508:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10509:     }
1.84      www      10510: # ------------------------------------------------------------- Make the course
                   10511:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10512:                       $course_server);
1.84      www      10513:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10514:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10515:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10516: 	return 'error: no such course';
                   10517:     }
1.271     www      10518: # ----------------------------------------------------------------- Course made
1.516     raeburn  10519: # log existence
1.1029    raeburn  10520:     my $now = time;
1.918     raeburn  10521:     my $newcourse = {
                   10522:                     $udom.'_'.$uname => {
1.921     raeburn  10523:                                      description => $description,
                   10524:                                      inst_code   => $inst_code,
                   10525:                                      owner       => $course_owner,
                   10526:                                      type        => $crstype,
1.1029    raeburn  10527:                                      creator     => $env{'user.name'}.':'.
                   10528:                                                     $env{'user.domain'},
                   10529:                                      created     => $now,
                   10530:                                      context     => $context,
1.918     raeburn  10531:                                                 },
                   10532:                     };
1.921     raeburn  10533:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10534: # set toplevel url
1.271     www      10535:     my $topurl=$url;
                   10536:     unless ($nonstandard) {
                   10537: # ------------------------------------------ For standard courses, make top url
                   10538:         my $mapurl=&clutter($url);
1.278     www      10539:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10540:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10541: <map>
                   10542: <resource id="1" type="start"></resource>
                   10543: <resource id="2" src="$mapurl"></resource>
                   10544: <resource id="3" type="finish"></resource>
                   10545: <link index="1" from="1" to="2"></link>
                   10546: <link index="2" from="2" to="3"></link>
                   10547: </map>
                   10548: ENDINITMAP
                   10549:         $topurl=&declutter(
1.638     albertel 10550:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10551:                           );
                   10552:     }
                   10553: # ----------------------------------------------------------- Write preferences
1.84      www      10554:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10555:                      ('description'              => $description,
                   10556:                       'url'                      => $topurl,
                   10557:                       'internal.creator'         => $env{'user.name'}.':'.
                   10558:                                                     $env{'user.domain'},
                   10559:                       'internal.created'         => $now,
                   10560:                       'internal.creationcontext' => $context)
                   10561:                     );
1.84      www      10562:     return '/'.$udom.'/'.$uname;
                   10563: }
                   10564: 
1.1011    raeburn  10565: # ------------------------------------------------------------------- Create ID
                   10566: sub generate_coursenum {
1.1038    raeburn  10567:     my ($udom,$crstype) = @_;
1.1011    raeburn  10568:     my $domdesc = &domain($udom);
                   10569:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10570:     my $first;
                   10571:     if ($crstype eq 'Community') {
                   10572:         $first = '0';
                   10573:     } else {
                   10574:         $first = int(1+rand(9)); 
                   10575:     } 
                   10576:     my $uname=$first.
1.1011    raeburn  10577:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10578:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10579:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10580: # ----------------------------------------------- Make sure that does not exist
                   10581:     my $uhome=&homeserver($uname,$udom,'true');
                   10582:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10583:         if ($crstype eq 'Community') {
                   10584:             $first = '0';
                   10585:         } else {
                   10586:             $first = int(1+rand(9));
                   10587:         }
                   10588:         $uname=$first.
1.1011    raeburn  10589:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10590:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10591:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10592:         $uhome=&homeserver($uname,$udom,'true');
                   10593:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10594:             return 'error: unable to generate unique course-ID';
                   10595:         }
                   10596:     }
                   10597:     return $uname;
                   10598: }
                   10599: 
1.813     albertel 10600: sub is_course {
1.1167    droeschl 10601:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10602:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10603:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10604:     my $uhome=&homeserver($cnum,$cdom);
                   10605:     my $iscourse;
                   10606:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10607:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10608:     } else {
                   10609:         my $hashid = $cdom.':'.$cnum;
                   10610:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10611:         unless (defined($cached)) {
                   10612:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10613:                                         $cnum,undef,undef,'.');
                   10614:             $iscourse = 0;
                   10615:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10616:                 $iscourse = 1;
                   10617:             }
                   10618:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10619:         }
                   10620:     }
                   10621:     return unless($iscourse);
1.1167    droeschl 10622:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10623: }
                   10624: 
1.1015    raeburn  10625: sub store_userdata {
                   10626:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10627:     my $result;
1.1016    raeburn  10628:     if ($datakey ne '') {
1.1013    raeburn  10629:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10630:             if ($udom eq '' || $uname eq '') {
                   10631:                 $udom = $env{'user.domain'};
                   10632:                 $uname = $env{'user.name'};
                   10633:             }
                   10634:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10635:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10636:                 $result = 'error: no_host';
                   10637:             } else {
1.1172.2.138  raeburn  10638:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10639:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10640: 
                   10641:                 my $namevalue='';
                   10642:                 foreach my $key (keys(%{$storehash})) {
                   10643:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10644:                 }
                   10645:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10646:                 unless ($namespace eq 'courserequests') {
                   10647:                     $datakey = &escape($datakey);
                   10648:                 }
1.1105    raeburn  10649:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10650:                                   $namevalue,$uhome);
1.1013    raeburn  10651:             }
                   10652:         } else {
                   10653:             $result = 'error: data to store was not a hash reference'; 
                   10654:         }
                   10655:     } else {
                   10656:         $result= 'error: invalid requestkey'; 
                   10657:     }
                   10658:     return $result;
                   10659: }
                   10660: 
1.21      www      10661: # ---------------------------------------------------------- Assign Custom Role
                   10662: 
                   10663: sub assigncustomrole {
1.957     raeburn  10664:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10665:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10666:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10667: }
                   10668: 
                   10669: # ----------------------------------------------------------------- Revoke Role
                   10670: 
                   10671: sub revokerole {
1.957     raeburn  10672:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10673:     my $now=time;
1.965     raeburn  10674:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10675: }
                   10676: 
                   10677: # ---------------------------------------------------------- Revoke Custom Role
                   10678: 
                   10679: sub revokecustomrole {
1.957     raeburn  10680:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10681:     my $now=time;
1.357     www      10682:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10683:            $deleteflag,$selfenroll,$context);
1.17      www      10684: }
                   10685: 
1.533     banghart 10686: # ------------------------------------------------------------ Disk usage
1.535     albertel 10687: sub diskusage {
1.955     raeburn  10688:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10689:     $directorypath =~ s/\/$//;
                   10690:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10691:                        .&escape($getpropath).':'.&escape($uname).':'
                   10692:                        .&escape($udom),homeserver($uname,$udom));
                   10693:     if ($listing eq 'unknown_cmd') {
                   10694:         if ($getpropath) {
                   10695:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10696:         }
                   10697:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10698:     }
1.514     albertel 10699:     return $listing;
1.512     banghart 10700: }
                   10701: 
1.566     banghart 10702: sub is_locked {
1.1096    raeburn  10703:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10704:     my @check;
                   10705:     my $is_locked;
1.1093    raeburn  10706:     push (@check,$file_name);
1.613     albertel 10707:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10708: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10709:     my ($tmp)=keys(%locked);
                   10710:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10711:     
1.566     banghart 10712:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10713:         $is_locked = 'false';
                   10714:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10715:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10716:                $is_locked = 'true';
1.1096    raeburn  10717:                if (ref($which) eq 'ARRAY') {
                   10718:                    push(@{$which},$entry);
                   10719:                } else {
                   10720:                    last;
                   10721:                }
1.745     raeburn  10722:            }
                   10723:        }
1.566     banghart 10724:     } else {
                   10725:         $is_locked = 'false';
                   10726:     }
1.1093    raeburn  10727:     return $is_locked;
1.566     banghart 10728: }
                   10729: 
1.759     albertel 10730: sub declutter_portfile {
                   10731:     my ($file) = @_;
1.833     albertel 10732:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10733:     return $file;
                   10734: }
                   10735: 
1.559     banghart 10736: # ------------------------------------------------------------- Mark as Read Only
                   10737: 
                   10738: sub mark_as_readonly {
                   10739:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10740:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10741:     my ($tmp)=keys(%current_permissions);
                   10742:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10743:     foreach my $file (@{$files}) {
1.759     albertel 10744: 	$file = &declutter_portfile($file);
1.561     banghart 10745:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10746:     }
1.613     albertel 10747:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10748:     return;
                   10749: }
                   10750: 
1.572     banghart 10751: # ------------------------------------------------------------Save Selected Files
                   10752: 
                   10753: sub save_selected_files {
                   10754:     my ($user, $path, @files) = @_;
                   10755:     my $filename = $user."savedfiles";
1.573     banghart 10756:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10757:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10758:     foreach my $file (@files) {
1.620     albertel 10759:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10760:     }
                   10761:     foreach my $file (@other_files) {
1.574     banghart 10762:         print (OUT $file."\n");
1.572     banghart 10763:     }
1.574     banghart 10764:     close (OUT);
1.572     banghart 10765:     return 'ok';
                   10766: }
                   10767: 
1.574     banghart 10768: sub clear_selected_files {
                   10769:     my ($user) = @_;
                   10770:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10771:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10772:     print (OUT undef);
                   10773:     close (OUT);
                   10774:     return ("ok");    
                   10775: }
                   10776: 
1.572     banghart 10777: sub files_in_path {
                   10778:     my ($user, $path) = @_;
                   10779:     my $filename = $user."savedfiles";
                   10780:     my %return_files;
1.1172.2.96  raeburn  10781:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10782:     while (my $line_in = <IN>) {
1.574     banghart 10783:         chomp ($line_in);
                   10784:         my @paths_and_file = split (m!/!, $line_in);
                   10785:         my $file_part = pop (@paths_and_file);
                   10786:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10787:         $path_part.='/';
                   10788:         my $path_and_file = $path_part.$file_part;
                   10789:         if ($path_part eq $path) {
                   10790:             $return_files{$file_part}= 'selected';
                   10791:         }
                   10792:     }
1.574     banghart 10793:     close (IN);
                   10794:     return (\%return_files);
1.572     banghart 10795: }
                   10796: 
                   10797: # called in portfolio select mode, to show files selected NOT in current directory
                   10798: sub files_not_in_path {
                   10799:     my ($user, $path) = @_;
                   10800:     my $filename = $user."savedfiles";
                   10801:     my @return_files;
                   10802:     my $path_part;
1.1172.2.96  raeburn  10803:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10804:     while (my $line = <IN>) {
1.572     banghart 10805:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10806:         my @paths_and_file = split(m|/|, $line);
                   10807:         my $file_part = pop(@paths_and_file);
                   10808:         chomp($file_part);
                   10809:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10810:         $path_part .= '/';
                   10811:         my $path_and_file = $path_part.$file_part;
                   10812:         if ($path_part ne $path) {
1.800     albertel 10813:             push(@return_files, ($path_and_file));
1.572     banghart 10814:         }
                   10815:     }
1.800     albertel 10816:     close(OUT);
1.574     banghart 10817:     return (@return_files);
1.572     banghart 10818: }
                   10819: 
1.745     raeburn  10820: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10821: 
1.745     raeburn  10822: sub get_portfile_permissions {
                   10823:     my ($domain,$user) = @_;
1.613     albertel 10824:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10825:     my ($tmp)=keys(%current_permissions);
                   10826:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10827:     return \%current_permissions;
                   10828: }
                   10829: 
                   10830: #---------------------------------------------Get portfolio file access controls
                   10831: 
1.749     raeburn  10832: sub get_access_controls {
1.745     raeburn  10833:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10834:     my %access;
                   10835:     my $real_file = $file;
                   10836:     $file =~ s/\.meta$//;
1.745     raeburn  10837:     if (defined($file)) {
1.749     raeburn  10838:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10839:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10840:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10841:             }
                   10842:         }
1.745     raeburn  10843:     } else {
1.749     raeburn  10844:         foreach my $key (keys(%{$current_permissions})) {
                   10845:             if ($key =~ /\0accesscontrol$/) {
                   10846:                 if (defined($group)) {
                   10847:                     if ($key !~ m-^\Q$group\E/-) {
                   10848:                         next;
                   10849:                     }
                   10850:                 }
                   10851:                 my ($fullpath) = split(/\0/,$key);
                   10852:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10853:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10854:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10855:                     }
                   10856:                 }
                   10857:             }
                   10858:         }
                   10859:     }
                   10860:     return %access;
                   10861: }
                   10862: 
                   10863: sub modify_access_controls {
                   10864:     my ($file_name,$changes,$domain,$user)=@_;
                   10865:     my ($outcome,$deloutcome);
                   10866:     my %store_permissions;
                   10867:     my %new_values;
                   10868:     my %new_control;
                   10869:     my %translation;
                   10870:     my @deletions = ();
                   10871:     my $now = time;
                   10872:     if (exists($$changes{'activate'})) {
                   10873:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10874:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10875:             my $numnew = scalar(@newitems);
                   10876:             for (my $i=0; $i<$numnew; $i++) {
                   10877:                 my $newkey = $newitems[$i];
                   10878:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10879:                 if ($newkey =~ /^\d+:/) { 
                   10880:                     $newkey =~ s/^(\d+)/$newid/;
                   10881:                     $translation{$1} = $newid;
                   10882:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10883:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10884:                     $translation{$1} = $newid;
                   10885:                 }
1.749     raeburn  10886:                 $new_values{$file_name."\0".$newkey} = 
                   10887:                                           $$changes{'activate'}{$newitems[$i]};
                   10888:                 $new_control{$newkey} = $now;
                   10889:             }
                   10890:         }
                   10891:     }
                   10892:     my %todelete;
                   10893:     my %changed_items;
                   10894:     foreach my $action ('delete','update') {
                   10895:         if (exists($$changes{$action})) {
                   10896:             if (ref($$changes{$action}) eq 'HASH') {
                   10897:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10898:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10899:                     if ($action eq 'delete') { 
                   10900:                         $todelete{$itemnum} = 1;
                   10901:                     } else {
                   10902:                         $changed_items{$itemnum} = $key;
                   10903:                     }
                   10904:                 }
1.745     raeburn  10905:             }
                   10906:         }
1.749     raeburn  10907:     }
                   10908:     # get lock on access controls for file.
                   10909:     my $lockhash = {
                   10910:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10911:                                                        ':'.$env{'user.domain'},
                   10912:                    }; 
                   10913:     my $tries = 0;
                   10914:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10915:    
1.1172.2.79  raeburn  10916:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10917:         $tries ++;
1.1172.2.79  raeburn  10918:         sleep(0.1);
1.749     raeburn  10919:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10920:     }
                   10921:     if ($gotlock eq 'ok') {
                   10922:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10923:         my ($tmp)=keys(%curr_permissions);
                   10924:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10925:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10926:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10927:             if (ref($curr_controls) eq 'HASH') {
                   10928:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10929:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10930:                     if (defined($todelete{$itemnum})) {
                   10931:                         push(@deletions,$file_name."\0".$control_item);
                   10932:                     } else {
                   10933:                         if (defined($changed_items{$itemnum})) {
                   10934:                             $new_control{$changed_items{$itemnum}} = $now;
                   10935:                             push(@deletions,$file_name."\0".$control_item);
                   10936:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10937:                         } else {
                   10938:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10939:                         }
                   10940:                     }
1.745     raeburn  10941:                 }
                   10942:             }
                   10943:         }
1.970     raeburn  10944:         my ($group);
                   10945:         if (&is_course($domain,$user)) {
                   10946:             ($group,my $file) = split(/\//,$file_name,2);
                   10947:         }
1.749     raeburn  10948:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10949:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10950:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10951:         #  remove lock
                   10952:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10953:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10954:         my $sqlresult =
1.970     raeburn  10955:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10956:                                     $group);
1.749     raeburn  10957:     } else {
                   10958:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10959:     }
1.749     raeburn  10960:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10961: }
                   10962: 
1.827     raeburn  10963: sub make_public_indefinitely {
                   10964:     my ($requrl) = @_;
                   10965:     my $now = time;
                   10966:     my $action = 'activate';
                   10967:     my $aclnum = 0;
                   10968:     if (&is_portfolio_url($requrl)) {
                   10969:         my (undef,$udom,$unum,$file_name,$group) =
                   10970:             &parse_portfolio_url($requrl);
                   10971:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10972:         my %access_controls = &get_access_controls($current_perms,
                   10973:                                                    $group,$file_name);
                   10974:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10975:             my ($num,$scope,$end,$start) = 
                   10976:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10977:             if ($scope eq 'public') {
                   10978:                 if ($start <= $now && $end == 0) {
                   10979:                     $action = 'none';
                   10980:                 } else {
                   10981:                     $action = 'update';
                   10982:                     $aclnum = $num;
                   10983:                 }
                   10984:                 last;
                   10985:             }
                   10986:         }
                   10987:         if ($action eq 'none') {
                   10988:              return 'ok';
                   10989:         } else {
                   10990:             my %changes;
                   10991:             my $newend = 0;
                   10992:             my $newstart = $now;
                   10993:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10994:             $changes{$action}{$newkey} = {
                   10995:                 type => 'public',
                   10996:                 time => {
                   10997:                     start => $newstart,
                   10998:                     end   => $newend,
                   10999:                 },
                   11000:             };
                   11001:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11002:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11003:             return $outcome;
                   11004:         }
                   11005:     } else {
                   11006:         return 'invalid';
                   11007:     }
                   11008: }
                   11009: 
1.745     raeburn  11010: #------------------------------------------------------Get Marked as Read Only
                   11011: 
                   11012: sub get_marked_as_readonly {
                   11013:     my ($domain,$user,$what,$group) = @_;
                   11014:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11015:     my @readonly_files;
1.629     banghart 11016:     my $cmp1=$what;
                   11017:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11018:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11019:         if (defined($group)) {
                   11020:             if ($file_name !~ m-^\Q$group\E/-) {
                   11021:                 next;
                   11022:             }
                   11023:         }
1.561     banghart 11024:         if (ref($value) eq "ARRAY"){
                   11025:             foreach my $stored_what (@{$value}) {
1.629     banghart 11026:                 my $cmp2=$stored_what;
1.759     albertel 11027:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11028:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11029:                 }
1.629     banghart 11030:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11031:                     push(@readonly_files, $file_name);
1.745     raeburn  11032:                     last;
1.563     banghart 11033:                 } elsif (!defined($what)) {
                   11034:                     push(@readonly_files, $file_name);
1.745     raeburn  11035:                     last;
1.561     banghart 11036:                 }
                   11037:             }
1.745     raeburn  11038:         }
1.561     banghart 11039:     }
                   11040:     return @readonly_files;
                   11041: }
1.577     banghart 11042: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11043: 
1.577     banghart 11044: sub get_marked_as_readonly_hash {
1.745     raeburn  11045:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11046:     my %readonly_files;
1.745     raeburn  11047:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11048:         if (defined($group)) {
                   11049:             if ($file_name !~ m-^\Q$group\E/-) {
                   11050:                 next;
                   11051:             }
                   11052:         }
1.577     banghart 11053:         if (ref($value) eq "ARRAY"){
                   11054:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11055:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11056:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11057:                         if ($lock_descriptor eq 'graded') {
                   11058:                             $readonly_files{$file_name} = 'graded';
                   11059:                         } elsif ($lock_descriptor eq 'handback') {
                   11060:                             $readonly_files{$file_name} = 'handback';
                   11061:                         } else {
                   11062:                             if (!exists($readonly_files{$file_name})) {
                   11063:                                 $readonly_files{$file_name} = 'locked';
                   11064:                             }
                   11065:                         }
1.745     raeburn  11066:                     }
1.750     banghart 11067:                 } 
1.577     banghart 11068:             }
                   11069:         } 
                   11070:     }
                   11071:     return %readonly_files;
                   11072: }
1.559     banghart 11073: # ------------------------------------------------------------ Unmark as Read Only
                   11074: 
                   11075: sub unmark_as_readonly {
1.629     banghart 11076:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11077:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11078:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11079:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11080:     my $symb_crs = $what;
                   11081:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11082:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11083:     my ($tmp)=keys(%current_permissions);
                   11084:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11085:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11086:     foreach my $file (@readonly_files) {
1.759     albertel 11087: 	my $clean_file = &declutter_portfile($file);
                   11088: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11089: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11090:         my @new_locks;
                   11091:         my @del_keys;
                   11092:         if (ref($current_locks) eq "ARRAY"){
                   11093:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11094:                 my $compare=$locker;
1.749     raeburn  11095:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11096:                     $compare=join('',@{$locker});
1.746     raeburn  11097:                     if ($compare ne $symb_crs) {
                   11098:                         push(@new_locks, $locker);
                   11099:                     }
1.563     banghart 11100:                 }
                   11101:             }
1.650     albertel 11102:             if (scalar(@new_locks) > 0) {
1.563     banghart 11103:                 $current_permissions{$file} = \@new_locks;
                   11104:             } else {
                   11105:                 push(@del_keys, $file);
1.613     albertel 11106:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11107:                 delete($current_permissions{$file});
1.563     banghart 11108:             }
                   11109:         }
1.561     banghart 11110:     }
1.613     albertel 11111:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11112:     return;
                   11113: }
1.512     banghart 11114: 
1.17      www      11115: # ------------------------------------------------------------ Directory lister
                   11116: 
                   11117: sub dirlist {
1.955     raeburn  11118:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11119:     $uri=~s/^\///;
                   11120:     $uri=~s/\/$//;
1.253     stredwic 11121:     my ($udom, $uname);
1.955     raeburn  11122:     if ($getuserdir) {
1.253     stredwic 11123:         $udom = $userdomain;
                   11124:         $uname = $username;
1.955     raeburn  11125:     } else {
                   11126:         (undef,$udom,$uname)=split(/\//,$uri);
                   11127:         if(defined($userdomain)) {
                   11128:             $udom = $userdomain;
                   11129:         }
                   11130:         if(defined($username)) {
                   11131:             $uname = $username;
                   11132:         }
1.253     stredwic 11133:     }
1.955     raeburn  11134:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11135: 
1.955     raeburn  11136:     $dirRoot = $perlvar{'lonDocRoot'};
                   11137:     if (defined($getpropath)) {
                   11138:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11139:         $dirRoot =~ s/\/$//;
1.955     raeburn  11140:     } elsif (defined($getuserdir)) {
                   11141:         my $subdir=$uname.'__';
                   11142:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11143:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11144:                    ."/$udom/$subdir/$uname";
                   11145:     } elsif (defined($alternateRoot)) {
                   11146:         $dirRoot = $alternateRoot;
1.751     banghart 11147:     }
1.253     stredwic 11148: 
                   11149:     if($udom) {
                   11150:         if($uname) {
1.1135    raeburn  11151:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11152:             if ($uhome eq 'no_host') {
                   11153:                 return ([],'no_host');
                   11154:             }
1.955     raeburn  11155:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11156:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11157:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11158:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11159:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11160:             } else {
                   11161:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11162:             }
1.605     matthew  11163:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11164:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11165:                 @listing_results = split(/:/,$listing);
                   11166:             } else {
                   11167:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11168:             }
1.1135    raeburn  11169:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11170:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11171:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11172:                 return ([],$listing);
                   11173:             } else {
                   11174:                 return (\@listing_results);
1.1135    raeburn  11175:             }
1.955     raeburn  11176:         } elsif(!$alternateRoot) {
1.1136    raeburn  11177:             my (%allusers,%listerror);
1.841     albertel 11178: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11179:  	    foreach my $tryserver (keys(%servers)) {
                   11180:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11181:                                   &escape($udom),$tryserver);
                   11182:                 if ($listing eq 'unknown_cmd') {
                   11183: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11184: 				      $udom, $tryserver);
                   11185:                 } else {
                   11186:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11187:                 }
1.841     albertel 11188: 		if ($listing eq 'unknown_cmd') {
                   11189: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11190: 				      $udom, $tryserver);
                   11191: 		    @listing_results = split(/:/,$listing);
                   11192: 		} else {
                   11193: 		    @listing_results =
                   11194: 			map { &unescape($_); } split(/:/,$listing);
                   11195: 		}
1.1136    raeburn  11196:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11197:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11198:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11199:                     $listerror{$tryserver} = $listing;
                   11200:                 } else {
1.841     albertel 11201: 		    foreach my $line (@listing_results) {
                   11202: 			my ($entry) = split(/&/,$line,2);
                   11203: 			$allusers{$entry} = 1;
                   11204: 		    }
                   11205: 		}
1.253     stredwic 11206:             }
1.1136    raeburn  11207:             my @alluserslist=();
1.800     albertel 11208:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11209:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11210:             }
1.1172.2.80  raeburn  11211:             if (!%listerror) {
                   11212:                 # no errors
                   11213:                 return (\@alluserslist);
                   11214:             } elsif (scalar(keys(%servers)) == 1) {
                   11215:                 # one library server, one error
                   11216:                 my ($key) = keys(%listerror);
                   11217:                 return (\@alluserslist, $listerror{$key});
                   11218:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11219:                 # con_lost indicates that we might miss data from at least one
                   11220:                 # library server
                   11221:                 return (\@alluserslist, 'con_lost');
                   11222:             } else {
                   11223:                 # multiple library servers and no con_lost -> data should be
                   11224:                 # complete.
                   11225:                 return (\@alluserslist);
                   11226:             }
                   11227: 
1.253     stredwic 11228:         } else {
1.1136    raeburn  11229:             return ([],'missing username');
1.253     stredwic 11230:         }
1.955     raeburn  11231:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11232:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11233:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11234:         return (\@all_domains);
1.955     raeburn  11235:     } else {
1.1136    raeburn  11236:         return ([],'missing domain');
1.275     stredwic 11237:     }
                   11238: }
                   11239: 
                   11240: # --------------------------------------------- GetFileTimestamp
                   11241: # This function utilizes dirlist and returns the date stamp for
                   11242: # when it was last modified.  It will also return an error of -1
                   11243: # if an error occurs
                   11244: 
                   11245: sub GetFileTimestamp {
1.955     raeburn  11246:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11247:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11248:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11249:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11250:                                     undef,$getuserdir);
                   11251:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11252:         return -1;
                   11253:     }
                   11254:     if (ref($fileref) eq 'ARRAY') {
                   11255:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11256:         # @stats contains first the filename, then the stat output
                   11257:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11258:     } else {
                   11259:         return -1;
1.253     stredwic 11260:     }
1.26      www      11261: }
                   11262: 
1.712     albertel 11263: sub stat_file {
                   11264:     my ($uri) = @_;
1.787     albertel 11265:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11266: 
1.955     raeburn  11267:     my ($udom,$uname,$file);
1.712     albertel 11268:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11269: 	($udom,$uname,$file) =
1.811     albertel 11270: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11271: 	$file = 'userfiles/'.$file;
                   11272:     }
                   11273:     if ($uri =~ m-^/res/-) {
                   11274: 	($udom,$uname) = 
1.807     albertel 11275: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11276: 	$file = $uri;
                   11277:     }
                   11278: 
                   11279:     if (!$udom || !$uname || !$file) {
                   11280: 	# unable to handle the uri
                   11281: 	return ();
                   11282:     }
1.956     raeburn  11283:     my $getpropath;
                   11284:     if ($file =~ /^userfiles\//) {
                   11285:         $getpropath = 1;
                   11286:     }
1.1136    raeburn  11287:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11288:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11289:         return ();
                   11290:     } else {
                   11291:         if (ref($listref) eq 'ARRAY') {
                   11292:             my @stats = split('&',$listref->[0]);
                   11293: 	    shift(@stats); #filename is first
                   11294: 	    return @stats;
                   11295:         }
1.712     albertel 11296:     }
                   11297:     return ();
                   11298: }
                   11299: 
1.26      www      11300: # -------------------------------------------------------- Value of a Condition
                   11301: 
1.713     albertel 11302: # gets the value of a specific preevaluated condition
                   11303: #    stored in the string  $env{user.state.<cid>}
                   11304: # or looks up a condition reference in the bighash and if if hasn't
                   11305: # already been evaluated recurses into docondval to get the value of
                   11306: # the condition, then memoizing it to 
                   11307: #   $env{user.state.<cid>.<condition>}
1.40      www      11308: sub directcondval {
                   11309:     my $number=shift;
1.620     albertel 11310:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11311: 	&Apache::lonuserstate::evalstate();
                   11312:     }
1.713     albertel 11313:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11314: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11315:     } elsif ($number =~ /^_/) {
                   11316: 	my $sub_condition;
                   11317: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11318: 		&GDBM_READER(),0640)) {
                   11319: 	    $sub_condition=$bighash{'conditions'.$number};
                   11320: 	    untie(%bighash);
                   11321: 	}
                   11322: 	my $value = &docondval($sub_condition);
1.949     raeburn  11323: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11324: 	return $value;
                   11325:     }
1.620     albertel 11326:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11327:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11328:     } else {
                   11329:        return 2;
                   11330:     }
                   11331: }
                   11332: 
1.713     albertel 11333: # get the collection of conditions for this resource
1.26      www      11334: sub condval {
                   11335:     my $condidx=shift;
1.54      www      11336:     my $allpathcond='';
1.713     albertel 11337:     foreach my $cond (split(/\|/,$condidx)) {
                   11338: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11339: 	    $allpathcond.=
                   11340: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11341: 	}
1.191     harris41 11342:     }
1.54      www      11343:     $allpathcond=~s/\|$//;
1.713     albertel 11344:     return &docondval($allpathcond);
                   11345: }
                   11346: 
                   11347: #evaluates an expression of conditions
                   11348: sub docondval {
                   11349:     my ($allpathcond) = @_;
                   11350:     my $result=0;
                   11351:     if ($env{'request.course.id'}
                   11352: 	&& defined($allpathcond)) {
                   11353: 	my $operand='|';
                   11354: 	my @stack;
                   11355: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11356: 	    if ($chunk eq '(') {
                   11357: 		push @stack,($operand,$result);
                   11358: 	    } elsif ($chunk eq ')') {
                   11359: 		my $before=pop @stack;
                   11360: 		if (pop @stack eq '&') {
                   11361: 		    $result=$result>$before?$before:$result;
                   11362: 		} else {
                   11363: 		    $result=$result>$before?$result:$before;
                   11364: 		}
                   11365: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11366: 		$operand=$chunk;
                   11367: 	    } else {
                   11368: 		my $new=directcondval($chunk);
                   11369: 		if ($operand eq '&') {
                   11370: 		    $result=$result>$new?$new:$result;
                   11371: 		} else {
                   11372: 		    $result=$result>$new?$result:$new;
                   11373: 		}
                   11374: 	    }
                   11375: 	}
1.26      www      11376:     }
                   11377:     return $result;
1.421     albertel 11378: }
                   11379: 
                   11380: # ---------------------------------------------------- Devalidate courseresdata
                   11381: 
                   11382: sub devalidatecourseresdata {
                   11383:     my ($coursenum,$coursedomain)=@_;
                   11384:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11385:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11386: }
                   11387: 
1.763     www      11388: 
1.200     www      11389: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11390: #
                   11391: #  Parameters:
                   11392: #      $coursenum    - Number of the course.
                   11393: #      $coursedomain - Domain at which the course was created.
                   11394: #  Returns:
                   11395: #     A hash of the course parameters along (I think) with timestamps
                   11396: #     and version info.
1.877     foxr     11397: 
1.624     albertel 11398: sub get_courseresdata {
                   11399:     my ($coursenum,$coursedomain)=@_;
1.200     www      11400:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11401:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11402:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11403:     my %dumpreply;
1.417     albertel 11404:     unless (defined($cached)) {
1.624     albertel 11405: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11406: 	$result=\%dumpreply;
1.251     albertel 11407: 	my ($tmp) = keys(%dumpreply);
                   11408: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11409: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11410: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11411: 	    return $tmp;
1.416     albertel 11412: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11413: 	    $result=undef;
1.599     albertel 11414: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11415: 	}
                   11416:     }
1.624     albertel 11417:     return $result;
                   11418: }
                   11419: 
1.633     albertel 11420: sub devalidateuserresdata {
                   11421:     my ($uname,$udom)=@_;
                   11422:     my $hashid="$udom:$uname";
                   11423:     &devalidate_cache_new('userres',$hashid);
                   11424: }
                   11425: 
1.624     albertel 11426: sub get_userresdata {
                   11427:     my ($uname,$udom)=@_;
                   11428:     #most student don\'t have any data set, check if there is some data
                   11429:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11430: 
                   11431:     my $hashid="$udom:$uname";
                   11432:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11433:     if (!defined($cached)) {
                   11434: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11435: 	$result=\%resourcedata;
                   11436: 	&do_cache_new('userres',$hashid,$result,600);
                   11437:     }
                   11438:     my ($tmp)=keys(%$result);
                   11439:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11440: 	return $result;
                   11441:     }
                   11442:     #error 2 occurs when the .db doesn't exist
                   11443:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11444:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11445: 	    &logthis("<font color=\"blue\">WARNING:".
                   11446: 		     " Trying to get resource data for ".
                   11447: 		     $uname." at ".$udom.": ".
                   11448: 		     $tmp."</font>");
                   11449:         }
1.624     albertel 11450:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11451: 	#&EXT_cache_set($udom,$uname);
                   11452: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11453: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11454:     }
                   11455:     return $tmp;
                   11456: }
1.879     foxr     11457: #----------------------------------------------- resdata - return resource data
                   11458: #  Purpose:
                   11459: #    Return resource data for either users or for a course.
                   11460: #  Parameters:
                   11461: #     $name      - Course/user name.
                   11462: #     $domain    - Name of the domain the user/course is registered on.
                   11463: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11464: #     @which     - Array of names of resources desired.
                   11465: #  Returns:
                   11466: #     The value of the first reasource in @which that is found in the
                   11467: #     resource hash.
                   11468: #  Exceptional Conditions:
                   11469: #     If the $type passed in is not valid (not the string 'course' or 
                   11470: #     'user', an undefined  reference is returned.
                   11471: #     If none of the resources are found, an undef is returned
1.624     albertel 11472: sub resdata {
                   11473:     my ($name,$domain,$type,@which)=@_;
                   11474:     my $result;
                   11475:     if ($type eq 'course') {
                   11476: 	$result=&get_courseresdata($name,$domain);
                   11477:     } elsif ($type eq 'user') {
                   11478: 	$result=&get_userresdata($name,$domain);
                   11479:     }
                   11480:     if (!ref($result)) { return $result; }    
1.251     albertel 11481:     foreach my $item (@which) {
1.927     albertel 11482: 	if (defined($result->{$item->[0]})) {
                   11483: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11484: 	}
1.250     albertel 11485:     }
1.291     albertel 11486:     return undef;
1.200     www      11487: }
                   11488: 
1.1172.2.31  raeburn  11489: sub get_numsuppfiles {
                   11490:     my ($cnum,$cdom,$ignorecache)=@_;
                   11491:     my $hashid=$cnum.':'.$cdom;
                   11492:     my ($suppcount,$cached);
                   11493:     unless ($ignorecache) {
                   11494:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11495:     }
                   11496:     unless (defined($cached)) {
                   11497:         my $chome=&homeserver($cnum,$cdom);
                   11498:         unless ($chome eq 'no_host') {
                   11499:             ($suppcount,my $errors) = (0,0);
                   11500:             my $suppmap = 'supplemental.sequence';
                   11501:             ($suppcount,$errors) =
                   11502:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11503:         }
                   11504:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11505:     }
                   11506:     return $suppcount;
                   11507: }
                   11508: 
1.379     matthew  11509: #
                   11510: # EXT resource caching routines
                   11511: #
                   11512: 
                   11513: sub clear_EXT_cache_status {
1.383     albertel 11514:     &delenv('cache.EXT.');
1.379     matthew  11515: }
                   11516: 
                   11517: sub EXT_cache_status {
                   11518:     my ($target_domain,$target_user) = @_;
1.383     albertel 11519:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11520:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11521:         # We know already the user has no data
                   11522:         return 1;
                   11523:     } else {
                   11524:         return 0;
                   11525:     }
                   11526: }
                   11527: 
                   11528: sub EXT_cache_set {
                   11529:     my ($target_domain,$target_user) = @_;
1.383     albertel 11530:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11531:     #&appenv({$cachename => time});
1.379     matthew  11532: }
                   11533: 
1.28      www      11534: # --------------------------------------------------------- Value of a Variable
1.58      www      11535: sub EXT {
1.715     albertel 11536: 
1.1172.2.28  raeburn  11537:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11538:     unless ($varname) { return ''; }
1.218     albertel 11539:     #get real user name/domain, courseid and symb
                   11540:     my $courseid;
1.359     albertel 11541:     my $publicuser;
1.427     www      11542:     if ($symbparm) {
                   11543: 	$symbparm=&get_symb_from_alias($symbparm);
                   11544:     }
1.218     albertel 11545:     if (!($uname && $udom)) {
1.790     albertel 11546:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11547:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11548:     } else {
1.620     albertel 11549: 	$courseid=$env{'request.course.id'};
1.218     albertel 11550:     }
1.48      www      11551:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11552:     my $rest;
1.320     albertel 11553:     if (defined($therest[0])) {
1.48      www      11554:        $rest=join('.',@therest);
                   11555:     } else {
                   11556:        $rest='';
                   11557:     }
1.320     albertel 11558: 
1.57      www      11559:     my $qualifierrest=$qualifier;
                   11560:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11561:     my $spacequalifierrest=$space;
                   11562:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11563:     if ($realm eq 'user') {
1.48      www      11564: # --------------------------------------------------------------- user.resource
                   11565: 	if ($space eq 'resource') {
1.651     albertel 11566: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11567: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11568: 		 &&
1.1172.2.142  raeburn  11569: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11570: 		# if we are in the middle of processing the resource the
                   11571: 		# get the value we are planning on committing
                   11572:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11573:                     return $Apache::lonhomework::results{$qualifierrest};
                   11574:                 } else {
                   11575:                     return $Apache::lonhomework::history{$qualifierrest};
                   11576:                 }
1.335     albertel 11577: 	    } else {
1.359     albertel 11578: 		my %restored;
1.620     albertel 11579: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11580: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11581: 		} else {
                   11582: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11583: 		}
1.335     albertel 11584: 		return $restored{$qualifierrest};
                   11585: 	    }
1.48      www      11586: # ----------------------------------------------------------------- user.access
                   11587:         } elsif ($space eq 'access') {
1.218     albertel 11588: 	    # FIXME - not supporting calls for a specific user
1.48      www      11589:             return &allowed($qualifier,$rest);
                   11590: # ------------------------------------------ user.preferences, user.environment
                   11591:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11592: 	    if (($uname eq $env{'user.name'}) &&
                   11593: 		($udom eq $env{'user.domain'})) {
                   11594: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11595: 	    } else {
1.359     albertel 11596: 		my %returnhash;
                   11597: 		if (!$publicuser) {
                   11598: 		    %returnhash=&userenvironment($udom,$uname,
                   11599: 						 $qualifierrest);
                   11600: 		}
1.218     albertel 11601: 		return $returnhash{$qualifierrest};
                   11602: 	    }
1.48      www      11603: # ----------------------------------------------------------------- user.course
                   11604:         } elsif ($space eq 'course') {
1.218     albertel 11605: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11606:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11607: # ------------------------------------------------------------------- user.role
                   11608:         } elsif ($space eq 'role') {
1.218     albertel 11609: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11610:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11611:             if ($qualifier eq 'value') {
                   11612: 		return $role;
                   11613:             } elsif ($qualifier eq 'extent') {
                   11614:                 return $where;
                   11615:             }
                   11616: # ----------------------------------------------------------------- user.domain
                   11617:         } elsif ($space eq 'domain') {
1.218     albertel 11618:             return $udom;
1.48      www      11619: # ------------------------------------------------------------------- user.name
                   11620:         } elsif ($space eq 'name') {
1.218     albertel 11621:             return $uname;
1.48      www      11622: # ---------------------------------------------------- Any other user namespace
1.29      www      11623:         } else {
1.359     albertel 11624: 	    my %reply;
                   11625: 	    if (!$publicuser) {
                   11626: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11627: 	    }
                   11628: 	    return $reply{$qualifierrest};
1.48      www      11629:         }
1.236     www      11630:     } elsif ($realm eq 'query') {
                   11631: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11632:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11633: 						[$spacequalifierrest]);
1.620     albertel 11634: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11635:    } elsif ($realm eq 'request') {
1.48      www      11636: # ------------------------------------------------------------- request.browser
                   11637:         if ($space eq 'browser') {
1.1145    bisitz   11638:             return $env{'browser.'.$qualifier};
1.57      www      11639: # ------------------------------------------------------------ request.filename
                   11640:         } else {
1.620     albertel 11641:             return $env{'request.'.$spacequalifierrest};
1.29      www      11642:         }
1.28      www      11643:     } elsif ($realm eq 'course') {
1.48      www      11644: # ---------------------------------------------------------- course.description
1.620     albertel 11645:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11646:     } elsif ($realm eq 'resource') {
1.165     www      11647: 
1.620     albertel 11648: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11649: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11650: 	}
1.693     albertel 11651: 
1.1172.2.30  raeburn  11652:         if ($qualifier eq '') {
                   11653: 	    if ($space eq 'title') {
                   11654: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11655: 	        return &gettitle($symbparm);
                   11656: 	    }
1.693     albertel 11657: 	
1.1172.2.30  raeburn  11658: 	    if ($space eq 'map') {
                   11659: 	        my ($map) = &decode_symb($symbparm);
                   11660: 	        return &symbread($map);
                   11661: 	    }
                   11662:             if ($space eq 'maptitle') {
                   11663:                 my ($map) = &decode_symb($symbparm);
                   11664:                 return &gettitle($map);
                   11665:             }
                   11666: 	    if ($space eq 'filename') {
                   11667: 	        if ($symbparm) {
                   11668: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11669: 	        }
                   11670: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11671: 	    }
1.1172.2.30  raeburn  11672: 
                   11673:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11674:                 if ($space eq 'visibleparts') {
                   11675:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11676:                     my $item;
                   11677:                     if (ref($navmap)) {
                   11678:                         my $res = $navmap->getBySymb($symbparm);
                   11679:                         my $parts = $res->parts();
                   11680:                         if (ref($parts) eq 'ARRAY') {
                   11681:                             $item = join(',',@{$parts});
                   11682:                         }
                   11683:                         undef($navmap);
                   11684:                     }
                   11685:                     return $item;
                   11686:                 }
                   11687:             }
                   11688:         }
1.693     albertel 11689: 
                   11690: 	my ($section, $group, @groups);
1.593     albertel 11691: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11692:         if (($courseid eq '') && ($cid)) {
                   11693:             $courseid = $cid;
                   11694:         }
                   11695: 	if (($symbparm && $courseid) && 
                   11696: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11697: 
1.218     albertel 11698: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11699: 
1.60      www      11700: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11701: 	    my $symbp=$symbparm;
1.735     albertel 11702: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11703: 
                   11704: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11705: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11706: 
1.620     albertel 11707: 	    if (($env{'user.name'} eq $uname) &&
                   11708: 		($env{'user.domain'} eq $udom)) {
                   11709: 		$section=$env{'request.course.sec'};
1.733     raeburn  11710:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11711:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11712: 	    } else {
1.539     albertel 11713: 		if (! defined($usection)) {
1.551     albertel 11714: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11715: 		} else {
                   11716: 		    $section = $usection;
                   11717: 		}
1.733     raeburn  11718:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11719: 	    }
                   11720: 
                   11721: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11722: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11723: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11724: 
1.593     albertel 11725: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11726: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11727: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11728: 
1.60      www      11729: # ----------------------------------------------------------- first, check user
1.624     albertel 11730: 
                   11731: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11732: 				       ([$courselevelr,'resource'],
                   11733: 					[$courselevelm,'map'     ],
                   11734: 					[$courselevel, 'course'  ]));
1.931     albertel 11735: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11736: 
1.594     albertel 11737: # ------------------------------------------------ second, check some of course
1.684     raeburn  11738:             my $coursereply;
1.691     raeburn  11739:             if (@groups > 0) {
                   11740:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11741:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11742:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11743:             }
1.96      www      11744: 
1.684     raeburn  11745: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11746: 				  $env{'course.'.$courseid.'.domain'},
                   11747: 				  'course',
                   11748: 				  ([$seclevelr,   'resource'],
                   11749: 				   [$seclevelm,   'map'     ],
                   11750: 				   [$seclevel,    'course'  ],
                   11751: 				   [$courselevelr,'resource']));
                   11752: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11753: 
1.60      www      11754: # ------------------------------------------------------ third, check map parms
1.218     albertel 11755: 	    my %parmhash=();
                   11756: 	    my $thisparm='';
                   11757: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11758: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11759: 		    &GDBM_READER(),0640)) {
1.218     albertel 11760: 		$thisparm=$parmhash{$symbparm};
                   11761: 		untie(%parmhash);
                   11762: 	    }
1.927     albertel 11763: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11764: 	}
1.594     albertel 11765: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11766: 
1.218     albertel 11767: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11768: 	my $filename;
                   11769: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11770: 	if ($symbparm) {
1.409     www      11771: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11772: 	} else {
1.620     albertel 11773: 	    $filename=$env{'request.filename'};
1.282     albertel 11774: 	}
                   11775: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11776: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11777: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11778: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11779: 
1.927     albertel 11780: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11781: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11782: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11783: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11784: 				     $env{'course.'.$courseid.'.domain'},
                   11785: 				     'course',
1.927     albertel 11786: 				     ([$courselevelm,'map'   ],
                   11787: 				      [$courselevel, 'course']));
                   11788: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11789: 	}
1.145     www      11790: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11791: 	unless ($space eq '0') {
1.336     albertel 11792: 	    my @parts=split(/_/,$space);
                   11793: 	    my $id=pop(@parts);
                   11794: 	    my $part=join('_',@parts);
                   11795: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11796: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11797: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11798: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11799: 	}
1.395     albertel 11800: 	if ($recurse) { return undef; }
                   11801: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11802: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11803: # ---------------------------------------------------- Any other user namespace
                   11804:     } elsif ($realm eq 'environment') {
                   11805: # ----------------------------------------------------------------- environment
1.620     albertel 11806: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11807: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11808: 	} else {
1.770     albertel 11809: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11810: 		return '';
                   11811: 	    }
1.219     albertel 11812: 	    my %returnhash=&userenvironment($udom,$uname,
                   11813: 					    $spacequalifierrest);
                   11814: 	    return $returnhash{$spacequalifierrest};
                   11815: 	}
1.28      www      11816:     } elsif ($realm eq 'system') {
1.48      www      11817: # ----------------------------------------------------------------- system.time
                   11818: 	if ($space eq 'time') {
                   11819: 	    return time;
                   11820:         }
1.696     albertel 11821:     } elsif ($realm eq 'server') {
                   11822: # ----------------------------------------------------------------- system.time
                   11823: 	if ($space eq 'name') {
                   11824: 	    return $ENV{'SERVER_NAME'};
                   11825:         }
1.28      www      11826:     }
1.48      www      11827:     return '';
1.61      www      11828: }
                   11829: 
1.927     albertel 11830: sub get_reply {
                   11831:     my ($reply_value) = @_;
1.940     raeburn  11832:     if (ref($reply_value) eq 'ARRAY') {
                   11833:         if (wantarray) {
                   11834: 	    return @$reply_value;
                   11835:         }
                   11836:         return $reply_value->[0];
                   11837:     } else {
                   11838:         return $reply_value;
1.927     albertel 11839:     }
                   11840: }
                   11841: 
1.691     raeburn  11842: sub check_group_parms {
                   11843:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11844:     my @groupitems = ();
                   11845:     my $resultitem;
1.927     albertel 11846:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11847:     foreach my $group (@{$groups}) {
                   11848:         foreach my $level (@levels) {
1.927     albertel 11849:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11850:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11851:         }
                   11852:     }
                   11853:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11854:                             $env{'course.'.$courseid.'.domain'},
                   11855:                                      'course',@groupitems);
                   11856:     return $coursereply;
                   11857: }
                   11858: 
                   11859: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11860:     my ($courseid,@groups) = @_;
                   11861:     @groups = sort(@groups);
1.691     raeburn  11862:     return @groups;
                   11863: }
                   11864: 
1.395     albertel 11865: sub packages_tab_default {
                   11866:     my ($uri,$varname)=@_;
                   11867:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11868: 
                   11869:     my (@extension,@specifics,$do_default);
                   11870:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11871: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11872: 	if ($pack_type eq 'default') {
                   11873: 	    $do_default=1;
                   11874: 	} elsif ($pack_type eq 'extension') {
                   11875: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11876: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11877: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11878: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11879: 	}
                   11880:     }
                   11881:     # first look for a package that matches the requested part id
                   11882:     foreach my $package (@specifics) {
                   11883: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11884: 	next if ($pack_part ne $part);
                   11885: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11886: 	    return $packagetab{"$pack_type&$name&default"};
                   11887: 	}
                   11888:     }
                   11889:     # look for any possible matching non extension_ package
                   11890:     foreach my $package (@specifics) {
                   11891: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11892: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11893: 	    return $packagetab{"$pack_type&$name&default"};
                   11894: 	}
1.585     albertel 11895: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11896: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11897: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11898: 	}
                   11899:     }
1.738     albertel 11900:     # look for any posible extension_ match
                   11901:     foreach my $package (@extension) {
                   11902: 	my ($package,$pack_type)=@{$package};
                   11903: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11904: 	    return $packagetab{"$pack_type&$name&default"};
                   11905: 	}
                   11906: 	if (defined($packagetab{$package."&$name&default"})) {
                   11907: 	    return $packagetab{$package."&$name&default"};
                   11908: 	}
                   11909:     }
                   11910:     # look for a global default setting
                   11911:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11912: 	return $packagetab{"default&$name&default"};
                   11913:     }
1.395     albertel 11914:     return undef;
                   11915: }
                   11916: 
1.334     albertel 11917: sub add_prefix_and_part {
                   11918:     my ($prefix,$part)=@_;
                   11919:     my $keyroot;
                   11920:     if (defined($prefix) && $prefix !~ /^__/) {
                   11921: 	# prefix that has a part already
                   11922: 	$keyroot=$prefix;
                   11923:     } elsif (defined($prefix)) {
                   11924: 	# prefix that is missing a part
                   11925: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11926:     } else {
                   11927: 	# no prefix at all
                   11928: 	if (defined($part)) { $keyroot='_'.$part; }
                   11929:     }
                   11930:     return $keyroot;
                   11931: }
                   11932: 
1.71      www      11933: # ---------------------------------------------------------------- Get metadata
                   11934: 
1.599     albertel 11935: my %metaentry;
1.1070    www      11936: my %importedpartids;
1.1172.2.99  raeburn  11937: my %importedrespids;
1.71      www      11938: sub metadata {
1.176     www      11939:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11940:     $uri=&declutter($uri);
1.288     albertel 11941:     # if it is a non metadata possible uri return quickly
1.529     albertel 11942:     if (($uri eq '') || 
                   11943: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11944: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11945:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11946: 	return undef;
                   11947:     }
1.1172.2.49  raeburn  11948:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11949: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11950: 	return undef;
1.288     albertel 11951:     }
1.73      www      11952:     my $filename=$uri;
                   11953:     $uri=~s/\.meta$//;
1.172     www      11954: #
                   11955: # Is the metadata already cached?
1.177     www      11956: # Look at timestamp of caching
1.172     www      11957: # Everything is cached by the main uri, libraries are never directly cached
                   11958: #
1.428     albertel 11959:     if (!defined($liburi)) {
1.599     albertel 11960: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11961: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11962:     }
                   11963:     {
1.1069    www      11964: # Imported parts would go here
1.1172.2.99  raeburn  11965:         my @origfiletagids=();
1.1069    www      11966:         my $importedparts=0;
1.1172.2.99  raeburn  11967: 
                   11968: # Imported responseids would go here
                   11969:         my $importedresponses=0;
1.172     www      11970: #
                   11971: # Is this a recursive call for a library?
                   11972: #
1.599     albertel 11973: #	if (! exists($metacache{$uri})) {
                   11974: #	    $metacache{$uri}={};
                   11975: #	}
1.924     albertel 11976: 	my $cachetime = 60*60;
1.171     www      11977:         if ($liburi) {
                   11978: 	    $liburi=&declutter($liburi);
                   11979:             $filename=$liburi;
1.401     bowersj2 11980:         } else {
1.599     albertel 11981: 	    &devalidate_cache_new('meta',$uri);
                   11982: 	    undef(%metaentry);
1.401     bowersj2 11983: 	}
1.140     www      11984:         my %metathesekeys=();
1.73      www      11985:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11986: 	my $metastring;
1.1140    www      11987: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11988: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11989: 	    $metastring = 
1.929     albertel 11990: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11991: 					  ('grade_target' => 'meta'));
                   11992: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11993: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11994:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11995: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11996: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11997: 	    $metastring=&getfile($file);
1.489     albertel 11998: 	}
1.208     albertel 11999:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12000:         my $token;
1.140     www      12001:         undef %metathesekeys;
1.71      www      12002:         while ($token=$parser->get_token) {
1.339     albertel 12003: 	    if ($token->[0] eq 'S') {
                   12004: 		if (defined($token->[2]->{'package'})) {
1.172     www      12005: #
                   12006: # This is a package - get package info
                   12007: #
1.339     albertel 12008: 		    my $package=$token->[2]->{'package'};
                   12009: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12010: 		    if (defined($token->[2]->{'id'})) { 
                   12011: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12012: 		    }
1.599     albertel 12013: 		    if ($metaentry{':packages'}) {
                   12014: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12015: 		    } else {
1.599     albertel 12016: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12017: 		    }
1.736     albertel 12018: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12019: 			my $part=$keyroot;
                   12020: 			$part=~s/^\_//;
1.736     albertel 12021: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12022: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12023: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12024: 			    # ignore package.tab specified default values
                   12025:                             # here &package_tab_default() will fetch those
                   12026: 			    if ($subp eq 'default') { next; }
1.736     albertel 12027: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12028: 			    my $unikey;
                   12029: 			    if ($pack =~ /_0$/) {
                   12030: 				$unikey='parameter_0_'.$name;
                   12031: 				$part=0;
                   12032: 			    } else {
                   12033: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12034: 			    }
1.339     albertel 12035: 			    if ($subp eq 'display') {
                   12036: 				$value.=' [Part: '.$part.']';
                   12037: 			    }
1.599     albertel 12038: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12039: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12040: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12041: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12042: 			    }
1.599     albertel 12043: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12044: 				$metaentry{':'.$unikey}=
                   12045: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12046: 			    }
1.339     albertel 12047: 			}
                   12048: 		    }
                   12049: 		} else {
1.172     www      12050: #
                   12051: # This is not a package - some other kind of start tag
1.339     albertel 12052: #
                   12053: 		    my $entry=$token->[1];
1.1068    www      12054: 		    my $unikey='';
1.175     www      12055: 
1.339     albertel 12056: 		    if ($entry eq 'import') {
1.175     www      12057: #
                   12058: # Importing a library here
1.339     albertel 12059: #
1.1067    www      12060:                         my $location=$parser->get_text('/import');
                   12061:                         my $dir=$filename;
                   12062:                         $dir=~s|[^/]*$||;
                   12063:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12064: 
                   12065:                         my $importid=$token->[2]->{'id'};
1.1068    www      12066:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12067: #
                   12068: # Check metadata for imported file to
                   12069: # see if it contained response items
                   12070: #
                   12071:                         my %currmetaentry = %metaentry;
                   12072:                         my $libresponseorder = &metadata($location,'responseorder');
                   12073:                         my $origfile;
                   12074:                         if ($libresponseorder ne '') {
                   12075:                             if ($#origfiletagids<0) {
                   12076:                                 undef(%importedrespids);
                   12077:                                 undef(%importedpartids);
                   12078:                             }
                   12079:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12080:                             if (@{$importedrespids{$importid}} > 0) {
                   12081:                                 $importedresponses = 1;
                   12082: # We need to get the original file and the imported file to get the response order correct
                   12083: # Load and inspect original file
                   12084:                                 if ($#origfiletagids<0) {
                   12085:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12086:                                     $origfile=&getfile($origfilelocation);
                   12087:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12088:                                 }
                   12089:                             }
                   12090:                         }
                   12091: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12092: # hash populated for imported library file
                   12093:                         %metaentry = %currmetaentry;
                   12094:                         undef(%currmetaentry);
1.1068    www      12095:                         if ($importmode eq 'problem') {
1.1069    www      12096: # Import as problem/response
1.1068    www      12097:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12098:                         } elsif ($importmode eq 'part') {
                   12099: # Import as part(s)
1.1069    www      12100:                            $importedparts=1;
                   12101: # We need to get the original file and the imported file to get the part order correct
                   12102: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12103: # Load and inspect original file if we didn't do that already
                   12104:                            if ($#origfiletagids<0) {
                   12105:                                undef(%importedrespids);
                   12106:                                undef(%importedpartids);
                   12107:                                if ($origfile eq '') {
                   12108:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12109:                                    $origfile=&getfile($origfilelocation);
                   12110:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12111:                                }
1.1070    www      12112:                            }
                   12113: 
1.1069    www      12114: # Load and inspect imported file
                   12115:                            my $impfile=&getfile($location);
                   12116:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12117:                            if ($#impfilepartids>=0) {
                   12118: # This problem had parts
1.1070    www      12119:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12120:                            } else {
                   12121: # Importing by turning a single problem into a problem part
                   12122: # It gets the import-tags ID as part-ID
                   12123:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12124:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12125:                            }
1.1068    www      12126:                         } else {
                   12127: # Normal import
                   12128:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12129:                            if (defined($token->[2]->{'id'})) {
                   12130:                               $unikey.='_'.$token->[2]->{'id'};
                   12131:                            }
1.1067    www      12132:                         }
                   12133: 
1.339     albertel 12134: 			if ($depthcount<20) {
1.736     albertel 12135: 			    my $metadata = 
                   12136: 				&metadata($uri,'keys', $location,$unikey,
                   12137: 					  $depthcount+1);
                   12138: 			    foreach my $meta (split(',',$metadata)) {
                   12139: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12140: 				$metathesekeys{$meta}=1;
1.339     albertel 12141: 			    }
1.1068    www      12142: 			
                   12143:                         }
1.1067    www      12144: 		    } else {
                   12145: #
                   12146: # Not importing, some other kind of non-package, non-library start tag
                   12147: # 
                   12148:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12149:                         if (defined($token->[2]->{'id'})) {
                   12150:                             $unikey.='_'.$token->[2]->{'id'};
                   12151:                         }
1.339     albertel 12152: 			if (defined($token->[2]->{'name'})) { 
                   12153: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12154: 			}
                   12155: 			$metathesekeys{$unikey}=1;
1.736     albertel 12156: 			foreach my $param (@{$token->[3]}) {
                   12157: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12158: 				$token->[2]->{$param};
1.339     albertel 12159: 			}
                   12160: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12161: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12162: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12163: 		 # only ws inside the tag, and not in default, so use default
                   12164: 		 # as value
1.599     albertel 12165: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12166: 			} elsif ( $internaltext =~ /\S/ ) {
                   12167: 		  # something interesting inside the tag
                   12168: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12169: 			} else {
1.908     albertel 12170: 		  # no interesting values, don't set a default
1.339     albertel 12171: 			}
1.172     www      12172: # end of not-a-package not-a-library import
1.339     albertel 12173: 		    }
1.172     www      12174: # end of not-a-package start tag
1.339     albertel 12175: 		}
1.172     www      12176: # the next is the end of "start tag"
1.339     albertel 12177: 	    }
                   12178: 	}
1.483     albertel 12179: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12180: 	$extension = lc($extension);
                   12181: 	if ($extension eq 'htm') { $extension='html'; }
                   12182: 
1.737     albertel 12183: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12184: 	    #no specific packages #how's our extension
                   12185: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12186: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12187: 					 \%metathesekeys);
                   12188: 	}
1.883     albertel 12189: 
                   12190: 	if (!exists($metaentry{':packages'})
                   12191: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12192: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12193: 		#no specific packages well let's get default then
                   12194: 		if ($key!~/^default&/) { next; }
1.488     albertel 12195: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12196: 					     \%metathesekeys);
                   12197: 	    }
                   12198: 	}
1.338     www      12199: # are there custom rights to evaluate
1.599     albertel 12200: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12201: 
1.338     www      12202:     #
                   12203:     # Importing a rights file here
1.339     albertel 12204:     #
                   12205: 	    unless ($depthcount) {
1.599     albertel 12206: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12207: 		my $dir=$filename;
                   12208: 		$dir=~s|[^/]*$||;
                   12209: 		$location=&filelocation($dir,$location);
1.736     albertel 12210: 		my $rights_metadata =
                   12211: 		    &metadata($uri,'keys',$location,'_rights',
                   12212: 			      $depthcount+1);
                   12213: 		foreach my $rights (split(',',$rights_metadata)) {
                   12214: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12215: 		    $metathesekeys{$rights}=1;
1.339     albertel 12216: 		}
                   12217: 	    }
                   12218: 	}
1.737     albertel 12219: 	# uniqifiy package listing
                   12220: 	my %seen;
                   12221: 	my @uniq_packages =
                   12222: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12223: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12224: 
1.1172.2.99  raeburn  12225:         if (($importedresponses) || ($importedparts)) {
                   12226:             if ($importedparts) {
1.1070    www      12227: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12228:                 $metaentry{':partorder'}='';
                   12229:                 $metathesekeys{'partorder'}=1;
                   12230:             }
                   12231:             if ($importedresponses) {
                   12232: # We had imported responses and need to rebuild responseorder
                   12233:                 $metaentry{':responseorder'}='';
                   12234:                 $metathesekeys{'responseorder'}=1;
                   12235:             }
                   12236:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12237:                 my $origid = $origfiletagids[$index+1];
                   12238:                 if ($origfiletagids[$index] eq 'part') {
                   12239: # Original part, part of the problem
                   12240:                     if ($importedparts) {
                   12241:                         $metaentry{':partorder'}.=','.$origid;
                   12242:                     }
                   12243:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12244:                     if ($importedparts) {
                   12245: # We have imported parts at this position
                   12246:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12247:                     }
                   12248:                     if ($importedresponses) {
                   12249: # We have imported responses at this position
                   12250:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12251:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12252:                         }
                   12253:                     }
                   12254:                 } else {
                   12255: # Original response item, part of the problem
                   12256:                     if ($importedresponses) {
                   12257:                         $metaentry{':responseorder'}.=','.$origid;
                   12258:                     }
                   12259:                 }
                   12260:             }
                   12261:             if ($importedparts) {
                   12262:                 $metaentry{':partorder'}=~s/^\,//;
                   12263:             }
                   12264:             if ($importedresponses) {
                   12265:                 $metaentry{':responseorder'}=~s/^\,//;
                   12266:             }
1.1070    www      12267:         }
                   12268: 
1.737     albertel 12269: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12270: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12271: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12272: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12273: # this is the end of "was not already recently cached
1.71      www      12274:     }
1.599     albertel 12275:     return $metaentry{':'.$what};
1.261     albertel 12276: }
                   12277: 
1.488     albertel 12278: sub metadata_create_package_def {
1.483     albertel 12279:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12280:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12281:     if ($subp eq 'default') { next; }
                   12282:     
1.599     albertel 12283:     if (defined($metaentry{':packages'})) {
                   12284: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12285:     } else {
1.599     albertel 12286: 	$metaentry{':packages'}=$package;
1.483     albertel 12287:     }
                   12288:     my $value=$packagetab{$key};
                   12289:     my $unikey;
                   12290:     $unikey='parameter_0_'.$name;
1.599     albertel 12291:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12292:     $$metathesekeys{$unikey}=1;
1.599     albertel 12293:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12294: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12295:     }
1.599     albertel 12296:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12297: 	$metaentry{':'.$unikey}=
                   12298: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12299:     }
                   12300: }
                   12301: 
1.261     albertel 12302: sub metadata_generate_part0 {
                   12303:     my ($metadata,$metacache,$uri) = @_;
                   12304:     my %allnames;
1.737     albertel 12305:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12306: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12307: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12308: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12309: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12310: 	    $allnames{$name}=$part;
                   12311: 	  }
                   12312: 	}
                   12313:     }
                   12314:     foreach my $name (keys(%allnames)) {
                   12315:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12316:       my $key=":parameter_0_$name";
1.261     albertel 12317:       $$metacache{"$key.part"}='0';
                   12318:       $$metacache{"$key.name"}=$name;
1.428     albertel 12319:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12320: 					   $allnames{$name}.'_'.$name.
                   12321: 					   '.type'};
1.428     albertel 12322:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12323: 			     '.display'};
1.644     www      12324:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12325:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12326:       $$metacache{"$key.display"}=$olddis;
                   12327:     }
1.71      www      12328: }
                   12329: 
1.764     albertel 12330: # ------------------------------------------------------ Devalidate title cache
                   12331: 
                   12332: sub devalidate_title_cache {
                   12333:     my ($url)=@_;
                   12334:     if (!$env{'request.course.id'}) { return; }
                   12335:     my $symb=&symbread($url);
                   12336:     if (!$symb) { return; }
                   12337:     my $key=$env{'request.course.id'}."\0".$symb;
                   12338:     &devalidate_cache_new('title',$key);
                   12339: }
                   12340: 
1.1014    droeschl 12341: # ------------------------------------------------- Get the title of a course
                   12342: 
                   12343: sub current_course_title {
                   12344:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12345: }
1.301     www      12346: # ------------------------------------------------- Get the title of a resource
                   12347: 
                   12348: sub gettitle {
                   12349:     my $urlsymb=shift;
                   12350:     my $symb=&symbread($urlsymb);
1.534     albertel 12351:     if ($symb) {
1.620     albertel 12352: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12353: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12354: 	if (defined($cached)) { 
                   12355: 	    return $result;
                   12356: 	}
1.534     albertel 12357: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12358: 	my $title='';
1.907     albertel 12359: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12360: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12361: 	} else {
                   12362: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12363: 		    &GDBM_READER(),0640)) {
                   12364: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12365: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12366: 		untie(%bighash);
                   12367: 	    }
1.534     albertel 12368: 	}
                   12369: 	$title=~s/\&colon\;/\:/gs;
                   12370: 	if ($title) {
1.1159    www      12371: # Remember both $symb and $title for dynamic metadata
                   12372:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12373:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12374: # Cache this title and then return it
1.599     albertel 12375: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12376: 	}
                   12377: 	$urlsymb=$url;
                   12378:     }
                   12379:     my $title=&metadata($urlsymb,'title');
                   12380:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12381:     return $title;
1.301     www      12382: }
1.613     albertel 12383: 
1.614     albertel 12384: sub get_slot {
                   12385:     my ($which,$cnum,$cdom)=@_;
                   12386:     if (!$cnum || !$cdom) {
1.790     albertel 12387: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12388: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12389: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12390:     }
1.703     albertel 12391:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12392:     my %slotinfo;
                   12393:     if (exists($remembered{$key})) {
                   12394: 	$slotinfo{$which} = $remembered{$key};
                   12395:     } else {
                   12396: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12397: 	&Apache::lonhomework::showhash(%slotinfo);
                   12398: 	my ($tmp)=keys(%slotinfo);
                   12399: 	if ($tmp=~/^error:/) { return (); }
                   12400: 	$remembered{$key} = $slotinfo{$which};
                   12401:     }
1.616     albertel 12402:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12403: 	return %{$slotinfo{$which}};
                   12404:     }
                   12405:     return $slotinfo{$which};
1.614     albertel 12406: }
1.1150    raeburn  12407: 
                   12408: sub get_reservable_slots {
                   12409:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12410:     my $now = time;
                   12411:     my $reservable_info;
                   12412:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12413:     if (exists($remembered{$key})) {
                   12414:         $reservable_info = $remembered{$key};
                   12415:     } else {
                   12416:         my %resv;
                   12417:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12418:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12419:         $reservable_info = \%resv;
                   12420:         $remembered{$key} = $reservable_info;
                   12421:     }
                   12422:     return $reservable_info;
                   12423: }
                   12424: 
                   12425: sub get_course_slots {
                   12426:     my ($cnum,$cdom) = @_;
                   12427:     my $hashid=$cnum.':'.$cdom;
                   12428:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12429:     if (defined($cached)) {
                   12430:         if (ref($result) eq 'HASH') {
                   12431:             return %{$result};
                   12432:         }
                   12433:     } else {
                   12434:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12435:         my ($tmp) = keys(%slots);
                   12436:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12437:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12438:             return %slots;
                   12439:         }
                   12440:     }
                   12441:     return;
                   12442: }
                   12443: 
                   12444: sub devalidate_slots_cache {
                   12445:     my ($cnum,$cdom)=@_;
                   12446:     my $hashid=$cnum.':'.$cdom;
                   12447:     &devalidate_cache_new('allslots',$hashid);
                   12448: }
                   12449: 
1.1172.2.8  raeburn  12450: sub get_coursechange {
                   12451:     my ($cdom,$cnum) = @_;
                   12452:     if ($cdom eq '' || $cnum eq '') {
                   12453:         return unless ($env{'request.course.id'});
                   12454:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12455:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12456:     }
                   12457:     my $hashid=$cdom.'_'.$cnum;
                   12458:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12459:     if ((defined($cached)) && ($change ne '')) {
                   12460:         return $change;
                   12461:     } else {
                   12462:         my %crshash;
                   12463:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12464:         if ($crshash{'internal.contentchange'} eq '') {
                   12465:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12466:             if ($change eq '') {
                   12467:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12468:                 $change = $crshash{'internal.created'};
                   12469:             }
                   12470:         } else {
                   12471:             $change = $crshash{'internal.contentchange'};
                   12472:         }
                   12473:         my $cachetime = 600;
                   12474:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12475:     }
                   12476:     return $change;
                   12477: }
                   12478: 
                   12479: sub devalidate_coursechange_cache {
                   12480:     my ($cnum,$cdom)=@_;
                   12481:     my $hashid=$cnum.':'.$cdom;
                   12482:     &devalidate_cache_new('crschange',$hashid);
                   12483: }
                   12484: 
1.31      www      12485: # ------------------------------------------------- Update symbolic store links
                   12486: 
                   12487: sub symblist {
                   12488:     my ($mapname,%newhash)=@_;
1.438     www      12489:     $mapname=&deversion(&declutter($mapname));
1.31      www      12490:     my %hash;
1.620     albertel 12491:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12492:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12493:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12494: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12495: 		next if ($url eq 'last_known'
                   12496: 			 && $env{'form.no_update_last_known'});
                   12497: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12498: 						    $newhash{$url}->[1],
                   12499: 						    $newhash{$url}->[0]);
1.191     harris41 12500:             }
1.31      www      12501:             if (untie(%hash)) {
                   12502: 		return 'ok';
                   12503:             }
                   12504:         }
                   12505:     }
                   12506:     return 'error';
1.212     www      12507: }
                   12508: 
                   12509: # --------------------------------------------------------------- Verify a symb
                   12510: 
                   12511: sub symbverify {
1.1172.2.11  raeburn  12512:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12513:     my $thisfn=$thisurl;
1.439     www      12514:     $thisfn=&declutter($thisfn);
1.215     www      12515: # direct jump to resource in page or to a sequence - will construct own symbs
                   12516:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12517: # check URL part
1.409     www      12518:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12519: 
1.431     www      12520:     unless ($url eq $thisfn) { return 0; }
1.213     www      12521: 
1.216     www      12522:     $symb=&symbclean($symb);
1.510     www      12523:     $thisurl=&deversion($thisurl);
1.439     www      12524:     $thisfn=&deversion($thisfn);
1.213     www      12525: 
                   12526:     my %bighash;
                   12527:     my $okay=0;
1.431     www      12528: 
1.620     albertel 12529:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12530:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12531:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12532:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12533:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12534:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12535:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12536:             }
                   12537:         }
                   12538:         my $ids;
1.1172.2.122  raeburn  12539:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12540:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12541:         } else {
                   12542:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12543:         }
1.1102    raeburn  12544:         unless ($ids) {
1.1172.2.13  raeburn  12545:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12546:             $ids=$bighash{$idkey};
1.216     www      12547:         }
                   12548:         if ($ids) {
                   12549: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12550:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12551:                 $symb =~ s/\?.+$//;
                   12552:             }
1.800     albertel 12553: 	    foreach my $id (split(/\,/,$ids)) {
                   12554: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12555:                if (
                   12556:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12557:    eq $symb) {
1.1172.2.11  raeburn  12558:                    if (ref($encstate)) {
                   12559:                        $$encstate = $bighash{'encrypted_'.$id};
                   12560:                    }
1.1172.2.13  raeburn  12561:                    if (($env{'request.role.adv'}) ||
                   12562:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12563:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12564:                        $okay=1;
                   12565:                        last;
                   12566:                    }
                   12567:                }
                   12568:            }
1.216     www      12569:         }
1.213     www      12570: 	untie(%bighash);
                   12571:     }
                   12572:     return $okay;
1.31      www      12573: }
                   12574: 
1.210     www      12575: # --------------------------------------------------------------- Clean-up symb
                   12576: 
                   12577: sub symbclean {
                   12578:     my $symb=shift;
1.568     albertel 12579:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12580: # remove version from map
                   12581:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12582: 
1.210     www      12583: # remove version from URL
                   12584:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12585: 
1.507     www      12586: # remove wrapper
                   12587: 
1.510     www      12588:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12589:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12590:     return $symb;
1.409     www      12591: }
                   12592: 
                   12593: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12594: 
                   12595: sub encode_symb {
                   12596:     my ($map,$resid,$url)=@_;
                   12597:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12598: }
1.409     www      12599: 
                   12600: sub decode_symb {
1.568     albertel 12601:     my $symb=shift;
                   12602:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12603:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12604:     return (&fixversion($map),$resid,&fixversion($url));
                   12605: }
                   12606: 
                   12607: sub fixversion {
                   12608:     my $fn=shift;
1.609     banghart 12609:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12610:     my %bighash;
                   12611:     my $uri=&clutter($fn);
1.620     albertel 12612:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12613: # is this cached?
1.599     albertel 12614:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12615:     if (defined($cached)) { return $result; }
                   12616: # unfortunately not cached, or expired
1.620     albertel 12617:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12618: 	    &GDBM_READER(),0640)) {
                   12619:  	if ($bighash{'version_'.$uri}) {
                   12620:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12621:  	    unless (($version eq 'mostrecent') || 
                   12622: 		    ($version==&getversion($uri))) {
1.440     www      12623:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12624:  	    }
                   12625:  	}
                   12626:  	untie %bighash;
1.413     www      12627:     }
1.599     albertel 12628:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12629: }
                   12630: 
                   12631: sub deversion {
                   12632:     my $url=shift;
                   12633:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12634:     return $url;
1.210     www      12635: }
                   12636: 
1.31      www      12637: # ------------------------------------------------------ Return symb list entry
                   12638: 
                   12639: sub symbread {
1.1172.2.126  raeburn  12640:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12641:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12642:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12643:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12644:         unless (ref($possibles) eq 'HASH') {
                   12645:             if ($ignorecachednull) {
                   12646:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12647:             } else {
                   12648:                 return $env{$cache_str};
                   12649:             }
1.1172.2.66  raeburn  12650:         }
                   12651:     }
1.242     www      12652: # no filename provided? try from environment
1.1172.2.54  raeburn  12653:     unless ($thisfn) {
1.620     albertel 12654:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12655:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12656:         }
                   12657:         $thisfn=$env{'request.filename'};
1.44      www      12658:     }
1.569     albertel 12659:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12660: # is that filename actually a symb? Verify, clean, and return
                   12661:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12662: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12663: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12664: 	}
1.242     www      12665:     }
1.44      www      12666:     $thisfn=declutter($thisfn);
1.31      www      12667:     my %hash;
1.37      www      12668:     my %bighash;
                   12669:     my $syval='';
1.620     albertel 12670:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12671:         my $targetfn = $thisfn;
1.609     banghart 12672:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12673:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12674:         }
1.687     albertel 12675: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12676: 	    $targetfn=$1;
                   12677: 	}
1.1172.2.128  raeburn  12678:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12679:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12680:                           &GDBM_READER(),0640)) {
                   12681: 	        $syval=$hash{$targetfn};
                   12682:                 untie(%hash);
                   12683:             }
1.1172.2.128  raeburn  12684:             if ($syval && $checkforblock) {
                   12685:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12686:                 if (@blockers) {
                   12687:                     $syval='';
                   12688:                 }
                   12689:             }
1.37      www      12690:         }
                   12691: # ---------------------------------------------------------- There was an entry
                   12692:         if ($syval) {
1.601     albertel 12693: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12694: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12695: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12696: 		    #return $env{$cache_str}='';
1.601     albertel 12697: 		#}    
                   12698: 		#$syval.=$1;
                   12699: 	    #}
1.37      www      12700:         } else {
                   12701: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12702:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12703:                             &GDBM_READER(),0640)) {
1.37      www      12704: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12705:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12706:               unless ($ids) { 
                   12707:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12708:               }
                   12709:               unless ($ids) {
                   12710: # alias?
                   12711: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12712:               }
1.37      www      12713:               if ($ids) {
                   12714: # ------------------------------------------------------------------- Has ID(s)
                   12715:                  my @possibilities=split(/\,/,$ids);
1.39      www      12716:                  if ($#possibilities==0) {
                   12717: # ----------------------------------------------- There is only one possibility
1.37      www      12718: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12719: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12720: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12721:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12722:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12723:                              $possibles->{$syval} = 1;
                   12724:                          }
1.1172.2.66  raeburn  12725:                      }
                   12726:                      if ($checkforblock) {
1.1172.2.126  raeburn  12727:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12728:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12729:                              if (@blockers) {
                   12730:                                  $syval = '';
                   12731:                                  untie(%bighash);
                   12732:                                  return $env{$cache_str}='';
                   12733:                              }
1.1172.2.66  raeburn  12734:                          }
                   12735:                      }
                   12736:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12737: # ------------------------------------------ There is more than one possibility
                   12738:                      my $realpossible=0;
1.800     albertel 12739:                      foreach my $id (@possibilities) {
                   12740: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12741:                          my $canaccess;
                   12742:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12743:                              $canaccess = 1;
                   12744:                          } else {
                   12745:                              $canaccess = &allowed('bre',$file);
                   12746:                          }
                   12747:                          if ($canaccess) {
                   12748:          		     my ($mapid,$resid)=split(/\./,$id);
                   12749:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12750:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12751:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12752:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12753:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12754:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12755:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12756:                                      if (@blockers > 0) {
                   12757:                                          $syval = '';
                   12758:                                      } else {
1.1172.2.66  raeburn  12759:                                          $syval = $poss_syval;
                   12760:                                          $realpossible++;
                   12761:                                      }
                   12762:                                  } else {
                   12763:                                      $syval = $poss_syval;
                   12764:                                      $realpossible++;
                   12765:                                  }
1.1172.2.126  raeburn  12766:                                  if ($syval) {
                   12767:                                      if (ref($possibles) eq 'HASH') {
                   12768:                                          $possibles->{$syval} = 1;
                   12769:                                      }
                   12770:                                  }
1.1172.2.66  raeburn  12771:                              }
1.39      www      12772: 			 }
1.191     harris41 12773:                      }
1.39      www      12774: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12775:                  } else {
                   12776:                      $syval='';
1.37      www      12777:                  }
                   12778: 	      }
1.1172.2.66  raeburn  12779:               untie(%bighash);
1.481     raeburn  12780:            }
1.31      www      12781:         }
1.62      www      12782:         if ($syval) {
1.1172.2.128  raeburn  12783: 	    return $env{$cache_str}=$syval;
1.62      www      12784:         }
1.31      www      12785:     }
1.949     raeburn  12786:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12787:     return $env{$cache_str}='';
1.31      www      12788: }
                   12789: 
                   12790: # ---------------------------------------------------------- Return random seed
                   12791: 
1.32      www      12792: sub numval {
                   12793:     my $txt=shift;
                   12794:     $txt=~tr/A-J/0-9/;
                   12795:     $txt=~tr/a-j/0-9/;
                   12796:     $txt=~tr/K-T/0-9/;
                   12797:     $txt=~tr/k-t/0-9/;
                   12798:     $txt=~tr/U-Z/0-5/;
                   12799:     $txt=~tr/u-z/0-5/;
                   12800:     $txt=~s/\D//g;
1.564     albertel 12801:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12802:     return int($txt);
1.368     albertel 12803: }
                   12804: 
1.484     albertel 12805: sub numval2 {
                   12806:     my $txt=shift;
                   12807:     $txt=~tr/A-J/0-9/;
                   12808:     $txt=~tr/a-j/0-9/;
                   12809:     $txt=~tr/K-T/0-9/;
                   12810:     $txt=~tr/k-t/0-9/;
                   12811:     $txt=~tr/U-Z/0-5/;
                   12812:     $txt=~tr/u-z/0-5/;
                   12813:     $txt=~s/\D//g;
                   12814:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12815:     my $total;
                   12816:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12817:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12818:     return int($total);
                   12819: }
                   12820: 
1.575     albertel 12821: sub numval3 {
                   12822:     use integer;
                   12823:     my $txt=shift;
                   12824:     $txt=~tr/A-J/0-9/;
                   12825:     $txt=~tr/a-j/0-9/;
                   12826:     $txt=~tr/K-T/0-9/;
                   12827:     $txt=~tr/k-t/0-9/;
                   12828:     $txt=~tr/U-Z/0-5/;
                   12829:     $txt=~tr/u-z/0-5/;
                   12830:     $txt=~s/\D//g;
                   12831:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12832:     my $total;
                   12833:     foreach my $val (@txts) { $total+=$val; }
                   12834:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12835:     return $total;
                   12836: }
                   12837: 
1.675     albertel 12838: sub digest {
                   12839:     my ($data)=@_;
                   12840:     my $digest=&Digest::MD5::md5($data);
                   12841:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12842:     my ($e,$f);
                   12843:     {
                   12844:         use integer;
                   12845:         $e=($a+$b);
                   12846:         $f=($c+$d);
                   12847:         if ($_64bit) {
                   12848:             $e=(($e<<32)>>32);
                   12849:             $f=(($f<<32)>>32);
                   12850:         }
                   12851:     }
                   12852:     if (wantarray) {
                   12853: 	return ($e,$f);
                   12854:     } else {
                   12855: 	my $g;
                   12856: 	{
                   12857: 	    use integer;
                   12858: 	    $g=($e+$f);
                   12859: 	    if ($_64bit) {
                   12860: 		$g=(($g<<32)>>32);
                   12861: 	    }
                   12862: 	}
                   12863: 	return $g;
                   12864:     }
                   12865: }
                   12866: 
1.368     albertel 12867: sub latest_rnd_algorithm_id {
1.675     albertel 12868:     return '64bit5';
1.366     albertel 12869: }
1.32      www      12870: 
1.503     albertel 12871: sub get_rand_alg {
                   12872:     my ($courseid)=@_;
1.790     albertel 12873:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12874:     if ($courseid) {
1.620     albertel 12875: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12876:     }
                   12877:     return &latest_rnd_algorithm_id();
                   12878: }
                   12879: 
1.562     albertel 12880: sub validCODE {
                   12881:     my ($CODE)=@_;
                   12882:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12883:     return 0;
                   12884: }
                   12885: 
1.491     albertel 12886: sub getCODE {
1.620     albertel 12887:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12888:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12889: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12890: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12891: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12892:     }
                   12893:     return undef;
                   12894: }
1.1133    foxr     12895: #
                   12896: #  Determines the random seed for a specific context:
                   12897: #
                   12898: # parameters:
                   12899: #   symb      - in course context the symb for the seed.
                   12900: #   course_id - The course id of the form domain_coursenum.
                   12901: #   domain    - Domain for the user.
                   12902: #   course    - Course for the user.
                   12903: #   cenv      - environment of the course.
                   12904: #
                   12905: # NOTE:
                   12906: #   All parameters are picked out of the environment if missing
                   12907: #   or not defined.
                   12908: #   If a symb cannot be determined the current time is used instead.
                   12909: #
                   12910: #  For a given well defined symb, courside, domain, username,
                   12911: #  and course environment, the seed is reproducible.
                   12912: #
1.31      www      12913: sub rndseed {
1.1133    foxr     12914:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12915:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12916:     if (!defined($symb)) {
1.366     albertel 12917: 	unless ($symb=$wsymb) { return time; }
                   12918:     }
1.1146    foxr     12919:     if (!defined $courseid) { 
                   12920: 	$courseid=$wcourseid; 
                   12921:     }
                   12922:     if (!defined $domain) { $domain=$wdomain; }
                   12923:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12924: 
                   12925:     my $which;
                   12926:     if (defined($cenv->{'rndseed'})) {
                   12927: 	$which = $cenv->{'rndseed'};
                   12928:     } else {
                   12929: 	$which =&get_rand_alg($courseid);
                   12930:     }
1.491     albertel 12931:     if (defined(&getCODE())) {
1.675     albertel 12932: 	if ($which eq '64bit5') {
                   12933: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12934: 	} elsif ($which eq '64bit4') {
1.575     albertel 12935: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12936: 	} else {
                   12937: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12938: 	}
1.675     albertel 12939:     } elsif ($which eq '64bit5') {
                   12940: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12941:     } elsif ($which eq '64bit4') {
                   12942: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12943:     } elsif ($which eq '64bit3') {
                   12944: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12945:     } elsif ($which eq '64bit2') {
                   12946: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12947:     } elsif ($which eq '64bit') {
                   12948: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12949:     }
                   12950:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12951: }
                   12952: 
                   12953: sub rndseed_32bit {
                   12954:     my ($symb,$courseid,$domain,$username)=@_;
                   12955:     {
                   12956: 	use integer;
                   12957: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12958: 	my $symbseed=numval($symb) << 22;
                   12959: 	my $namechck=unpack("%32C*",$username) << 17;
                   12960: 	my $nameseed=numval($username) << 12;
                   12961: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12962: 	my $courseseed=unpack("%32C*",$courseid);
                   12963: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12965: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12966: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12967: 	return $num;
                   12968:     }
                   12969: }
                   12970: 
                   12971: sub rndseed_64bit {
                   12972:     my ($symb,$courseid,$domain,$username)=@_;
                   12973:     {
                   12974: 	use integer;
                   12975: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12976: 	my $symbseed=numval($symb) << 10;
                   12977: 	my $namechck=unpack("%32S*",$username);
                   12978: 	
                   12979: 	my $nameseed=numval($username) << 21;
                   12980: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12981: 	my $courseseed=unpack("%32S*",$courseid);
                   12982: 	
                   12983: 	my $num1=$symbchck+$symbseed+$namechck;
                   12984: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12985: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12986: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12987: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12988: 	return "$num1,$num2";
1.155     albertel 12989:     }
1.366     albertel 12990: }
                   12991: 
1.443     albertel 12992: sub rndseed_64bit2 {
                   12993:     my ($symb,$courseid,$domain,$username)=@_;
                   12994:     {
                   12995: 	use integer;
                   12996: 	# strings need to be an even # of cahracters long, it it is odd the
                   12997:         # last characters gets thrown away
                   12998: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12999: 	my $symbseed=numval($symb) << 10;
                   13000: 	my $namechck=unpack("%32S*",$username.' ');
                   13001: 	
                   13002: 	my $nameseed=numval($username) << 21;
1.501     albertel 13003: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13004: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13005: 	
                   13006: 	my $num1=$symbchck+$symbseed+$namechck;
                   13007: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13008: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13009: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13010: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13011: 	return "$num1,$num2";
                   13012:     }
                   13013: }
                   13014: 
                   13015: sub rndseed_64bit3 {
                   13016:     my ($symb,$courseid,$domain,$username)=@_;
                   13017:     {
                   13018: 	use integer;
                   13019: 	# strings need to be an even # of cahracters long, it it is odd the
                   13020:         # last characters gets thrown away
                   13021: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13022: 	my $symbseed=numval2($symb) << 10;
                   13023: 	my $namechck=unpack("%32S*",$username.' ');
                   13024: 	
                   13025: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13026: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13027: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13028: 	
                   13029: 	my $num1=$symbchck+$symbseed+$namechck;
                   13030: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13031: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13032: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13033: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13034: 	
1.503     albertel 13035: 	return "$num1:$num2";
1.443     albertel 13036:     }
                   13037: }
                   13038: 
1.575     albertel 13039: sub rndseed_64bit4 {
                   13040:     my ($symb,$courseid,$domain,$username)=@_;
                   13041:     {
                   13042: 	use integer;
                   13043: 	# strings need to be an even # of cahracters long, it it is odd the
                   13044:         # last characters gets thrown away
                   13045: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13046: 	my $symbseed=numval3($symb) << 10;
                   13047: 	my $namechck=unpack("%32S*",$username.' ');
                   13048: 	
                   13049: 	my $nameseed=numval3($username) << 21;
                   13050: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13051: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13052: 	
                   13053: 	my $num1=$symbchck+$symbseed+$namechck;
                   13054: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13055: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13056: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13057: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13058: 	
1.575     albertel 13059: 	return "$num1:$num2";
                   13060:     }
                   13061: }
                   13062: 
1.675     albertel 13063: sub rndseed_64bit5 {
                   13064:     my ($symb,$courseid,$domain,$username)=@_;
                   13065:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13066:     return "$num1:$num2";
                   13067: }
                   13068: 
1.366     albertel 13069: sub rndseed_CODE_64bit {
                   13070:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13071:     {
1.366     albertel 13072: 	use integer;
1.443     albertel 13073: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13074: 	my $symbseed=numval2($symb);
1.491     albertel 13075: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13076: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13077: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13078: 	my $num1=$symbseed+$CODEchck;
                   13079: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13080: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13081: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13082: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13083: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13084: 	return "$num1:$num2";
1.366     albertel 13085:     }
                   13086: }
                   13087: 
1.575     albertel 13088: sub rndseed_CODE_64bit4 {
                   13089:     my ($symb,$courseid,$domain,$username)=@_;
                   13090:     {
                   13091: 	use integer;
                   13092: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13093: 	my $symbseed=numval3($symb);
                   13094: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13095: 	my $CODEseed=numval3(&getCODE());
                   13096: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   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.575     albertel 13101: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13102: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13103: 	return "$num1:$num2";
                   13104:     }
                   13105: }
                   13106: 
1.675     albertel 13107: sub rndseed_CODE_64bit5 {
                   13108:     my ($symb,$courseid,$domain,$username)=@_;
                   13109:     my $code = &getCODE();
                   13110:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13111:     return "$num1:$num2";
                   13112: }
                   13113: 
1.366     albertel 13114: sub setup_random_from_rndseed {
                   13115:     my ($rndseed)=@_;
1.503     albertel 13116:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13117: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13118:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13119:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13120:         } else {
                   13121:             &Math::Random::random_set_seed($num1,$num2);
                   13122:         }
1.366     albertel 13123:     } else {
                   13124: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13125:     }
1.36      albertel 13126: }
                   13127: 
1.474     albertel 13128: sub latest_receipt_algorithm_id {
1.835     albertel 13129:     return 'receipt3';
1.474     albertel 13130: }
                   13131: 
1.480     www      13132: sub recunique {
                   13133:     my $fucourseid=shift;
                   13134:     my $unique;
1.835     albertel 13135:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13136: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13137: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13138:     } else {
                   13139: 	$unique=$perlvar{'lonReceipt'};
                   13140:     }
                   13141:     return unpack("%32C*",$unique);
                   13142: }
                   13143: 
                   13144: sub recprefix {
                   13145:     my $fucourseid=shift;
                   13146:     my $prefix;
1.835     albertel 13147:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13148: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13149: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13150:     } else {
                   13151: 	$prefix=$perlvar{'lonHostID'};
                   13152:     }
                   13153:     return unpack("%32C*",$prefix);
                   13154: }
                   13155: 
1.76      www      13156: sub ireceipt {
1.474     albertel 13157:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13158: 
                   13159:     my $return =&recprefix($fucourseid).'-';
                   13160: 
                   13161:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13162: 	$env{'request.state'} eq 'construct') {
                   13163: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13164: 	return $return;
                   13165:     }
                   13166: 
1.76      www      13167:     my $cuname=unpack("%32C*",$funame);
                   13168:     my $cudom=unpack("%32C*",$fudom);
                   13169:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13170:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13171:     my $cunique=&recunique($fucourseid);
1.474     albertel 13172:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13173:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13174: 
1.790     albertel 13175: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13176: 			       
                   13177: 	$return.= ($cunique%$cuname+
                   13178: 		   $cunique%$cudom+
                   13179: 		   $cusymb%$cuname+
                   13180: 		   $cusymb%$cudom+
                   13181: 		   $cucourseid%$cuname+
                   13182: 		   $cucourseid%$cudom+
                   13183: 		   $cpart%$cuname+
                   13184: 		   $cpart%$cudom);
                   13185:     } else {
                   13186: 	$return.= ($cunique%$cuname+
                   13187: 		   $cunique%$cudom+
                   13188: 		   $cusymb%$cuname+
                   13189: 		   $cusymb%$cudom+
                   13190: 		   $cucourseid%$cuname+
                   13191: 		   $cucourseid%$cudom);
                   13192:     }
                   13193:     return $return;
1.76      www      13194: }
                   13195: 
                   13196: sub receipt {
1.474     albertel 13197:     my ($part)=@_;
1.790     albertel 13198:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13199:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13200: }
1.260     ng       13201: 
1.790     albertel 13202: sub whichuser {
                   13203:     my ($passedsymb)=@_;
                   13204:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13205:     if (defined($env{'form.grade_symb'})) {
                   13206: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13207: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13208: 	if (!$allowed &&
                   13209: 	    exists($env{'request.course.sec'}) &&
                   13210: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13211: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13212: 			      '/'.$env{'request.course.sec'});
                   13213: 	}
                   13214: 	if ($allowed) {
                   13215: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13216: 	    $courseid=$tmp_courseid;
                   13217: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13218: 	    ($name)=&get_env_multiple('form.grade_username');
                   13219: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13220: 	}
                   13221:     }
                   13222:     if (!$passedsymb) {
                   13223: 	$symb=&symbread();
                   13224:     } else {
                   13225: 	$symb=$passedsymb;
                   13226:     }
                   13227:     $courseid=$env{'request.course.id'};
                   13228:     $domain=$env{'user.domain'};
                   13229:     $name=$env{'user.name'};
                   13230:     if ($name eq 'public' && $domain eq 'public') {
                   13231: 	if (!defined($env{'form.username'})) {
                   13232: 	    $env{'form.username'}.=time.rand(10000000);
                   13233: 	}
                   13234: 	$name.=$env{'form.username'};
                   13235:     }
                   13236:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13237: 
                   13238: }
                   13239: 
1.36      albertel 13240: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13241: # returns either the contents of the file or 
                   13242: # -1 if the file doesn't exist
1.481     raeburn  13243: #
                   13244: # if the target is a file that was uploaded via DOCS, 
                   13245: # a check will be made to see if a current copy exists on the local server,
                   13246: # if it does this will be served, otherwise a copy will be retrieved from
                   13247: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13248: # the local server.   
1.472     albertel 13249: 
1.36      albertel 13250: sub getfile {
1.538     albertel 13251:     my ($file) = @_;
1.609     banghart 13252:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13253:     &repcopy($file);
                   13254:     return &readfile($file);
                   13255: }
                   13256: 
                   13257: sub repcopy_userfile {
                   13258:     my ($file)=@_;
1.1142    raeburn  13259:     my $londocroot = $perlvar{'lonDocRoot'};
                   13260:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13261:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13262:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13263: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13264:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13265:     if (-e "$file") {
1.828     www      13266: # we already have a local copy, check it out
1.538     albertel 13267: 	my @fileinfo = stat($file);
1.828     www      13268: 	my $rtncode;
                   13269: 	my $info;
1.538     albertel 13270: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13271: 	if ($lwpresp ne 'ok') {
1.828     www      13272: # there is no such file anymore, even though we had a local copy
1.482     albertel 13273: 	    if ($rtncode eq '404') {
1.538     albertel 13274: 		unlink($file);
1.482     albertel 13275: 	    }
                   13276: 	    return -1;
                   13277: 	}
                   13278: 	if ($info < $fileinfo[9]) {
1.828     www      13279: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13280: 	    return 'ok';
1.828     www      13281: 	} else {
                   13282: # the file is outdated, get rid of it
                   13283: 	    unlink($file);
1.482     albertel 13284: 	}
1.828     www      13285:     }
                   13286: # one way or the other, at this point, we don't have the file
                   13287: # construct the correct path for the file
                   13288:     my @parts = ($cdom,$cnum); 
                   13289:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13290: 	push @parts, split(/\//,$1);
                   13291:     }
                   13292:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13293:     foreach my $part (@parts) {
                   13294: 	$path .= '/'.$part;
                   13295: 	if (!-e $path) {
                   13296: 	    mkdir($path,0770);
1.482     albertel 13297: 	}
                   13298:     }
1.828     www      13299: # now the path exists for sure
                   13300: # get a user agent
                   13301:     my $ua=new LWP::UserAgent;
                   13302:     my $transferfile=$file.'.in.transfer';
                   13303: # FIXME: this should flock
                   13304:     if (-e $transferfile) { return 'ok'; }
                   13305:     my $request;
                   13306:     $uri=~s/^\///;
1.980     raeburn  13307:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13308:     my $hostname = &hostname($homeserver);
1.980     raeburn  13309:     my $protocol = $protocol{$homeserver};
                   13310:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13311:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13312:     my $response=$ua->request($request,$transferfile);
                   13313: # did it work?
                   13314:     if ($response->is_error()) {
                   13315: 	unlink($transferfile);
                   13316: 	&logthis("Userfile repcopy failed for $uri");
                   13317: 	return -1;
                   13318:     }
                   13319: # worked, rename the transfer file
                   13320:     rename($transferfile,$file);
1.607     raeburn  13321:     return 'ok';
1.481     raeburn  13322: }
                   13323: 
1.517     albertel 13324: sub tokenwrapper {
                   13325:     my $uri=shift;
1.980     raeburn  13326:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13327:     $uri=~s|^/||;
1.620     albertel 13328:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13329:     my $token=$1;
1.552     albertel 13330:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13331:     if ($udom && $uname && $file) {
                   13332: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13333:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13334:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13335:         my $hostname = &hostname($homeserver);
1.980     raeburn  13336:         my $protocol = $protocol{$homeserver};
                   13337:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13338:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13339:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13340:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13341:     } else {
                   13342:         return '/adm/notfound.html';
                   13343:     }
                   13344: }
                   13345: 
1.828     www      13346: # call with reqtype HEAD: get last modification time
                   13347: # call with reqtype GET: get the file contents
                   13348: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13349: #
1.481     raeburn  13350: sub getuploaded {
                   13351:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13352:     $uri=~s/^\///;
1.980     raeburn  13353:     my $homeserver = &homeserver($cnum,$cdom);
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:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13358:     my $ua=new LWP::UserAgent;
                   13359:     my $request=new HTTP::Request($reqtype,$uri);
                   13360:     my $response=$ua->request($request);
                   13361:     $$rtncode = $response->code;
1.482     albertel 13362:     if (! $response->is_success()) {
                   13363: 	return 'failed';
                   13364:     }      
                   13365:     if ($reqtype eq 'HEAD') {
1.486     www      13366: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13367:     } elsif ($reqtype eq 'GET') {
                   13368: 	$$info = $response->content;
1.472     albertel 13369:     }
1.482     albertel 13370:     return 'ok';
1.36      albertel 13371: }
                   13372: 
1.481     raeburn  13373: sub readfile {
                   13374:     my $file = shift;
                   13375:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13376:     my $fh;
1.1172.2.96  raeburn  13377:     open($fh,"<",$file);
1.481     raeburn  13378:     my $a='';
1.800     albertel 13379:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13380:     return $a;
                   13381: }
                   13382: 
1.36      albertel 13383: sub filelocation {
1.590     banghart 13384:     my ($dir,$file) = @_;
                   13385:     my $location;
                   13386:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13387: 
                   13388:     if ($file =~ m-^/adm/-) {
                   13389: 	$file=~s-^/adm/wrapper/-/-;
                   13390: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13391:     }
1.882     albertel 13392: 
1.1139    www      13393:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13394:         $location = $file;
1.609     banghart 13395:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13396:         my ($udom,$uname,$filename)=
1.811     albertel 13397:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13398:         my $home=&homeserver($uname,$udom);
                   13399:         my $is_me=0;
                   13400:         my @ids=&current_machine_ids();
                   13401:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13402:         if ($is_me) {
1.1117    foxr     13403:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13404:         } else {
                   13405:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13406:   	      $udom.'/'.$uname.'/'.$filename;
                   13407:         }
1.882     albertel 13408:     } elsif ($file =~ m-^/adm/-) {
                   13409: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13410:     } else {
                   13411:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13412:         $file=~s:^/(res|priv)/:/:;
                   13413:         my $space=$1;
1.590     banghart 13414:         if ( !( $file =~ m:^/:) ) {
                   13415:             $location = $dir. '/'.$file;
                   13416:         } else {
1.1142    raeburn  13417:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13418:         }
1.59      albertel 13419:     }
1.590     banghart 13420:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13421:     while ($location=~m{/\.\./}) {
                   13422: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13423: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13424: 	} else {
                   13425: 	    $location=~ s{/\.\./}{/}g;
                   13426: 	}
                   13427:     } #remove dir/..
1.590     banghart 13428:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13429:     return $location;
1.46      www      13430: }
1.36      albertel 13431: 
1.46      www      13432: sub hreflocation {
                   13433:     my ($dir,$file)=@_;
1.980     raeburn  13434:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13435: 	$file=filelocation($dir,$file);
1.700     albertel 13436:     } elsif ($file=~m-^/adm/-) {
                   13437: 	$file=~s-^/adm/wrapper/-/-;
                   13438: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13439:     }
                   13440:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13441: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13442:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13443: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13444: 	        {/uploaded/$1/$2/}x;
1.46      www      13445:     }
1.913     albertel 13446:     if ($file=~ m{^/userfiles/}) {
                   13447: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13448:     }
1.462     albertel 13449:     return $file;
1.465     albertel 13450: }
                   13451: 
1.1139    www      13452: 
                   13453: 
                   13454: 
                   13455: 
1.465     albertel 13456: sub current_machine_domains {
1.853     albertel 13457:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13458: }
                   13459: 
                   13460: sub machine_domains {
                   13461:     my ($hostname) = @_;
1.465     albertel 13462:     my @domains;
1.838     albertel 13463:     my %hostname = &all_hostnames();
1.465     albertel 13464:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13465: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13466: 	if ($hostname eq $name) {
1.844     albertel 13467: 	    push(@domains,&host_domain($id));
1.465     albertel 13468: 	}
                   13469:     }
                   13470:     return @domains;
                   13471: }
                   13472: 
                   13473: sub current_machine_ids {
1.853     albertel 13474:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13475: }
                   13476: 
                   13477: sub machine_ids {
                   13478:     my ($hostname) = @_;
                   13479:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13480:     my @ids;
1.888     albertel 13481:     my %name_to_host = &all_names();
1.889     albertel 13482:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13483: 	return @{ $name_to_host{$hostname} };
                   13484:     }
                   13485:     return;
1.31      www      13486: }
                   13487: 
1.824     raeburn  13488: sub additional_machine_domains {
                   13489:     my @domains;
1.1172.2.142  raeburn  13490:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13491:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13492:             while( my $line = <$fh>) {
                   13493:                 chomp($line);
                   13494:                 $line =~ s/\s//g;
                   13495:                 push(@domains,$line);
                   13496:             }
                   13497:             close($fh);
                   13498:         }
1.824     raeburn  13499:     }
                   13500:     return @domains;
                   13501: }
                   13502: 
                   13503: sub default_login_domain {
                   13504:     my $domain = $perlvar{'lonDefDomain'};
                   13505:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13506:     foreach my $posdom (&current_machine_domains(),
                   13507:                         &additional_machine_domains()) {
                   13508:         if (lc($posdom) eq lc($testdomain)) {
                   13509:             $domain=$posdom;
                   13510:             last;
                   13511:         }
                   13512:     }
                   13513:     return $domain;
                   13514: }
                   13515: 
1.1172.2.106  raeburn  13516: sub shared_institution {
1.1172.2.136  raeburn  13517:     my ($dom,$lonhost) = @_;
                   13518:     if ($lonhost eq '') {
                   13519:         $lonhost = $perlvar{'lonHostID'};
                   13520:     }
1.1172.2.106  raeburn  13521:     my $same_intdom;
1.1172.2.136  raeburn  13522:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13523:     if ($hostintdom ne '') {
                   13524:         my %iphost = &get_iphost();
                   13525:         my $primary_id = &domain($dom,'primary');
                   13526:         my $primary_ip = &get_host_ip($primary_id);
                   13527:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13528:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13529:                 my $intdom = &internet_dom($id);
                   13530:                 if ($intdom eq $hostintdom) {
                   13531:                     $same_intdom = 1;
                   13532:                     last;
                   13533:                 }
                   13534:             }
                   13535:         }
                   13536:     }
                   13537:     return $same_intdom;
                   13538: }
                   13539: 
1.1172.2.120  raeburn  13540: sub uses_sts {
                   13541:     my ($ignore_cache) = @_;
                   13542:     my $lonhost = $perlvar{'lonHostID'};
                   13543:     my $hostname = &hostname($lonhost);
                   13544:     my $sts_on;
                   13545:     if ($protocol{$lonhost} eq 'https') {
                   13546:         my $cachetime = 12*3600;
                   13547:         if (!$ignore_cache) {
                   13548:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13549:             if (defined($cached)) {
                   13550:                 return $sts_on;
                   13551:             }
                   13552:         }
1.1172.2.121  raeburn  13553:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13554:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13555:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13556:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13557:         if ($response->is_success) {
                   13558:             my $has_sts = $response->header('Strict-Transport-Security');
                   13559:             if ($has_sts eq '') {
                   13560:                 $sts_on = 0;
                   13561:             } else {
                   13562:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13563:                     my $maxage = $1;
                   13564:                     if ($maxage) {
                   13565:                         $sts_on = 1;
                   13566:                     } else {
                   13567:                         $sts_on = 0;
                   13568:                     }
                   13569:                 } else {
                   13570:                     $sts_on = 0;
                   13571:                 }
                   13572:             }
                   13573:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13574:         }
                   13575:     }
                   13576:     return;
                   13577: }
                   13578: 
1.1172.2.142  raeburn  13579: sub waf_allssl {
                   13580:     my ($host_name) = @_;
                   13581:     my $alias = &get_proxy_alias();
                   13582:     if ($host_name eq '') {
                   13583:         $host_name = $ENV{'SERVER_NAME'};
                   13584:     }
                   13585:     if (($host_name ne '') && ($alias eq $host_name)) {
                   13586:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   13587:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   13588:         if ($defdomdefaults{'waf_sslopt'}) {
                   13589:             return $defdomdefaults{'waf_sslopt'};
                   13590:         }
                   13591:     }
                   13592:     return;
                   13593: }
                   13594: 
1.1172.2.134  raeburn  13595: sub get_requestor_ip {
                   13596:     my ($r,$nolookup,$noproxy) = @_;
                   13597:     my $from_ip;
                   13598:     if (ref($r)) {
1.1172.2.142  raeburn  13599:         if ($r->can('useragent_ip')) {
                   13600:             if ($noproxy && $r->can('client_ip')) {
                   13601:                 $from_ip = $r->client_ip();
                   13602:             } else {
                   13603:                 $from_ip = $r->useragent_ip();
                   13604:             }
                   13605:         } elsif ($r->connection->can('remote_ip')) {
                   13606:             $from_ip = $r->connection->remote_ip();
                   13607:         } else {
                   13608:             $from_ip = $r->get_remote_host($nolookup);
                   13609:         }
1.1172.2.134  raeburn  13610:     } else {
                   13611:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13612:     }
1.1172.2.142  raeburn  13613:     return $from_ip if ($noproxy);
                   13614:    # Who controls proxy settings for server
                   13615:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   13616:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   13617:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   13618:         if ($proxyinfo->{'vpnint'}) {
                   13619:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   13620:                 return $from_ip;
                   13621:             }
                   13622:         }
                   13623:         if ($proxyinfo->{'trusted'}) {
                   13624:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   13625:                 my $ipheader = $proxyinfo->{'ipheader'};
                   13626:                 my ($ip,$xfor);
                   13627:                 if (ref($r)) {
                   13628:                     if ($ipheader) {
                   13629:                         $ip = $r->headers_in->{$ipheader};
                   13630:                     }
                   13631:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   13632:                 } else {
                   13633:                     if ($ipheader) {
                   13634:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   13635:                     }
                   13636:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   13637:                 }
                   13638:                 if (($ip eq '') && ($xfor ne '')) {
                   13639:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   13640:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   13641:                             $ip = $poss_ip;
                   13642:                             last;
                   13643:                         }
                   13644:                     }
                   13645:                 }
                   13646:                 if ($ip ne '') {
                   13647:                     return $ip;
                   13648:                 }
                   13649:             }
                   13650:         }
                   13651:     }
1.1172.2.134  raeburn  13652:     return $from_ip;
                   13653: }
                   13654: 
1.1172.2.142  raeburn  13655: sub get_proxy_settings {
                   13656:     my ($dom_in_use) = @_;
                   13657:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   13658:     my $proxyinfo = {
                   13659:                        ipheader => $domdefaults{'waf_ipheader'},
                   13660:                        trusted  => $domdefaults{'waf_trusted'},
                   13661:                        vpnint   => $domdefaults{'waf_vpnint'},
                   13662:                        vpnext   => $domdefaults{'waf_vpnext'},
                   13663:                        sslopt   => $domdefaults{'waf_sslopt'},
                   13664:                     };
                   13665:     return $proxyinfo;
                   13666: }
                   13667: 
                   13668: sub ip_match {
                   13669:     my ($ip,$pattern_str) = @_;
                   13670:     $ip=Net::CIDR::cidrvalidate($ip);
                   13671:     if ($ip) {
                   13672:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   13673:     }
                   13674:     return;
                   13675: }
                   13676: 
                   13677: sub get_proxy_alias {
                   13678:     my ($lonid) = @_;
                   13679:     if ($lonid eq '') {
                   13680:         $lonid = $perlvar{'lonHostID'};
                   13681:     }
                   13682:     if (!defined(&hostname($lonid))) {
                   13683:         return;
                   13684:     }
                   13685:     if ($lonid ne '') {
                   13686:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   13687:         if ($cached) {
                   13688:             return $alias;
                   13689:         }
                   13690:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13691:         if ($dom ne '') {
                   13692:             my $cachetime = 60*60*24;
                   13693:             my %domconfig =
                   13694:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13695:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13696:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   13697:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   13698:                 }
                   13699:             }
                   13700:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   13701:         }
                   13702:     }
                   13703:     return;
                   13704: }
                   13705: 
                   13706: sub use_proxy_alias {
                   13707:     my ($r,$lonid) = @_;
                   13708:     my $alias = &get_proxy_alias($lonid);
                   13709:     if ($alias) {
                   13710:         my $dom = &host_domain($lonid);
                   13711:         if ($dom ne '') {
                   13712:             my $proxyinfo = &get_proxy_settings($dom);
                   13713:             my ($vpnint,$remote_ip);
                   13714:             if (ref($proxyinfo) eq 'HASH') {
                   13715:                 $vpnint = $proxyinfo->{'vpnint'};
                   13716:                 if ($vpnint) {
                   13717:                     $remote_ip = &get_requestor_ip($r,1,1);
                   13718:                 }
                   13719:             }
                   13720:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   13721:                 return $alias;
                   13722:             }
                   13723:         }
                   13724:     }
                   13725:     return;
                   13726: }
                   13727: 
                   13728: sub alias_sso {
                   13729:     my ($lonid) = @_;
                   13730:     if ($lonid eq '') {
                   13731:         $lonid = $perlvar{'lonHostID'};
                   13732:     }
                   13733:     if (!defined(&hostname($lonid))) {
                   13734:         return;
                   13735:     }
                   13736:     if ($lonid ne '') {
                   13737:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   13738:         if ($cached) {
                   13739:             return $use_alias;
                   13740:         }
                   13741:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13742:         if ($dom ne '') {
                   13743:             my $cachetime = 60*60*24;
                   13744:             my %domconfig =
                   13745:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13746:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13747:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   13748:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   13749:                 }
                   13750:             }
                   13751:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   13752:         }
                   13753:     }
                   13754:     return;
                   13755: }
                   13756: 
                   13757: sub get_saml_landing {
                   13758:     my ($lonid) = @_;
                   13759:     if ($lonid eq '') {
                   13760:         my $defdom = &default_login_domain();
                   13761:         my @hosts = &current_machine_ids();
                   13762:         if (@hosts > 1) {
                   13763:             foreach my $hostid (@hosts) {
                   13764:                 if (&host_domain($hostid) eq $defdom) {
                   13765:                     $lonid = $hostid;
                   13766:                     last;
                   13767:                 }
                   13768:             }
                   13769:         } else {
                   13770:             $lonid = $perlvar{'lonHostID'};
                   13771:         }
                   13772:         if ($lonid) {
                   13773:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   13774:                 return;
                   13775:             }
                   13776:         } else {
                   13777:             return;
                   13778:         }
                   13779:     } elsif (!defined(&hostname($lonid))) {
                   13780:         return;
                   13781:     }
                   13782:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   13783:     if ($cached) {
                   13784:         return $landing;
                   13785:     }
                   13786:     my $dom = &Apache::lonnet::host_domain($lonid);
                   13787:     if ($dom ne '') {
                   13788:         my $cachetime = 60*60*24;
                   13789:         my %domconfig =
                   13790:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   13791:         if (ref($domconfig{'login'}) eq 'HASH') {
                   13792:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   13793:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   13794:                     $landing = 1;
                   13795:                 }
                   13796:             }
                   13797:         }
                   13798:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   13799:     }
                   13800:     return;
                   13801: }
                   13802: 
1.31      www      13803: # ------------------------------------------------------------- Declutters URLs
                   13804: 
                   13805: sub declutter {
                   13806:     my $thisfn=shift;
1.569     albertel 13807:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13808:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13809:         $thisfn=~s{^/home/httpd/html}{};
                   13810:     }
1.31      www      13811:     $thisfn=~s/^\///;
1.697     albertel 13812:     $thisfn=~s|^adm/wrapper/||;
                   13813:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13814:     $thisfn=~s/^res\///;
1.1172    bisitz   13815:     $thisfn=~s/^priv\///;
1.1032    raeburn  13816:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13817:         $thisfn=~s/\?.+$//;
                   13818:     }
1.268     www      13819:     return $thisfn;
                   13820: }
                   13821: 
                   13822: # ------------------------------------------------------------- Clutter up URLs
                   13823: 
                   13824: sub clutter {
                   13825:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13826:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13827: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13828:        $thisfn='/res'.$thisfn; 
                   13829:     }
1.1031    raeburn  13830:     if ($thisfn !~m|^/adm|) {
                   13831: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13832: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13833: 	} else {
                   13834: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13835: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13836: 	    if ($embstyle eq 'ssi'
                   13837: 		|| ($embstyle eq 'hdn')
                   13838: 		|| ($embstyle eq 'rat')
                   13839: 		|| ($embstyle eq 'prv')
                   13840: 		|| ($embstyle eq 'ign')) {
                   13841: 		#do nothing with these
                   13842: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13843: 		|| ($embstyle eq 'emb')
                   13844: 		|| ($embstyle eq 'wrp')) {
                   13845: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13846: 	    } elsif ($embstyle eq 'unk'
                   13847: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13848: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13849: 	    } else {
1.718     www      13850: #		&logthis("Got a blank emb style");
1.695     albertel 13851: 	    }
1.694     albertel 13852: 	}
                   13853:     }
1.31      www      13854:     return $thisfn;
1.12      www      13855: }
                   13856: 
1.787     albertel 13857: sub clutter_with_no_wrapper {
                   13858:     my $uri = &clutter(shift);
                   13859:     if ($uri =~ m-^/adm/-) {
                   13860: 	$uri =~ s-^/adm/wrapper/-/-;
                   13861: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13862:     }
                   13863:     return $uri;
                   13864: }
                   13865: 
1.557     albertel 13866: sub freeze_escape {
                   13867:     my ($value)=@_;
                   13868:     if (ref($value)) {
                   13869: 	$value=&nfreeze($value);
                   13870: 	return '__FROZEN__'.&escape($value);
                   13871:     }
                   13872:     return &escape($value);
                   13873: }
                   13874: 
1.11      www      13875: 
1.557     albertel 13876: sub thaw_unescape {
                   13877:     my ($value)=@_;
                   13878:     if ($value =~ /^__FROZEN__/) {
                   13879: 	substr($value,0,10,undef);
                   13880: 	$value=&unescape($value);
                   13881: 	return &thaw($value);
                   13882:     }
                   13883:     return &unescape($value);
                   13884: }
                   13885: 
1.436     albertel 13886: sub correct_line_ends {
                   13887:     my ($result)=@_;
                   13888:     $$result =~s/\r\n/\n/mg;
                   13889:     $$result =~s/\r/\n/mg;
1.415     albertel 13890: }
1.1       albertel 13891: # ================================================================ Main Program
                   13892: 
1.184     www      13893: sub goodbye {
1.204     albertel 13894:    &logthis("Starting Shut down");
1.443     albertel 13895: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13896:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13897: #converted
1.599     albertel 13898: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13899:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13900: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13901: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13902: #1.1 only
1.870     albertel 13903: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13904: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13905: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13906: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13907:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13908:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13909:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13910:    &flushcourselogs();
                   13911:    &logthis("Shutting down");
                   13912: }
                   13913: 
1.852     albertel 13914: sub get_dns {
1.1172.2.17  raeburn  13915:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13916:     if (!$ignore_cache) {
                   13917: 	my ($content,$cached)=
                   13918: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13919: 	if ($cached) {
1.1172.2.17  raeburn  13920: 	    &$func($content,$hashref);
1.869     albertel 13921: 	    return;
                   13922: 	}
                   13923:     }
                   13924: 
                   13925:     my %alldns;
1.1172.2.96  raeburn  13926:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13927:         foreach my $dns (<$config>) {
                   13928: 	    next if ($dns !~ /^\^(\S*)/x);
                   13929:             my $line = $1;
                   13930:             my ($host,$protocol) = split(/:/,$line);
                   13931:             if ($protocol ne 'https') {
                   13932:                 $protocol = 'http';
                   13933:             }
                   13934: 	    $alldns{$host} = $protocol;
1.979     raeburn  13935:         }
1.1172.2.96  raeburn  13936:         close($config);
1.869     albertel 13937:     }
                   13938:     while (%alldns) {
1.1172.2.52  raeburn  13939: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  13940:         my @content;
                   13941:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   13942:             my $command = (split('/',$url))[3];
                   13943:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   13944:             delete($alldns{$dns});
                   13945:             next if (($dir eq '') || ($file eq ''));
                   13946:             if (open(my $config,'<',"$dir/$file")) {
                   13947:                 @content = <$config>;
                   13948:                 close($config);
                   13949:             }
                   13950:         } else {
                   13951: 	    my $ua=new LWP::UserAgent;
                   13952:             $ua->timeout(30);
                   13953: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   13954: 	    my $response=$ua->request($request);
                   13955:             delete($alldns{$dns});
                   13956: 	    next if ($response->is_error());
                   13957: 	    @content = split("\n",$response->content);
                   13958:         }
1.1172.2.17  raeburn  13959:         unless ($nocache) {
1.1172.2.23  raeburn  13960: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13961:         }
                   13962: 	&$func(\@content,$hashref);
1.869     albertel 13963: 	return;
1.852     albertel 13964:     }
1.871     albertel 13965:     my $which = (split('/',$url))[3];
                   13966:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13967:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13968:         my @content = <$config>;
                   13969:         &$func(\@content,$hashref);
                   13970:     }
1.1172.2.17  raeburn  13971:     return;
                   13972: }
                   13973: 
                   13974: # ------------------------------------------------------Get DNS checksums file
                   13975: sub parse_dns_checksums_tab {
                   13976:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13977:     my $lonhost = $perlvar{'lonHostID'};
                   13978:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13979:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13980:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13981:     my $webconfdir = '/etc/httpd/conf';
                   13982:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13983:         $webconfdir = '/etc/apache2';
                   13984:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13985:         if ($1 >= 10) {
                   13986:             $webconfdir = '/etc/apache2';
                   13987:         }
                   13988:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13989:         if ($1 >= 10.0) {
                   13990:             $webconfdir = '/etc/apache2';
                   13991:         }
                   13992:     }
1.1172.2.17  raeburn  13993:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13994:     my (%chksum,%revnum);
                   13995:     if (ref($lines) eq 'ARRAY') {
                   13996:         chomp(@{$lines});
1.1172.2.34  raeburn  13997:         my $version = shift(@{$lines});
                   13998:         if ($version eq $release) {
1.1172.2.17  raeburn  13999:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14000:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14001:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14002:                     if ($webconfdir eq '/etc/apache2') {
                   14003:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14004:                     }
                   14005:                 }
1.1172.2.34  raeburn  14006:                 $chksum{$file} = $shasum;
                   14007:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14008:             }
                   14009:             if (ref($hashref) eq 'HASH') {
                   14010:                 %{$hashref} = (
                   14011:                                 sums     => \%chksum,
                   14012:                                 versions => \%revnum,
                   14013:                               );
                   14014:             }
                   14015:         }
                   14016:     }
1.869     albertel 14017:     return;
1.852     albertel 14018: }
1.1172.2.17  raeburn  14019: 
                   14020: sub fetch_dns_checksums {
                   14021:     my %checksums;
1.1172.2.34  raeburn  14022:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14023:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14024:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14025:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14026:              \%checksums);
                   14027:     return \%checksums;
                   14028: }
                   14029: 
1.1172.2.142  raeburn  14030: sub parse_getdns_url {
                   14031:     my ($command,$url) = @_;
                   14032:     my $dir = $perlvar{'lonTabDir'};
                   14033:     my $file;
                   14034:     if ($command eq 'hosts') {
                   14035:         $file = 'dns_hosts.tab';
                   14036:     } elsif ($command eq 'domain') {
                   14037:         $file = 'dns_domain.tab';
                   14038:     } elsif ($command eq 'checksums') {
                   14039:         my $version = (split('/',$url))[4];
                   14040:         $file = "dns_checksums/$version.tab",
                   14041:     }
                   14042:     return ($dir,$file);
                   14043: }
                   14044: 
1.327     albertel 14045: # ------------------------------------------------------------ Read domain file
                   14046: {
1.852     albertel 14047:     my $loaded;
1.846     albertel 14048:     my %domain;
                   14049: 
1.852     albertel 14050:     sub parse_domain_tab {
                   14051: 	my ($lines) = @_;
                   14052: 	foreach my $line (@$lines) {
                   14053: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14054: 
1.846     albertel 14055: 	    chomp($line);
1.852     albertel 14056: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14057: 	    my %this_domain;
                   14058: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14059: 			       'lang_def', 'city', 'longi', 'lati',
                   14060: 			       'primary') {
                   14061: 		$this_domain{$field} = shift(@elements);
                   14062: 	    }
                   14063: 	    $domain{$name} = \%this_domain;
1.852     albertel 14064: 	}
                   14065:     }
1.864     albertel 14066: 
                   14067:     sub reset_domain_info {
                   14068: 	undef($loaded);
                   14069: 	undef(%domain);
                   14070:     }
                   14071: 
1.852     albertel 14072:     sub load_domain_tab {
1.1172.2.70  raeburn  14073: 	my ($ignore_cache,$nocache) = @_;
                   14074: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14075: 	my $fh;
1.1172.2.96  raeburn  14076: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14077: 	    my @lines = <$fh>;
                   14078: 	    &parse_domain_tab(\@lines);
1.448     albertel 14079: 	}
1.852     albertel 14080: 	close($fh);
                   14081: 	$loaded = 1;
1.327     albertel 14082:     }
1.846     albertel 14083: 
                   14084:     sub domain {
1.852     albertel 14085: 	&load_domain_tab() if (!$loaded);
                   14086: 
1.846     albertel 14087: 	my ($name,$what) = @_;
                   14088: 	return if ( !exists($domain{$name}) );
                   14089: 
                   14090: 	if (!$what) {
                   14091: 	    return $domain{$name}{'description'};
                   14092: 	}
                   14093: 	return $domain{$name}{$what};
                   14094:     }
1.974     raeburn  14095: 
                   14096:     sub domain_info {
                   14097:         &load_domain_tab() if (!$loaded);
                   14098:         return %domain;
                   14099:     }
                   14100: 
1.327     albertel 14101: }
                   14102: 
                   14103: 
1.1       albertel 14104: # ------------------------------------------------------------- Read hosts file
                   14105: {
1.838     albertel 14106:     my %hostname;
1.844     albertel 14107:     my %hostdom;
1.845     albertel 14108:     my %libserv;
1.852     albertel 14109:     my $loaded;
1.888     albertel 14110:     my %name_to_host;
1.1074    raeburn  14111:     my %internetdom;
1.1107    raeburn  14112:     my %LC_dns_serv;
1.852     albertel 14113: 
                   14114:     sub parse_hosts_tab {
                   14115: 	my ($file) = @_;
                   14116: 	foreach my $configline (@$file) {
                   14117: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14118:             chomp($configline);
                   14119: 	    if ($configline =~ /^\^/) {
                   14120:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14121:                     $LC_dns_serv{$1} = 1;
                   14122:                 }
                   14123:                 next;
                   14124:             }
1.1074    raeburn  14125: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14126: 	    $name=~s/\s//g;
                   14127: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14128:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14129:                     my $curr = $hostname{$id};
                   14130:                     my $skip;
                   14131:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14132:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14133:                             $skip = 1;
                   14134:                         } else {
                   14135:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14136:                         }
                   14137:                     }
                   14138:                     unless ($skip) {
                   14139:                         push(@{$name_to_host{$name}},$id);
                   14140:                     }
                   14141:                 } else {
                   14142:                     push(@{$name_to_host{$name}},$id);
                   14143:                 }
1.852     albertel 14144: 		$hostname{$id}=$name;
                   14145: 		$hostdom{$id}=$domain;
                   14146: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14147:                 if (defined($protocol)) {
                   14148:                     if ($protocol eq 'https') {
                   14149:                         $protocol{$id} = $protocol;
                   14150:                     } else {
                   14151:                         $protocol{$id} = 'http'; 
                   14152:                     }
1.968     raeburn  14153:                 } else {
1.969     raeburn  14154:                     $protocol{$id} = 'http';
1.968     raeburn  14155:                 }
1.1074    raeburn  14156:                 if (defined($intdom)) {
                   14157:                     $internetdom{$id} = $intdom;
                   14158:                 }
1.852     albertel 14159: 	    }
                   14160: 	}
                   14161:     }
1.864     albertel 14162:     
                   14163:     sub reset_hosts_info {
1.897     albertel 14164: 	&purge_remembered();
1.864     albertel 14165: 	&reset_domain_info();
                   14166: 	&reset_hosts_ip_info();
1.892     albertel 14167: 	undef(%name_to_host);
1.864     albertel 14168: 	undef(%hostname);
                   14169: 	undef(%hostdom);
                   14170: 	undef(%libserv);
                   14171: 	undef($loaded);
                   14172:     }
1.1       albertel 14173: 
1.852     albertel 14174:     sub load_hosts_tab {
1.1172.2.70  raeburn  14175: 	my ($ignore_cache,$nocache) = @_;
                   14176: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14177: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14178: 	my @config = <$config>;
                   14179: 	&parse_hosts_tab(\@config);
                   14180: 	close($config);
                   14181: 	$loaded=1;
1.1       albertel 14182:     }
1.852     albertel 14183: 
1.838     albertel 14184:     sub hostname {
1.852     albertel 14185: 	&load_hosts_tab() if (!$loaded);
                   14186: 
1.838     albertel 14187: 	my ($lonid) = @_;
                   14188: 	return $hostname{$lonid};
                   14189:     }
1.845     albertel 14190: 
1.838     albertel 14191:     sub all_hostnames {
1.852     albertel 14192: 	&load_hosts_tab() if (!$loaded);
                   14193: 
1.838     albertel 14194: 	return %hostname;
                   14195:     }
1.845     albertel 14196: 
1.888     albertel 14197:     sub all_names {
1.1172.2.70  raeburn  14198:         my ($ignore_cache,$nocache) = @_;
                   14199: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14200: 
                   14201: 	return %name_to_host;
                   14202:     }
                   14203: 
1.974     raeburn  14204:     sub all_host_domain {
                   14205:         &load_hosts_tab() if (!$loaded);
                   14206:         return %hostdom;
                   14207:     }
                   14208: 
1.845     albertel 14209:     sub is_library {
1.852     albertel 14210: 	&load_hosts_tab() if (!$loaded);
                   14211: 
1.845     albertel 14212: 	return exists($libserv{$_[0]});
                   14213:     }
                   14214: 
                   14215:     sub all_library {
1.852     albertel 14216: 	&load_hosts_tab() if (!$loaded);
                   14217: 
1.845     albertel 14218: 	return %libserv;
                   14219:     }
                   14220: 
1.1062    droeschl 14221:     sub unique_library {
                   14222: 	#2x reverse removes all hostnames that appear more than once
                   14223:         my %unique = reverse &all_library();
                   14224:         return reverse %unique;
                   14225:     }
                   14226: 
1.841     albertel 14227:     sub get_servers {
1.852     albertel 14228: 	&load_hosts_tab() if (!$loaded);
                   14229: 
1.841     albertel 14230: 	my ($domain,$type) = @_;
                   14231: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14232: 	                                          : %hostname;
                   14233: 	my %result;
1.842     albertel 14234: 	if (ref($domain) eq 'ARRAY') {
                   14235: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14236: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14237: 		    $result{$host} = $hostname;
                   14238: 		}
                   14239: 	    }
                   14240: 	} else {
                   14241: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14242: 		if ($hostdom{$host} eq $domain) {
                   14243: 		    $result{$host} = $hostname;
                   14244: 		}
1.841     albertel 14245: 	    }
                   14246: 	}
                   14247: 	return %result;
                   14248:     }
1.845     albertel 14249: 
1.1062    droeschl 14250:     sub get_unique_servers {
                   14251:         my %unique = reverse &get_servers(@_);
                   14252: 	return reverse %unique;
                   14253:     }
                   14254: 
1.844     albertel 14255:     sub host_domain {
1.852     albertel 14256: 	&load_hosts_tab() if (!$loaded);
                   14257: 
1.844     albertel 14258: 	my ($lonid) = @_;
                   14259: 	return $hostdom{$lonid};
                   14260:     }
                   14261: 
1.841     albertel 14262:     sub all_domains {
1.852     albertel 14263: 	&load_hosts_tab() if (!$loaded);
                   14264: 
1.841     albertel 14265: 	my %seen;
                   14266: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14267: 	return @uniq;
                   14268:     }
1.1074    raeburn  14269: 
                   14270:     sub internet_dom {
                   14271:         &load_hosts_tab() if (!$loaded);
                   14272: 
                   14273:         my ($lonid) = @_;
                   14274:         return $internetdom{$lonid};
                   14275:     }
1.1107    raeburn  14276: 
                   14277:     sub is_LC_dns {
                   14278:         &load_hosts_tab() if (!$loaded);
                   14279: 
                   14280:         my ($hostname) = @_;
                   14281:         return exists($LC_dns_serv{$hostname});
                   14282:     }
                   14283: 
1.1       albertel 14284: }
                   14285: 
1.847     albertel 14286: { 
                   14287:     my %iphost;
1.856     albertel 14288:     my %name_to_ip;
                   14289:     my %lonid_to_ip;
1.869     albertel 14290: 
1.847     albertel 14291:     sub get_hosts_from_ip {
                   14292: 	my ($ip) = @_;
                   14293: 	my %iphosts = &get_iphost();
                   14294: 	if (ref($iphosts{$ip})) {
                   14295: 	    return @{$iphosts{$ip}};
                   14296: 	}
                   14297: 	return;
1.839     albertel 14298:     }
1.864     albertel 14299:     
                   14300:     sub reset_hosts_ip_info {
                   14301: 	undef(%iphost);
                   14302: 	undef(%name_to_ip);
                   14303: 	undef(%lonid_to_ip);
                   14304:     }
1.856     albertel 14305: 
                   14306:     sub get_host_ip {
                   14307: 	my ($lonid) = @_;
                   14308: 	if (exists($lonid_to_ip{$lonid})) {
                   14309: 	    return $lonid_to_ip{$lonid};
                   14310: 	}
                   14311: 	my $name=&hostname($lonid);
                   14312:    	my $ip = gethostbyname($name);
                   14313: 	return if (!$ip || length($ip) ne 4);
                   14314: 	$ip=inet_ntoa($ip);
                   14315: 	$name_to_ip{$name}   = $ip;
                   14316: 	$lonid_to_ip{$lonid} = $ip;
                   14317: 	return $ip;
                   14318:     }
1.847     albertel 14319:     
                   14320:     sub get_iphost {
1.1172.2.70  raeburn  14321: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14322: 
1.869     albertel 14323: 	if (!$ignore_cache) {
                   14324: 	    if (%iphost) {
                   14325: 		return %iphost;
                   14326: 	    }
                   14327: 	    my ($ip_info,$cached)=
                   14328: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14329: 	    if ($cached) {
                   14330: 		%iphost      = %{$ip_info->[0]};
                   14331: 		%name_to_ip  = %{$ip_info->[1]};
                   14332: 		%lonid_to_ip = %{$ip_info->[2]};
                   14333: 		return %iphost;
                   14334: 	    }
                   14335: 	}
1.894     albertel 14336: 
                   14337: 	# get yesterday's info for fallback
                   14338: 	my %old_name_to_ip;
                   14339: 	my ($ip_info,$cached)=
                   14340: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14341: 	if ($cached) {
                   14342: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14343: 	}
                   14344: 
1.1172.2.70  raeburn  14345: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14346: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14347: 	    my $ip;
                   14348: 	    if (!exists($name_to_ip{$name})) {
                   14349: 		$ip = gethostbyname($name);
                   14350: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14351: 		    if (defined($old_name_to_ip{$name})) {
                   14352: 			$ip = $old_name_to_ip{$name};
                   14353: 			&logthis("Can't find $name defaulting to old $ip");
                   14354: 		    } else {
                   14355: 			&logthis("Name $name no IP found");
                   14356: 			next;
                   14357: 		    }
                   14358: 		} else {
                   14359: 		    $ip=inet_ntoa($ip);
1.847     albertel 14360: 		}
                   14361: 		$name_to_ip{$name} = $ip;
                   14362: 	    } else {
                   14363: 		$ip = $name_to_ip{$name};
1.653     albertel 14364: 	    }
1.888     albertel 14365: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14366: 		$lonid_to_ip{$id} = $ip;
                   14367: 	    }
                   14368: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14369: 	}
1.1172.2.70  raeburn  14370:         unless ($nocache) {
                   14371: 	    &do_cache_new('iphost','iphost',
                   14372: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14373: 		          48*60*60);
                   14374:         }
1.869     albertel 14375: 
1.847     albertel 14376: 	return %iphost;
1.598     albertel 14377:     }
                   14378: 
1.992     raeburn  14379:     #
                   14380:     #  Given a DNS returns the loncapa host name for that DNS 
                   14381:     # 
                   14382:     sub host_from_dns {
                   14383:         my ($dns) = @_;
                   14384:         my @hosts;
                   14385:         my $ip;
                   14386: 
1.993     raeburn  14387:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14388:             $ip = $name_to_ip{$dns};
                   14389:         }
                   14390:         if (!$ip) {
                   14391:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14392:             if (length($ip) == 4) { 
                   14393: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14394:             }
                   14395:         }
                   14396:         if ($ip) {
                   14397: 	    @hosts = get_hosts_from_ip($ip);
                   14398: 	    return $hosts[0];
                   14399:         }
                   14400:         return undef;
1.986     foxr     14401:     }
1.992     raeburn  14402: 
1.1074    raeburn  14403:     sub get_internet_names {
                   14404:         my ($lonid) = @_;
                   14405:         return if ($lonid eq '');
                   14406:         my ($idnref,$cached)=
                   14407:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14408:         if ($cached) {
                   14409:             return $idnref;
                   14410:         }
                   14411:         my $ip = &get_host_ip($lonid);
                   14412:         my @hosts = &get_hosts_from_ip($ip);
                   14413:         my %iphost = &get_iphost();
                   14414:         my (@idns,%seen);
                   14415:         foreach my $id (@hosts) {
                   14416:             my $dom = &host_domain($id);
                   14417:             my $prim_id = &domain($dom,'primary');
                   14418:             my $prim_ip = &get_host_ip($prim_id);
                   14419:             next if ($seen{$prim_ip});
                   14420:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14421:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14422:                     my $intdom = &internet_dom($id);
                   14423:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14424:                         push(@idns,$intdom);
                   14425:                     }
                   14426:                 }
                   14427:             }
                   14428:             $seen{$prim_ip} = 1;
                   14429:         }
1.1172.2.23  raeburn  14430:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14431:     }
                   14432: 
1.986     foxr     14433: }
                   14434: 
1.1079    raeburn  14435: sub all_loncaparevs {
1.1172.2.39  raeburn  14436:     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  14437: }
                   14438: 
1.1172.2.27  raeburn  14439: # ------------------------------------------------------- Read loncaparev table
                   14440: {
                   14441:     sub load_loncaparevs {
                   14442:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14443:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14444:                 while (my $configline=<$config>) {
                   14445:                     chomp($configline);
                   14446:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14447:                     $loncaparevs{$hostid}=$loncaparev;
                   14448:                 }
                   14449:                 close($config);
                   14450:             }
                   14451:         }
                   14452:     }
                   14453: }
                   14454: 
                   14455: # ----------------------------------------------------- Read serverhostID table
                   14456: {
                   14457:     sub load_serverhomeIDs {
                   14458:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14459:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14460:                 while (my $configline=<$config>) {
                   14461:                     chomp($configline);
                   14462:                     my ($name,$id)=split(/:/,$configline);
                   14463:                     $serverhomeIDs{$name}=$id;
                   14464:                 }
                   14465:                 close($config);
                   14466:             }
                   14467:         }
                   14468:     }
                   14469: }
                   14470: 
                   14471: 
1.862     albertel 14472: BEGIN {
                   14473: 
                   14474: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14475:     unless ($readit) {
                   14476: {
                   14477:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14478:     %perlvar = (%perlvar,%{$configvars});
                   14479: }
                   14480: 
                   14481: 
1.1       albertel 14482: # ------------------------------------------------------ Read spare server file
                   14483: {
1.1172.2.96  raeburn  14484:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14485: 
                   14486:     while (my $configline=<$config>) {
                   14487:        chomp($configline);
1.284     matthew  14488:        if ($configline) {
1.784     albertel 14489: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14490: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14491: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14492:        }
                   14493:     }
1.448     albertel 14494:     close($config);
1.1       albertel 14495: }
1.11      www      14496: # ------------------------------------------------------------ Read permissions
                   14497: {
1.1172.2.96  raeburn  14498:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14499: 
                   14500:     while (my $configline=<$config>) {
1.448     albertel 14501: 	chomp($configline);
                   14502: 	if ($configline) {
                   14503: 	    my ($role,$perm)=split(/ /,$configline);
                   14504: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14505: 	}
1.11      www      14506:     }
1.448     albertel 14507:     close($config);
1.11      www      14508: }
                   14509: 
                   14510: # -------------------------------------------- Read plain texts for permissions
                   14511: {
1.1172.2.96  raeburn  14512:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14513: 
                   14514:     while (my $configline=<$config>) {
1.448     albertel 14515: 	chomp($configline);
                   14516: 	if ($configline) {
1.742     raeburn  14517: 	    my ($short,@plain)=split(/:/,$configline);
                   14518:             %{$prp{$short}} = ();
                   14519: 	    if (@plain > 0) {
                   14520:                 $prp{$short}{'std'} = $plain[0];
                   14521:                 for (my $i=1; $i<@plain; $i++) {
                   14522:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14523:                 }
                   14524:             }
1.448     albertel 14525: 	}
1.135     www      14526:     }
1.448     albertel 14527:     close($config);
1.135     www      14528: }
                   14529: 
                   14530: # ---------------------------------------------------------- Read package table
                   14531: {
1.1172.2.96  raeburn  14532:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14533: 
                   14534:     while (my $configline=<$config>) {
1.483     albertel 14535: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14536: 	chomp($configline);
                   14537: 	my ($short,$plain)=split(/:/,$configline);
                   14538: 	my ($pack,$name)=split(/\&/,$short);
                   14539: 	if ($plain ne '') {
                   14540: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14541: 	    $packagetab{$short}=$plain; 
                   14542: 	}
1.11      www      14543:     }
1.448     albertel 14544:     close($config);
1.329     matthew  14545: }
                   14546: 
1.1172.2.27  raeburn  14547: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14548: 
1.1172.2.27  raeburn  14549: &load_loncaparevs();
                   14550: 
                   14551: # ------------------------------------------------------- Read serverhostID table
                   14552: 
                   14553: &load_serverhomeIDs();
1.1074    raeburn  14554: 
1.1172.2.27  raeburn  14555: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14556: {
                   14557:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14558:     if (-e $file) {
                   14559:         my $parser = HTML::LCParser->new($file);
                   14560:         while (my $token = $parser->get_token()) {
                   14561:             if ($token->[0] eq 'S') {
                   14562:                 my $item = $token->[1];
                   14563:                 my $name = $token->[2]{'name'};
                   14564:                 my $value = $token->[2]{'value'};
                   14565:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14566:                     my $release = $parser->get_text();
                   14567:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14568:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14569:                 }
                   14570:             }
                   14571:         }
                   14572:     }
1.1073    raeburn  14573: }
                   14574: 
1.1138    raeburn  14575: # ---------------------------------------------------------- Read managers table
                   14576: {
                   14577:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14578:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14579:             while (my $configline=<$config>) {
                   14580:                 chomp($configline);
                   14581:                 next if ($configline =~ /^\#/);
                   14582:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14583:                     $managerstab{$configline} = 1;
                   14584:                 }
                   14585:             }
                   14586:             close($config);
                   14587:         }
                   14588:     }
                   14589: }
                   14590: 
1.329     matthew  14591: # ------------- set up temporary directory
                   14592: {
1.1117    foxr     14593:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14594: 
1.11      www      14595: }
                   14596: 
1.1172.2.104  raeburn  14597: # ------------- set default texengine (domain default overrides this)
                   14598: {
                   14599:     $deftex = LONCAPA::texengine();
                   14600: }
                   14601: 
1.1172.2.114  raeburn  14602: # ------------- set default minimum length for passwords for internal auth users
                   14603: {
                   14604:     $passwdmin = LONCAPA::passwd_min();
                   14605: }
                   14606: 
1.794     albertel 14607: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14608: 				'compress_threshold'=> 20_000,
                   14609:  			        });
1.185     www      14610: 
1.281     www      14611: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14612: $dumpcount=0;
1.958     www      14613: $locknum=0;
1.22      www      14614: 
1.163     harris41 14615: &logtouch();
1.672     albertel 14616: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14617: $readit=1;
1.564     albertel 14618:     {
                   14619: 	use integer;
                   14620: 	my $test=(2**32)+1;
1.568     albertel 14621: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14622: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14623:     }
1.195     www      14624: }
1.1       albertel 14625: }
1.179     www      14626: 
1.1       albertel 14627: 1;
1.191     harris41 14628: __END__
                   14629: 
1.243     albertel 14630: =pod
                   14631: 
1.191     harris41 14632: =head1 NAME
                   14633: 
1.243     albertel 14634: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14635: 
                   14636: =head1 SYNOPSIS
                   14637: 
1.243     albertel 14638: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14639: 
                   14640:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14641: 
1.243     albertel 14642: Common parameters:
                   14643: 
                   14644: =over 4
                   14645: 
                   14646: =item *
                   14647: 
                   14648: $uname : an internal username (if $cname expecting a course Id specifically)
                   14649: 
                   14650: =item *
                   14651: 
                   14652: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14653: 
                   14654: =item *
                   14655: 
                   14656: $symb : a resource instance identifier
                   14657: 
                   14658: =item *
                   14659: 
                   14660: $namespace : the name of a .db file that contains the data needed or
                   14661: being set.
                   14662: 
                   14663: =back
                   14664: 
1.394     bowersj2 14665: =head1 OVERVIEW
1.191     harris41 14666: 
1.394     bowersj2 14667: lonnet provides subroutines which interact with the
                   14668: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14669: about classes, users, and resources.
1.243     albertel 14670: 
                   14671: For many of these objects you can also use this to store data about
                   14672: them or modify them in various ways.
1.191     harris41 14673: 
1.394     bowersj2 14674: =head2 Symbs
1.191     harris41 14675: 
1.394     bowersj2 14676: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14677: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14678: map, the resource number of the resource in the map, and the URL of
                   14679: the resource itself. The latter is somewhat redundant, but might help
                   14680: if maps change.
                   14681: 
                   14682: An example is
                   14683: 
                   14684:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14685: 
                   14686: The respective map entry is
                   14687: 
                   14688:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14689:   title="Problem 2">
                   14690:  </resource>
                   14691: 
                   14692: Symbs are used by the random number generator, as well as to store and
                   14693: restore data specific to a certain instance of for example a problem.
                   14694: 
                   14695: =head2 Storing And Retrieving Data
                   14696: 
                   14697: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14698: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14699: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14700: is is the non-critical message twin of cstore. These functions are for
                   14701: handlers to store a perl hash to a user's permanent data space in an
                   14702: easy manner, and to retrieve it again on another call. It is expected
                   14703: that a handler would use this once at the beginning to retrieve data,
                   14704: and then again once at the end to send only the new data back.
                   14705: 
                   14706: The data is stored in the user's data directory on the user's
                   14707: homeserver under the ID of the course.
                   14708: 
                   14709: The hash that is returned by restore will have all of the previous
                   14710: value for all of the elements of the hash.
                   14711: 
                   14712: Example:
                   14713: 
                   14714:  #creating a hash
                   14715:  my %hash;
                   14716:  $hash{'foo'}='bar';
                   14717: 
                   14718:  #storing it
                   14719:  &Apache::lonnet::cstore(\%hash);
                   14720: 
                   14721:  #changing a value
                   14722:  $hash{'foo'}='notbar';
                   14723: 
                   14724:  #adding a new value
                   14725:  $hash{'bar'}='foo';
                   14726:  &Apache::lonnet::cstore(\%hash);
                   14727: 
                   14728:  #retrieving the hash
                   14729:  my %history=&Apache::lonnet::restore();
                   14730: 
                   14731:  #print the hash
                   14732:  foreach my $key (sort(keys(%history))) {
                   14733:    print("\%history{$key} = $history{$key}");
                   14734:  }
                   14735: 
                   14736: Will print out:
1.191     harris41 14737: 
1.394     bowersj2 14738:  %history{1:foo} = bar
                   14739:  %history{1:keys} = foo:timestamp
                   14740:  %history{1:timestamp} = 990455579
                   14741:  %history{2:bar} = foo
                   14742:  %history{2:foo} = notbar
                   14743:  %history{2:keys} = foo:bar:timestamp
                   14744:  %history{2:timestamp} = 990455580
                   14745:  %history{bar} = foo
                   14746:  %history{foo} = notbar
                   14747:  %history{timestamp} = 990455580
                   14748:  %history{version} = 2
                   14749: 
                   14750: Note that the special hash entries C<keys>, C<version> and
                   14751: C<timestamp> were added to the hash. C<version> will be equal to the
                   14752: total number of versions of the data that have been stored. The
                   14753: C<timestamp> attribute will be the UNIX time the hash was
                   14754: stored. C<keys> is available in every historical section to list which
                   14755: keys were added or changed at a specific historical revision of a
                   14756: hash.
                   14757: 
                   14758: B<Warning>: do not store the hash that restore returns directly. This
                   14759: will cause a mess since it will restore the historical keys as if the
                   14760: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14761: 
1.394     bowersj2 14762: Calling convention:
1.191     harris41 14763: 
1.1172.2.27  raeburn  14764:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14765:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14766: 
1.394     bowersj2 14767: For more detailed information, see lonnet specific documentation.
1.191     harris41 14768: 
1.394     bowersj2 14769: =head1 RETURN MESSAGES
1.191     harris41 14770: 
1.394     bowersj2 14771: =over 4
1.191     harris41 14772: 
1.394     bowersj2 14773: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14774: 
1.394     bowersj2 14775: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14776: when the connection is brought back up
1.191     harris41 14777: 
1.394     bowersj2 14778: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14779: for later delivery
1.191     harris41 14780: 
1.967     bisitz   14781: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14782: 
1.394     bowersj2 14783: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14784: that was requested
1.191     harris41 14785: 
1.243     albertel 14786: =back
1.191     harris41 14787: 
1.243     albertel 14788: =head1 PUBLIC SUBROUTINES
1.191     harris41 14789: 
1.243     albertel 14790: =head2 Session Environment Functions
1.191     harris41 14791: 
1.243     albertel 14792: =over 4
1.191     harris41 14793: 
1.394     bowersj2 14794: =item * 
                   14795: X<appenv()>
1.949     raeburn  14796: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14797: the user envirnoment file, and will be restored for each access this
1.620     albertel 14798: user makes during this session, also modifies the %env for the current
1.949     raeburn  14799: process. Optional rolesarrayref - if defined contains a reference to an array
                   14800: of roles which are exempt from the restriction on modifying user.role entries 
                   14801: in the user's environment.db and in %env.    
1.191     harris41 14802: 
                   14803: =item *
1.394     bowersj2 14804: X<delenv()>
1.987     raeburn  14805: B<delenv($delthis,$regexp)>: removes all items from the session
                   14806: environment file that begin with $delthis. If the 
                   14807: optional second arg - $regexp - is true, $delthis is treated as a 
                   14808: regular expression, otherwise \Q$delthis\E is used. 
                   14809: The values are also deleted from the current processes %env.
1.191     harris41 14810: 
1.795     albertel 14811: =item * get_env_multiple($name) 
                   14812: 
                   14813: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14814: values may be defined and end up as an array ref.
                   14815: 
                   14816: returns an array of values
                   14817: 
1.243     albertel 14818: =back
                   14819: 
                   14820: =head2 User Information
1.191     harris41 14821: 
1.243     albertel 14822: =over 4
1.191     harris41 14823: 
                   14824: =item *
1.394     bowersj2 14825: X<queryauthenticate()>
                   14826: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14827: authentication scheme
                   14828: 
                   14829: =item *
1.394     bowersj2 14830: X<authenticate()>
1.1073    raeburn  14831: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14832: authenticate user from domain's lib servers (first use the current
                   14833: one). C<$upass> should be the users password.
1.1073    raeburn  14834: $checkdefauth is optional (value is 1 if a check should be made to
                   14835:    authenticate user using default authentication method, and allow
                   14836:    account creation if username does not have account in the domain).
                   14837: $clientcancheckhost is optional (value is 1 if checking whether the
                   14838:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14839: 
                   14840: =item *
1.394     bowersj2 14841: X<homeserver()>
                   14842: B<homeserver($uname,$udom)>: find the server which has
                   14843: the user's directory and files (there must be only one), this caches
                   14844: the answer, and also caches if there is a borken connection.
1.191     harris41 14845: 
                   14846: =item *
1.394     bowersj2 14847: X<idget()>
                   14848: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14849: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14850: username, and only 1 username per ID in a specific domain) (returns
                   14851: hash: id=>name,id=>name)
1.191     harris41 14852: 
                   14853: =item *
1.394     bowersj2 14854: X<idrget()>
                   14855: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14856: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14857: 
                   14858: =item *
1.394     bowersj2 14859: X<idput()>
                   14860: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14861: 
                   14862: =item *
1.394     bowersj2 14863: X<rolesinit()>
1.1169    droeschl 14864: B<rolesinit($udom,$username)>: get user privileges.
                   14865: returns user role, first access and timer interval hashes
1.243     albertel 14866: 
                   14867: =item *
1.1171    droeschl 14868: X<privileged()>
                   14869: B<privileged($username,$domain)>: returns a true if user has a
                   14870: privileged and active role (i.e. su or dc), false otherwise.
                   14871: 
                   14872: =item *
1.551     albertel 14873: X<getsection()>
                   14874: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14875: course $cname, return section name/number or '' for "not in course"
                   14876: and '-1' for "no section"
                   14877: 
                   14878: =item *
1.394     bowersj2 14879: X<userenvironment()>
                   14880: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14881: passed in @what from the requested user's environment, returns a hash
                   14882: 
1.858     raeburn  14883: =item * 
                   14884: X<userlog_query()>
1.859     albertel 14885: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14886: activity.log file. %filters defines filters applied when parsing the
                   14887: log file. These can be start or end timestamps, or the type of action
                   14888: - log to look for Login or Logout events, check for Checkin or
                   14889: Checkout, role for role selection. The response is in the form
                   14890: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14891: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14892: 
1.243     albertel 14893: =back
                   14894: 
                   14895: =head2 User Roles
                   14896: 
                   14897: =over 4
                   14898: 
                   14899: =item *
                   14900: 
1.1172.2.65  raeburn  14901: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14902: returns codes for allowed actions.
                   14903: 
                   14904: The first argument is required, all others are optional.
                   14905: 
                   14906: $priv is the privilege being checked.
                   14907: $uri contains additional information about what is being checked for access (e.g.,
                   14908: URL, course ID etc.).
                   14909: $symb is the unique resource instance identifier in a course; if needed,
                   14910: but not provided, it will be retrieved via a call to &symbread().
                   14911: $role is the role for which a priv is being checked (only used if priv is evb).
                   14912: $clientip is the user's IP address (only used when checking for access to portfolio
                   14913: files).
                   14914: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14915: prevents recursive calls to &allowed.
                   14916: 
1.243     albertel 14917:  F: full access
                   14918:  U,I,K: authentication modes (cxx only)
                   14919:  '': forbidden
                   14920:  1: user needs to choose course
                   14921:  2: browse allowed
1.766     albertel 14922:  A: passphrase authentication needed
1.1172.2.65  raeburn  14923:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14924: 
                   14925: =item *
                   14926: 
1.1172.2.13  raeburn  14927: constructaccess($url,$setpriv) : check for access to construction space URL
                   14928: 
                   14929: See if the owner domain and name in the URL match those in the
                   14930: expected environment.  If so, return three element list
                   14931: ($ownername,$ownerdomain,$ownerhome).
                   14932: 
                   14933: Otherwise return the null string.
                   14934: 
                   14935: If second argument 'setpriv' is true, it assigns the privileges,
                   14936: and returns the same three element list, unless the owner has
                   14937: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14938: in which case the null string is returned.
                   14939: 
                   14940: =item *
                   14941: 
1.1172.2.84  raeburn  14942: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14943: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14944: for system, domain, and course level. $uname and $udom are optional (current
                   14945: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14946: 
                   14947: =item *
                   14948: 
1.988     raeburn  14949: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14950: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14951: $type is Course (default) or Community.
1.988     raeburn  14952: If $forcedefault evaluates to true, text returned will be default 
                   14953: text for $type. Otherwise, if this is a course, the text returned 
                   14954: will be a custom name for the role (if defined in the course's 
                   14955: environment).  If no custom name is defined the default is returned.
                   14956:    
1.832     raeburn  14957: =item *
                   14958: 
1.1172.2.23  raeburn  14959: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14960: All arguments are optional. Returns a hash of a roles, either for
                   14961: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14962: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14963: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14964: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14965: For each key, value is set to colon-separated start and end times for
                   14966: the role.  If no username and domain are specified, will default to
1.934     raeburn  14967: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14968: of role statuses (active, future or previous), roles 
                   14969: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14970: to restrict the list of roles reported. If no array ref is 
                   14971: provided for types, will default to return only active roles.
1.834     albertel 14972: 
1.1172.2.13  raeburn  14973: =item *
                   14974: 
                   14975: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14976: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14977: 
                   14978: Additional optional arguments are: $type (if role checking is to be restricted
                   14979: to certain user status types -- previous (expired roles), active (currently
                   14980: available roles) or future (roles available in the future), and
                   14981: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14982: have active Domain Coordinator role in course's domain or in additional
                   14983: domains (specified in 'Domains to check for privileged users' in course
                   14984: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14985: 
                   14986: =item *
                   14987: 
                   14988: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14989: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14990: $possdomains and $possroles are optional array refs -- to domains to check and
                   14991: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14992: users' roles.db to check for a dc or su role in any domain. This can be
                   14993: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14994: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14995: this then allows &privileged_by_domain() to be used, which caches the identity
                   14996: of privileged users, eliminating the need for repeated calls to &dump().
                   14997: 
                   14998: =item *
                   14999: 
                   15000: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15001: where the outer hash keys are domains specified in the $possdomains array ref,
                   15002: next inner hash keys are privileged roles specified in the $roles array ref,
                   15003: and the innermost hash contains key = value pairs for username:domain = end:start
                   15004: for active or future "privileged" users with that role in that domain. To avoid
                   15005: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15006: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15007: 
1.243     albertel 15008: =back
                   15009: 
                   15010: =head2 User Modification
                   15011: 
                   15012: =over 4
                   15013: 
                   15014: =item *
                   15015: 
1.957     raeburn  15016: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15017: user for the level given by URL.  Optional start and end dates (leave empty
                   15018: string or zero for "no date")
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.243     albertel 15022: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15023: change a users, password, possible return values are: ok,
                   15024: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15025: refused
1.191     harris41 15026: 
                   15027: =item *
                   15028: 
1.243     albertel 15029: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15030: 
                   15031: =item *
                   15032: 
1.1058    raeburn  15033: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15034:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15035: 
                   15036: will update user information (firstname,middlename,lastname,generation,
                   15037: permanentemail), and if forceid is true, student/employee ID also.
                   15038: A user's institutional affiliation(s) can also be updated.
                   15039: User information fields will not be overwritten with empty entries 
                   15040: unless the field is included in the $candelete array reference.
                   15041: This array is included when a single user is modified via "Manage Users",
                   15042: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15043: 
                   15044: =item *
                   15045: 
1.286     matthew  15046: modifystudent
                   15047: 
1.957     raeburn  15048: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15049: The course id is resolved based on the current user's environment.  
                   15050: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15051: associated with a course.
                   15052: 
1.297     matthew  15053: This call is essentially a wrapper for lonnet::modifyuser and
                   15054: lonnet::modify_student_enrollment
1.286     matthew  15055: 
                   15056: Inputs: 
                   15057: 
                   15058: =over 4
                   15059: 
1.957     raeburn  15060: =item B<$udom> Student's loncapa domain
1.286     matthew  15061: 
1.957     raeburn  15062: =item B<$uname> Student's loncapa login name
1.286     matthew  15063: 
1.964     bisitz   15064: =item B<$uid> Student/Employee ID
1.286     matthew  15065: 
1.957     raeburn  15066: =item B<$umode> Student's authentication mode
1.286     matthew  15067: 
1.957     raeburn  15068: =item B<$upass> Student's password
1.286     matthew  15069: 
1.957     raeburn  15070: =item B<$first> Student's first name
1.286     matthew  15071: 
1.957     raeburn  15072: =item B<$middle> Student's middle name
1.286     matthew  15073: 
1.957     raeburn  15074: =item B<$last> Student's last name
1.286     matthew  15075: 
1.957     raeburn  15076: =item B<$gene> Student's generation
1.286     matthew  15077: 
1.957     raeburn  15078: =item B<$usec> Student's section in course
1.286     matthew  15079: 
                   15080: =item B<$end> Unix time of the roles expiration
                   15081: 
                   15082: =item B<$start> Unix time of the roles start date
                   15083: 
                   15084: =item B<$forceid> If defined, allow $uid to be changed
                   15085: 
                   15086: =item B<$desiredhome> server to use as home server for student
                   15087: 
1.957     raeburn  15088: =item B<$email> Student's permanent e-mail address
                   15089: 
                   15090: =item B<$type> Type of enrollment (auto or manual)
                   15091: 
1.963     raeburn  15092: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15093: 
                   15094: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15095: 
1.963     raeburn  15096: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15097: 
1.963     raeburn  15098: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15099: 
1.1172.2.19  raeburn  15100: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15101: 
                   15102: =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  15103: 
1.286     matthew  15104: =back
1.297     matthew  15105: 
                   15106: =item *
                   15107: 
                   15108: modify_student_enrollment
                   15109: 
1.1172.2.31  raeburn  15110: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15111: 'role.request.course' must be defined for this function to proceed.
                   15112: 
                   15113: Inputs:
                   15114: 
                   15115: =over 4
                   15116: 
1.1172.2.31  raeburn  15117: =item $udom, student's domain
1.297     matthew  15118: 
1.1172.2.31  raeburn  15119: =item $uname, student's name
1.297     matthew  15120: 
1.1172.2.31  raeburn  15121: =item $uid, student's user id
1.297     matthew  15122: 
1.1172.2.31  raeburn  15123: =item $first, student's first name
1.297     matthew  15124: 
                   15125: =item $middle
                   15126: 
                   15127: =item $last
                   15128: 
                   15129: =item $gene
                   15130: 
                   15131: =item $usec
                   15132: 
                   15133: =item $end
                   15134: 
                   15135: =item $start
                   15136: 
1.957     raeburn  15137: =item $type
                   15138: 
                   15139: =item $locktype
                   15140: 
                   15141: =item $cid
                   15142: 
                   15143: =item $selfenroll
                   15144: 
                   15145: =item $context
                   15146: 
1.1172.2.19  raeburn  15147: =item $credits, number of credits student will earn from this class
                   15148: 
1.1172.2.76  raeburn  15149: =item $instsec, institutional course section code for student
                   15150: 
1.297     matthew  15151: =back
                   15152: 
1.191     harris41 15153: 
                   15154: =item *
                   15155: 
1.243     albertel 15156: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15157: custom role; give a custom role to a user for the level given by URL.  Specify
                   15158: name and domain of role author, and role name
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.243     albertel 15162: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15163: 
                   15164: =item *
                   15165: 
1.243     albertel 15166: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15167: 
                   15168: =back
                   15169: 
                   15170: =head2 Course Infomation
                   15171: 
                   15172: =over 4
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.1118    foxr     15176: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15177: specified course id, including all environment settings for the
                   15178: course, the description of the course will be in the hash under the
                   15179: key 'description'
1.191     harris41 15180: 
1.1118    foxr     15181: $options is an optional parameter that if supplied is a hash reference that controls
                   15182: what how this function works.  It has the following key/values:
                   15183: 
                   15184: =over 4
                   15185: 
                   15186: =item freshen_cache
                   15187: 
                   15188: If defined, and the environment cache for the course is valid, it is 
                   15189: returned in the returned hash.
                   15190: 
                   15191: =item one_time
                   15192: 
                   15193: If defined, the last cache time is set to _now_
                   15194: 
                   15195: =item user
                   15196: 
                   15197: If defined, the supplied username is used instead of the current user.
                   15198: 
                   15199: 
                   15200: =back
                   15201: 
1.191     harris41 15202: =item *
                   15203: 
1.624     albertel 15204: resdata($name,$domain,$type,@which) : request for current parameter
                   15205: setting for a specific $type, where $type is either 'course' or 'user',
                   15206: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15207: answers for 10 minutes.
1.243     albertel 15208: 
1.877     foxr     15209: =item *
                   15210: 
                   15211: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15212: data base, returning a hash that is keyed by the resource name and has
                   15213: values that are the resource value.  I believe that the timestamps and
                   15214: versions are also returned.
                   15215: 
1.1172.2.31  raeburn  15216: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15217: supplemental content area. This routine caches the number of files for
                   15218: 10 minutes.
                   15219: 
1.243     albertel 15220: =back
                   15221: 
                   15222: =head2 Course Modification
                   15223: 
                   15224: =over 4
1.191     harris41 15225: 
                   15226: =item *
                   15227: 
1.243     albertel 15228: writecoursepref($courseid,%prefs) : write preferences (environment
                   15229: database) for a course
1.191     harris41 15230: 
                   15231: =item *
                   15232: 
1.1011    raeburn  15233: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15234: 
                   15235: =item *
                   15236: 
1.1038    raeburn  15237: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15238: 
1.1167    droeschl 15239: =item *
                   15240: 
                   15241: is_course($courseid), is_course($cdom, $cnum)
                   15242: 
                   15243: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15244: two component version $cdom, $cnum. It checks if the specified course exists.
                   15245: 
                   15246: Returns:
                   15247:     undef if the course doesn't exist, otherwise
                   15248:     in scalar context the combined courseid.
                   15249:     in list context the two components of the course identifier, domain and 
                   15250:     courseid.    
                   15251: 
1.243     albertel 15252: =back
                   15253: 
1.1172.2.109  raeburn  15254: =head2 Bubblesheet Configuration
                   15255: 
                   15256: =over 4
                   15257: 
                   15258: =item *
                   15259: 
                   15260: get_scantron_config($which)
                   15261: 
                   15262: $which - the name of the configuration to parse from the file.
                   15263: 
                   15264: Parses and returns the bubblesheet configuration line selected as a
                   15265: hash of configuration file fields.
                   15266: 
                   15267: 
                   15268: Returns:
                   15269:     If the named configuration is not in the file, an empty
                   15270:     hash is returned.
                   15271: 
                   15272:     a hash with the fields
                   15273:       name         - internal name for the this configuration setup
                   15274:       description  - text to display to operator that describes this config
                   15275:       CODElocation - if 0 or the string 'none'
                   15276:                           - no CODE exists for this config
                   15277:                      if -1 || the string 'letter'
                   15278:                           - a CODE exists for this config and is
                   15279:                             a string of letters
                   15280:                      Unsupported value (but planned for future support)
                   15281:                           if a positive integer
                   15282:                                - The CODE exists as the first n items from
                   15283:                                  the question section of the form
                   15284:                           if the string 'number'
                   15285:                                - The CODE exists for this config and is
                   15286:                                  a string of numbers
                   15287:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15288:                      the CODE starts
                   15289:       CODElength  - length of the CODE
                   15290:       IDstart     - column where the student/employee ID starts
                   15291:       IDlength    - length of the student/employee ID info
                   15292:       Qstart      - column where the information from the bubbled
                   15293:                     'questions' start
                   15294:       Qlength     - number of columns comprising a single bubble line from
                   15295:                     the sheet. (usually either 1 or 10)
                   15296:       Qon         - either a single character representing the character used
                   15297:                     to signal a bubble was chosen in the positional setup, or
                   15298:                     the string 'letter' if the letter of the chosen bubble is
                   15299:                     in the final, or 'number' if a number representing the
                   15300:                     chosen bubble is in the file (1->A 0->J)
                   15301:       Qoff        - the character used to represent that a bubble was
                   15302:                     left blank
                   15303:       PaperID     - if the scanning process generates a unique number for each
                   15304:                     sheet scanned the column that this ID number starts in
                   15305:       PaperIDlength - number of columns that comprise the unique ID number
                   15306:                       for the sheet of paper
                   15307:       FirstName   - column that the first name starts in
                   15308:       FirstNameLength - number of columns that the first name spans
                   15309:       LastName    - column that the last name starts in
                   15310:       LastNameLength - number of columns that the last name spans
                   15311:       BubblesPerRow - number of bubbles available in each row used to
                   15312:                       bubble an answer. (If not specified, 10 assumed).
                   15313: 
                   15314: 
                   15315: =item *
                   15316: 
                   15317: get_scantronformat_file($cdom)
                   15318: 
                   15319: $cdom - the course's domain (optional); if not supplied, uses
                   15320: domain for current $env{'request.course.id'}.
                   15321: 
                   15322: Returns an array containing lines from the scantron format file for
                   15323: the domain of the course.
                   15324: 
                   15325: If a url for a custom.tab file is listed in domain's configuration.db,
                   15326: lines are from this file.
                   15327: 
                   15328: Otherwise, if a default.tab has been published in RES space by the
                   15329: domainconfig user, lines are from this file.
                   15330: 
                   15331: Otherwise, fall back to getting lines from the legacy file on the
                   15332: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15333: 
                   15334: =back
                   15335: 
1.243     albertel 15336: =head2 Resource Subroutines
                   15337: 
                   15338: =over 4
1.191     harris41 15339: 
                   15340: =item *
                   15341: 
1.243     albertel 15342: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15343: 
                   15344: =item *
                   15345: 
1.243     albertel 15346: repcopy($filename) : subscribes to the requested file, and attempts to
                   15347: replicate from the owning library server, Might return
1.607     raeburn  15348: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15349: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15350: resource. Expects the local filesystem pathname
                   15351: (/home/httpd/html/res/....)
                   15352: 
                   15353: =back
                   15354: 
                   15355: =head2 Resource Information
                   15356: 
                   15357: =over 4
1.191     harris41 15358: 
                   15359: =item *
                   15360: 
1.1172.2.28  raeburn  15361: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15362: and returns the value of a variety of different possible values,
                   15363: $varname should be a request string, and the other parameters can be
                   15364: used to specify who and what one is asking about. Ordinarily, $cid 
                   15365: does not need to be specified, as it is retrived from 
                   15366: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15367: within lonuserstate::loadmap() when initializing a course, before
                   15368: $env{'request.course.id'} has been set, so it needs to be provided
                   15369: in that one case.
1.243     albertel 15370: 
                   15371: Possible values for $varname are environment.lastname (or other item
                   15372: from the envirnment hash), user.name (or someother aspect about the
                   15373: user), resource.0.maxtries (or some other part and parameter of a
                   15374: resource)
1.204     albertel 15375: 
                   15376: =item *
                   15377: 
1.243     albertel 15378: directcondval($number) : get current value of a condition; reads from a state
                   15379: string
1.204     albertel 15380: 
                   15381: =item *
                   15382: 
1.243     albertel 15383: condval($condidx) : value of condition index based on state
1.204     albertel 15384: 
                   15385: =item *
                   15386: 
1.243     albertel 15387: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15388: resource's metadata, $what should be either a specific key, or either
                   15389: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15390: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15391: 
                   15392: this function automatically caches all requests
1.191     harris41 15393: 
                   15394: =item *
                   15395: 
1.243     albertel 15396: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15397: network of library servers; returns file handle of where SQL and regex results
                   15398: will be stored for query
1.191     harris41 15399: 
                   15400: =item *
                   15401: 
1.1172.2.66  raeburn  15402: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15403: return symbolic list entry (all arguments optional).
                   15404: 
                   15405: Args: filename is the filename (including path) for the file for which a symb
                   15406: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15407: to check access status if more than one resource was found in the bighash
                   15408: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15409: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15410: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15411: cause possible symbs to be checked to determine if they are subject to content
                   15412: blocking, if so they will not be included as possible symbs; possibles is a
                   15413: ref to a hash, which, as a side effect, will be populated with all possible
                   15414: symbs (content blocking not tested).
                   15415: 
1.243     albertel 15416: returns the data handle
1.191     harris41 15417: 
                   15418: =item *
                   15419: 
1.1172.2.17  raeburn  15420: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15421: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15422: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15423: on failure, user must be in a course, as it assumes the existence of
                   15424: the course initial hash, and uses $env('request.course.id'}.  The third
                   15425: arg is an optional reference to a scalar.  If this arg is passed in the
                   15426: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15427: encrypted; otherwise it will be null.
1.243     albertel 15428: 
1.191     harris41 15429: =item *
                   15430: 
1.243     albertel 15431: symbclean($symb) : removes versions numbers from a symb, returns the
                   15432: cleaned symb
1.191     harris41 15433: 
                   15434: =item *
                   15435: 
1.243     albertel 15436: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15437: course map, user must be in a course for it to work.
1.191     harris41 15438: 
                   15439: =item *
                   15440: 
1.243     albertel 15441: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15442: 
                   15443: =item *
                   15444: 
1.243     albertel 15445: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15446: a random seed, all arguments are optional, if they aren't sent it uses the
                   15447: environment to derive them. Note: if symb isn't sent and it can't get one
                   15448: from &symbread it will use the current time as its return value
1.191     harris41 15449: 
                   15450: =item *
                   15451: 
1.243     albertel 15452: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15453: unfakeable, receipt
1.191     harris41 15454: 
                   15455: =item *
                   15456: 
1.620     albertel 15457: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15458: 
                   15459: =item *
                   15460: 
1.243     albertel 15461: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15462: 
                   15463: =item *
                   15464: 
1.243     albertel 15465: 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 15466: 
                   15467: =item *
                   15468: 
1.243     albertel 15469: 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 15470: 
                   15471: =item *
                   15472: 
1.243     albertel 15473: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15474: 
                   15475: =item *
                   15476: 
1.243     albertel 15477: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15478: forcing spreadsheet to reevaluate the resource scores next time.
                   15479: 
1.1172.2.13  raeburn  15480: =item *
                   15481: 
                   15482: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15483: when viewing in course context.
                   15484: 
                   15485:  input: six args -- filename (decluttered), course number, course domain,
                   15486:                     url, symb (if registered) and group (if this is a
                   15487:                     group item -- e.g., bulletin board, group page etc.).
                   15488: 
                   15489:  output: array of five scalars --
                   15490:          $cfile -- url for file editing if editable on current server
                   15491:          $home -- homeserver of resource (i.e., for author if published,
                   15492:                                           or course if uploaded.).
                   15493:          $switchserver --  1 if server switch will be needed.
                   15494:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15495:          $forceview -- 1 if icon/link should be to go to view mode
                   15496: 
                   15497: =item *
                   15498: 
                   15499: is_course_upload($file,$cnum,$cdom)
                   15500: 
                   15501: Used in course context to determine if current file was uploaded to
                   15502: the course (i.e., would be found in /userfiles/docs on the course's
                   15503: homeserver.
                   15504: 
                   15505:   input: 3 args -- filename (decluttered), course number and course domain.
                   15506:   output: boolean -- 1 if file was uploaded.
                   15507: 
1.243     albertel 15508: =back
                   15509: 
                   15510: =head2 Storing/Retreiving Data
                   15511: 
                   15512: =over 4
1.191     harris41 15513: 
                   15514: =item *
                   15515: 
1.1172.2.64  raeburn  15516: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15517: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15518: the remaining args aren't required and if they aren't passed or are '' they will
                   15519: be derived from the env (with the exception of $laststore, which is an
                   15520: optional arg used when a user's submission is stored in grading).
                   15521: $laststore is $version=$timestamp, where $version is the most recent version
                   15522: number retrieved for the corresponding $symb in the $namespace db file, and
                   15523: $timestamp is the timestamp for that transaction (UNIX time).
                   15524: $laststore is currently only passed when cstore() is called by
                   15525: structuretags::finalize_storage().
1.191     harris41 15526: 
                   15527: =item *
                   15528: 
1.1172.2.64  raeburn  15529: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15530: but uses critical subroutine
1.191     harris41 15531: 
                   15532: =item *
                   15533: 
1.243     albertel 15534: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15535: all args are optional
1.191     harris41 15536: 
                   15537: =item *
                   15538: 
1.717     albertel 15539: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15540: dumps the complete (or key matching regexp) namespace into a hash
                   15541: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15542: normally &store()ed into
                   15543: 
                   15544: $range should be either an integer '100' (give me the first 100
                   15545:                                            matching records)
                   15546:               or be  two integers sperated by a - with no spaces
                   15547:                  '30-50' (give me the 30th through the 50th matching
                   15548:                           records)
                   15549: 
                   15550: 
                   15551: =item *
                   15552: 
1.1172.2.59  raeburn  15553: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15554: replaces a &store() version of data with a replacement set of data
                   15555: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15556: reference. If $tolog is true, the transaction is logged in the courselog
                   15557: with an action=PUTSTORE.
1.717     albertel 15558: 
                   15559: =item *
                   15560: 
1.243     albertel 15561: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15562: works very similar to store/cstore, but all data is stored in a
                   15563: temporary location and can be reset using tmpreset, $storehash should
                   15564: be a hash reference, returns nothing on success
1.191     harris41 15565: 
                   15566: =item *
                   15567: 
1.243     albertel 15568: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15569: similar to restore, but all data is stored in a temporary location and
                   15570: can be reset using tmpreset. Returns a hash of values on success,
                   15571: error string otherwise.
1.191     harris41 15572: 
                   15573: =item *
                   15574: 
1.243     albertel 15575: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15576: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15577: 
                   15578: =item *
                   15579: 
1.243     albertel 15580: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15581: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15582: 
                   15583: =item *
                   15584: 
1.243     albertel 15585: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15586: namesp ($udom and $uname are optional)
1.191     harris41 15587: 
                   15588: =item *
                   15589: 
1.702     albertel 15590: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15591: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15592: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15593: 
1.702     albertel 15594: $range should be either an integer '100' (give me the first 100
                   15595:                                            matching records)
                   15596:               or be  two integers sperated by a - with no spaces
                   15597:                  '30-50' (give me the 30th through the 50th matching
                   15598:                           records)
1.449     matthew  15599: =item *
                   15600: 
                   15601: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15602: $store can be a scalar, an array reference, or if the amount to be 
                   15603: incremented is > 1, a hash reference.
                   15604: 
                   15605: ($udom and $uname are optional)
1.191     harris41 15606: 
                   15607: =item *
                   15608: 
1.243     albertel 15609: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15610: ($udom and $uname are optional)
1.191     harris41 15611: 
                   15612: =item *
                   15613: 
1.243     albertel 15614: cput($namespace,$storehash,$udom,$uname) : critical put
                   15615: ($udom and $uname are optional)
1.191     harris41 15616: 
                   15617: =item *
                   15618: 
1.748     albertel 15619: newput($namespace,$storehash,$udom,$uname) :
                   15620: 
                   15621: Attempts to store the items in the $storehash, but only if they don't
                   15622: currently exist, if this succeeds you can be certain that you have 
                   15623: successfully created a new key value pair in the $namespace db.
                   15624: 
                   15625: 
                   15626: Args:
                   15627:  $namespace: name of database to store values to
                   15628:  $storehash: hashref to store to the db
                   15629:  $udom: (optional) domain of user containing the db
                   15630:  $uname: (optional) name of user caontaining the db
                   15631: 
                   15632: Returns:
                   15633:  'ok' -> succeeded in storing all keys of $storehash
                   15634:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15635:                         least <key> already existed in the db (other
                   15636:                         requested keys may also already exist)
1.967     bisitz   15637:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15638:  'con_lost' -> unable to contact request server
                   15639:  'refused' -> action was not allowed by remote machine
                   15640: 
                   15641: 
                   15642: =item *
                   15643: 
1.243     albertel 15644: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15645: reference filled in from namesp (encrypts the return communication)
                   15646: ($udom and $uname are optional)
1.191     harris41 15647: 
                   15648: =item *
                   15649: 
1.243     albertel 15650: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15651: critical subroutine
                   15652: 
1.806     raeburn  15653: =item *
                   15654: 
1.860     raeburn  15655: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15656: array reference filled in from namespace found in domain level on either
                   15657: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15658: 
                   15659: =item *
                   15660: 
1.860     raeburn  15661: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15662: domain level either on specified domain server ($uhome) or primary domain 
                   15663: server ($udom and $uhome are optional)
1.806     raeburn  15664: 
1.943     raeburn  15665: =item * 
                   15666: 
1.1172.2.35  raeburn  15667: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15668: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15669: the target domain.
                   15670: 
                   15671: May also include additional key => value pairs for the following groups:
                   15672: 
                   15673: =over
                   15674: 
                   15675: =item
                   15676: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15677: 
                   15678: =over
                   15679: 
                   15680: =item defaultquota, authorquota
                   15681: 
                   15682: =back
                   15683: 
                   15684: =item
                   15685: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15686: portfolio for users).
                   15687: 
                   15688: =over
                   15689: 
                   15690: =item
                   15691: aboutme, blog, webdav, portfolio
                   15692: 
                   15693: =back
                   15694: 
                   15695: =item
                   15696: requestcourses: ability to request courses, and how requests are processed.
                   15697: 
                   15698: =over
                   15699: 
                   15700: =item
1.1172.2.37  raeburn  15701: official, unofficial, community, textbook
1.1172.2.35  raeburn  15702: 
                   15703: =back
                   15704: 
                   15705: =item
                   15706: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15707: 
                   15708: =over
                   15709: 
                   15710: =item
1.1172.2.44  raeburn  15711: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15712: 
                   15713: =back
                   15714: 
                   15715: =item
                   15716: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15717: for course's uploaded content.
                   15718: 
                   15719: =over
                   15720: 
                   15721: =item
1.1172.2.68  raeburn  15722: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15723: communityquota, textbookquota
1.1172.2.35  raeburn  15724: 
                   15725: =back
                   15726: 
                   15727: =item
                   15728: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15729: on your servers.
                   15730: 
                   15731: =over
                   15732: 
                   15733: =item
                   15734: remotesessions, hostedsessions
                   15735: 
                   15736: =back
                   15737: 
                   15738: =back
                   15739: 
                   15740: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15741: utility to create a configuration.db file on a domain's primary library server
                   15742: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15743: -- corresponding values are authentication type (internal, krb4, krb5,
                   15744: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15745: will be available. Values are retrieved from cache (if current), unless the
                   15746: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15747: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15748: 
                   15749: Typical usage:
1.943     raeburn  15750: 
1.1172.2.35  raeburn  15751: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15752: 
1.243     albertel 15753: =back
                   15754: 
                   15755: =head2 Network Status Functions
                   15756: 
                   15757: =over 4
1.191     harris41 15758: 
                   15759: =item *
                   15760: 
1.1137    raeburn  15761: dirlist() : return directory list based on URI (first arg).
                   15762: 
                   15763: Inputs: 1 required, 5 optional.
                   15764: 
                   15765: =over
                   15766: 
                   15767: =item 
                   15768: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15769: 
                   15770: =item
                   15771: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15772: 
                   15773: =item
                   15774: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15775: 
                   15776: =item
                   15777: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15778: 
                   15779: =item
                   15780: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15781: 
                   15782: =item 
                   15783: $alternateRoot - path to prepend in place of path from $uri.
                   15784: 
                   15785: =back
                   15786: 
                   15787: Returns: Array of up to two items.
                   15788: 
                   15789: =over
                   15790: 
                   15791: a reference to an array of files/subdirectories
                   15792: 
                   15793: =over
                   15794: 
                   15795: Each element in the array of files/subdirectories is a & separated list of
                   15796: item name and the result of running stat on the item.  If dirlist was requested
                   15797: for a file instead of a directory, the item name will be ''. For a directory 
                   15798: listing, if the item is a metadata file, the element will end &N&M 
                   15799: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15800: default copyright set (1).  
                   15801: 
                   15802: =back
                   15803: 
                   15804: a scalar containing error condition (if encountered).
                   15805: 
                   15806: =over
                   15807: 
                   15808: =item 
                   15809: no_host (no homeserver identified for $username:$domain).
                   15810: 
                   15811: =item 
                   15812: no_such_host (server contacted for listing not identified as valid host).
                   15813: 
                   15814: =item 
                   15815: con_lost (connection to remote server failed).
                   15816: 
                   15817: =item 
                   15818: refused (invalid $username:$domain received on lond side).
                   15819: 
                   15820: =item 
                   15821: no_such_dir (directory at specified path on lond side does not exist). 
                   15822: 
                   15823: =item 
                   15824: empty (directory at specified path on lond side is empty).
                   15825: 
                   15826: =over
                   15827: 
                   15828: This is currently not encountered because the &ls3, &ls2, 
                   15829: &ls (_handler) routines on the lond side do not filter out
                   15830: . and .. from a directory listing. 
                   15831: 
                   15832: =back
                   15833: 
                   15834: =back
                   15835: 
                   15836: =back
1.191     harris41 15837: 
                   15838: =item *
                   15839: 
1.243     albertel 15840: spareserver() : find server with least workload from spare.tab
                   15841: 
1.986     foxr     15842: 
                   15843: =item *
                   15844: 
                   15845: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15846: if there is no corresponding loncapa host.
                   15847: 
1.243     albertel 15848: =back
                   15849: 
1.986     foxr     15850: 
1.243     albertel 15851: =head2 Apache Request
                   15852: 
                   15853: =over 4
1.191     harris41 15854: 
                   15855: =item *
                   15856: 
1.243     albertel 15857: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15858: localhost, posts hash
                   15859: 
                   15860: =back
                   15861: 
                   15862: =head2 Data to String to Data
                   15863: 
                   15864: =over 4
1.191     harris41 15865: 
                   15866: =item *
                   15867: 
1.243     albertel 15868: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15869: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15870: 
                   15871: =item *
                   15872: 
1.243     albertel 15873: hashref2str($hashref) : convert a hashref into a string complete with
                   15874: escaping and '=' and '&' separators, supports elements that are
                   15875: arrayrefs and hashrefs
1.191     harris41 15876: 
                   15877: =item *
                   15878: 
1.243     albertel 15879: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15880: with escaping and '&' separators, supports elements that are arrayrefs
                   15881: and hashrefs
1.191     harris41 15882: 
                   15883: =item *
                   15884: 
1.243     albertel 15885: str2hash($string) : convert string to hash using unescaping and
                   15886: splitting on '=' and '&', supports elements that are arrayrefs and
                   15887: hashrefs
1.191     harris41 15888: 
                   15889: =item *
                   15890: 
1.243     albertel 15891: str2array($string) : convert string to hash using unescaping and
                   15892: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15893: 
                   15894: =back
                   15895: 
                   15896: =head2 Logging Routines
                   15897: 
                   15898: 
                   15899: These routines allow one to make log messages in the lonnet.log and
                   15900: lonnet.perm logfiles.
1.191     harris41 15901: 
1.1119    foxr     15902: =over 4
                   15903: 
1.191     harris41 15904: =item *
                   15905: 
1.243     albertel 15906: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15907: 
                   15908: =item *
                   15909: 
1.243     albertel 15910: logthis() : append message to the normal lonnet.log file, it gets
                   15911: preiodically rolled over and deleted.
1.191     harris41 15912: 
                   15913: =item *
                   15914: 
1.243     albertel 15915: logperm() : append a permanent message to lonnet.perm.log, this log
                   15916: file never gets deleted by any automated portion of the system, only
                   15917: messages of critical importance should go in here.
                   15918: 
1.1119    foxr     15919: 
1.243     albertel 15920: =back
                   15921: 
                   15922: =head2 General File Helper Routines
                   15923: 
                   15924: =over 4
1.191     harris41 15925: 
                   15926: =item *
                   15927: 
1.481     raeburn  15928: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15929: (a) files in /uploaded
                   15930:   (i) If a local copy of the file exists - 
                   15931:       compares modification date of local copy with last-modified date for 
                   15932:       definitive version stored on home server for course. If local copy is 
                   15933:       stale, requests a new version from the home server and stores it. 
                   15934:       If the original has been removed from the home server, then local copy 
                   15935:       is unlinked.
                   15936:   (ii) If local copy does not exist -
                   15937:       requests the file from the home server and stores it. 
                   15938:   
                   15939:   If $caller is 'uploadrep':  
                   15940:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15941:     for request for files originally uploaded via DOCS. 
                   15942:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15943:   
                   15944:   Otherwise:
                   15945:      This indicates a call from the content generation phase of the request.
                   15946:      -  returns the entire contents of the file or -1.
                   15947:      
                   15948: (b) files in /res
                   15949:    - returns the entire contents of a file or -1; 
                   15950:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15951: 
1.712     albertel 15952: 
                   15953: =item *
                   15954: 
                   15955: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15956:                   reference
                   15957: 
                   15958: returns either a stat() list of data about the file or an empty list
                   15959: if the file doesn't exist or couldn't find out about it (connection
                   15960: problems or user unknown)
                   15961: 
1.191     harris41 15962: =item *
                   15963: 
1.243     albertel 15964: filelocation($dir,$file) : returns file system location of a file
                   15965: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15966: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15967: and a file of ../bob will become /a/bob)
1.191     harris41 15968: 
                   15969: =item *
                   15970: 
                   15971: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15972: filelocation except for hrefs
                   15973: 
                   15974: =item *
                   15975: 
1.1172.2.49  raeburn  15976: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15977: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15978: 
1.243     albertel 15979: =back
                   15980: 
1.608     albertel 15981: =head2 Usererfile file routines (/uploaded*)
                   15982: 
                   15983: =over 4
                   15984: 
                   15985: =item *
                   15986: 
                   15987: userfileupload(): main rotine for putting a file in a user or course's
                   15988:                   filespace, arguments are,
                   15989: 
1.620     albertel 15990:  formname - required - this is the name of the element in $env where the
1.608     albertel 15991:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15992:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15993:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15994:  context - if coursedoc, store the file in the course of the active role
                   15995:              of the current user; 
                   15996:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15997:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15998:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15999:          if undefined, it will be placed in "unknown"
                   16000: 
                   16001:  (This routine calls clean_filename() to remove any dangerous
                   16002:  characters from the filename, and then calls finuserfileupload() to
                   16003:  complete the transaction)
                   16004: 
                   16005:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16006:  and /adm/notfound.html if unsuccessful
                   16007: 
                   16008: =item *
                   16009: 
                   16010: clean_filename(): routine for cleaing a filename up for storage in
                   16011:                  userfile space, argument is:
                   16012: 
                   16013:  filename - proposed filename
                   16014: 
                   16015: returns: the new clean filename
                   16016: 
                   16017: =item *
                   16018: 
1.1090    raeburn  16019: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16020: userspace, probably shouldn't be called directly
                   16021: 
                   16022:   docuname: username or courseid of destination for the file
                   16023:   docudom: domain of user/course of destination for the file
                   16024:   formname: same as for userfileupload()
1.1090    raeburn  16025:   fname: filename (including subdirectories) for the file
                   16026:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16027:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16028:   allfiles: reference to hash used to store objects found by parser
                   16029:   codebase: reference to hash used for codebases of java objects found by parser
                   16030:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16031:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16032:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16033:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16034:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16035:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16036:   mimetype: reference to scalar to accommodate mime type determined
                   16037:             from File::MMagic if $parser = parse.
1.608     albertel 16038: 
                   16039:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16040:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16041:  was 'overwrite').
                   16042:  
1.608     albertel 16043: 
                   16044: =item *
                   16045: 
                   16046: renameuserfile(): renames an existing userfile to a new name
                   16047: 
                   16048:   Args:
                   16049:    docuname: username or courseid of destination for the file
                   16050:    docudom: domain of user/course of destination for the file
                   16051:    old: current file name (including any subdirs under userfiles)
                   16052:    new: desired file name (including any subdirs under userfiles)
                   16053: 
                   16054: =item *
                   16055: 
                   16056: mkdiruserfile(): creates a directory is a userfiles dir
                   16057: 
                   16058:   Args:
                   16059:    docuname: username or courseid of destination for the file
                   16060:    docudom: domain of user/course of destination for the file
                   16061:    dir: dir to create (including any subdirs under userfiles)
                   16062: 
                   16063: =item *
                   16064: 
                   16065: removeuserfile(): removes a file that exists in userfiles
                   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:    fname: filname to delete (including any subdirs under userfiles)
                   16071: 
                   16072: =item *
                   16073: 
                   16074: removeuploadedurl(): convience function for removeuserfile()
                   16075: 
                   16076:   Args:
                   16077:    url:  a full /uploaded/... url to delete
                   16078: 
1.747     albertel 16079: =item * 
                   16080: 
                   16081: get_portfile_permissions():
                   16082:   Args:
                   16083:     domain: domain of user or course contain the portfolio files
                   16084:     user: name of user or num of course contain the portfolio files
                   16085:   Returns:
                   16086:     hashref of a dump of the proper file_permissions.db
                   16087:    
                   16088: 
                   16089: =item * 
                   16090: 
                   16091: get_access_controls():
                   16092: 
                   16093: Args:
                   16094:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16095:   group: (optional) the group you want the files associated with
                   16096:   file: (optional) the file you want access info on
                   16097: 
                   16098: Returns:
1.749     raeburn  16099:     a hash (keys are file names) of hashes containing
                   16100:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16101:         values are XML containing access control settings (see below) 
1.747     albertel 16102: 
                   16103: Internal notes:
                   16104: 
1.749     raeburn  16105:  access controls are stored in file_permissions.db as key=value pairs.
                   16106:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16107:         where scope -> public,guest,course,group,domains or users.
                   16108:               end -> UNIX time for end of access (0 -> no end date)
                   16109:               start -> UNIX time for start of access
                   16110: 
                   16111:     value -> XML description of access control
                   16112:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16113:             <start></start>
                   16114:             <end></end>
                   16115: 
                   16116:             <password></password>  for scope type = guest
                   16117: 
                   16118:             <domain></domain>     for scope type = course or group
                   16119:             <number></number>
                   16120:             <roles id="">
                   16121:              <role></role>
                   16122:              <access></access>
                   16123:              <section></section>
                   16124:              <group></group>
                   16125:             </roles>
                   16126: 
                   16127:             <dom></dom>         for scope type = domains
                   16128: 
                   16129:             <users>             for scope type = users
                   16130:              <user>
                   16131:               <uname></uname>
                   16132:               <udom></udom>
                   16133:              </user>
                   16134:             </users>
                   16135:            </scope> 
                   16136:               
                   16137:  Access data is also aggregated for each file in an additional key=value pair:
                   16138:  key -> path to file/file_name\0accesscontrol 
                   16139:  value -> reference to hash
                   16140:           hash contains key = value pairs
                   16141:           where key = uniqueID:scope_end_start
                   16142:                 value = UNIX time record was last updated
                   16143: 
                   16144:           Used to improve speed of look-ups of access controls for each file.  
                   16145:  
                   16146:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16147: 
1.1172.2.13  raeburn  16148: =item *
                   16149: 
1.749     raeburn  16150: modify_access_controls():
                   16151: 
                   16152: Modifies access controls for a portfolio file
                   16153: Args
                   16154: 1. file name
                   16155: 2. reference to hash of required changes,
                   16156: 3. domain
                   16157: 4. username
                   16158:   where domain,username are the domain of the portfolio owner 
                   16159:   (either a user or a course) 
                   16160: 
                   16161: Returns:
                   16162: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16163: 2. result of deletions ('ok' or 'error', with error message).
                   16164: 3. reference to hash of any new or updated access controls.
                   16165: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16166:    key = integer (inbound ID)
1.1172.2.13  raeburn  16167:    value = uniqueID
                   16168: 
                   16169: =item *
                   16170: 
                   16171: get_timebased_id():
                   16172: 
                   16173: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16174: course via the Course Editor (e.g., folders, composite pages,
                   16175: group bulletin boards).
                   16176: 
                   16177: Args: (first three required; six others optional)
                   16178: 
                   16179: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16180:    docssequence, or name of group
                   16181: 
                   16182: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16183:    e.g., num, boardids
                   16184: 
                   16185: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16186:    file will be named nohist_namespace.db
                   16187: 
                   16188: 4. cdom: domain of course; default is current course domain from %env
                   16189: 
                   16190: 5. cnum: course number; default is current course number from %env
                   16191: 
                   16192: 6. idtype: set to concat if an additional digit is to be appended to the
                   16193:    unix timestamp to form the suffix, if the plain timestamp is already
                   16194:    in use.  Default is to not do this, but simply increment the unix
                   16195:    timestamp by 1 until a unique key is obtained.
                   16196: 
                   16197: 7. who: holder of locking key; defaults to user:domain for user.
                   16198: 
                   16199: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16200:    retrying); default is 3.
                   16201: 
                   16202: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16203: 
                   16204: Returns:
                   16205: 
                   16206: 1. suffix obtained (numeric)
                   16207: 
                   16208: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16209: 
                   16210: 3. error: contains (localized) error message if an error occurred.
                   16211: 
1.747     albertel 16212: 
1.608     albertel 16213: =back
                   16214: 
1.243     albertel 16215: =head2 HTTP Helper Routines
                   16216: 
                   16217: =over 4
                   16218: 
1.191     harris41 16219: =item *
                   16220: 
                   16221: escape() : unpack non-word characters into CGI-compatible hex codes
                   16222: 
                   16223: =item *
                   16224: 
                   16225: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16226: 
1.243     albertel 16227: =back
                   16228: 
                   16229: =head1 PRIVATE SUBROUTINES
                   16230: 
                   16231: =head2 Underlying communication routines (Shouldn't call)
                   16232: 
                   16233: =over 4
                   16234: 
                   16235: =item *
                   16236: 
                   16237: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16238: 
                   16239: =item *
                   16240: 
                   16241: reply() : uses subreply to send a message to remote machine, logs all failures
                   16242: 
                   16243: =item *
                   16244: 
                   16245: critical() : passes a critical message to another server; if cannot
                   16246: get through then place message in connection buffer directory and
                   16247: returns con_delayed, if incapable of saving message, returns
                   16248: con_failed
                   16249: 
                   16250: =item *
                   16251: 
                   16252: reconlonc() : tries to reconnect lonc client processes.
                   16253: 
                   16254: =back
                   16255: 
                   16256: =head2 Resource Access Logging
                   16257: 
                   16258: =over 4
                   16259: 
                   16260: =item *
                   16261: 
                   16262: flushcourselogs() : flush (save) buffer logs and access logs
                   16263: 
                   16264: =item *
                   16265: 
                   16266: courselog($what) : save message for course in hash
                   16267: 
                   16268: =item *
                   16269: 
                   16270: courseacclog($what) : save message for course using &courselog().  Perform
                   16271: special processing for specific resource types (problems, exams, quizzes, etc).
                   16272: 
1.191     harris41 16273: =item *
                   16274: 
                   16275: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16276: as a PerlChildExitHandler
1.243     albertel 16277: 
                   16278: =back
                   16279: 
                   16280: =head2 Other
                   16281: 
                   16282: =over 4
                   16283: 
                   16284: =item *
                   16285: 
                   16286: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16287: 
                   16288: =back
                   16289: 
                   16290: =cut
1.877     foxr     16291: 

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