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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.147! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.146 2022/01/03 05:07:50 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);
1.1172.2.147! raeburn  1257:     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 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");
1.1172.2.147! raeburn  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.1172.2.147! raeburn  2274:                 } elsif ($item eq 'unamemap') {
        !          2275:                     $response=&unescape(&reply('instunamemapcheck:'.
        !          2276:                                                &escape($udom).':'.&escape($uname).
        !          2277:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2278:                 }
1.912     raeburn  2279:                 if ($response ne 'refused') {
                   2280:                     my @pairs=split(/\&/,$response);
                   2281:                     foreach my $item (@pairs) {
                   2282:                         my ($key,$value)=split(/=/,$item,2);
                   2283:                         $key = &unescape($key);
                   2284:                         next if ($key =~ /^error: 2 /);
                   2285:                         $returnhash{$key}=&thaw_unescape($value);
                   2286:                     }
                   2287:                 }
                   2288:             }
                   2289:         }
                   2290:     }
                   2291:     return %returnhash;
                   2292: }
                   2293: 
                   2294: sub inst_userrules {
1.923     raeburn  2295:     my ($udom,$check) = @_;
1.912     raeburn  2296:     my (%ruleshash,@ruleorder);
                   2297:     if ($udom ne '') {
                   2298:         my $homeserver=&domain($udom,'primary');
                   2299:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2300:             my $response;
                   2301:             if ($check eq 'id') {
                   2302:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2303:                                  $homeserver);
1.943     raeburn  2304:             } elsif ($check eq 'email') {
                   2305:                 $response=&reply('instemailrules:'.&escape($udom),
                   2306:                                  $homeserver);
1.1172.2.147! raeburn  2307:             } elsif ($check eq 'unamemap') {
        !          2308:                 $response=&reply('unamemaprules:'.&escape($udom),
        !          2309:                                  $homeserver);
1.923     raeburn  2310:             } else {
                   2311:                 $response=&reply('instuserrules:'.&escape($udom),
                   2312:                                  $homeserver);
                   2313:             }
1.912     raeburn  2314:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2315:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2316:                 ($response ne 'no_such_host')) {
                   2317:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2318:                 my @pairs=split(/\&/,$hashitems);
                   2319:                 foreach my $item (@pairs) {
                   2320:                     my ($key,$value)=split(/=/,$item,2);
                   2321:                     $key = &unescape($key);
                   2322:                     next if ($key =~ /^error: 2 /);
                   2323:                     $ruleshash{$key}=&thaw_unescape($value);
                   2324:                 }
                   2325:                 my @esc_order = split(/\&/,$orderitems);
                   2326:                 foreach my $item (@esc_order) {
                   2327:                     push(@ruleorder,&unescape($item));
                   2328:                 }
                   2329:             }
                   2330:         }
                   2331:     }
                   2332:     return (\%ruleshash,\@ruleorder);
                   2333: }
                   2334: 
1.976     raeburn  2335: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2336: 
                   2337: sub get_domain_defaults {
1.1172.2.35  raeburn  2338:     my ($domain,$ignore_cache) = @_;
                   2339:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2340:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2341:     unless ($ignore_cache) {
                   2342:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2343:         if (defined($cached)) {
                   2344:             if (ref($result) eq 'HASH') {
                   2345:                 return %{$result};
                   2346:             }
1.943     raeburn  2347:         }
                   2348:     }
                   2349:     my %domdefaults;
                   2350:     my %domconfig =
1.989     raeburn  2351:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2352:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2353:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2354:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2355:                                   'coursecategories','autoenroll',
1.1172.2.146  raeburn  2356:                                   'helpsettings','wafproxy'],$domain);
1.1172.2.41  raeburn  2357:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2358:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2359:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2360:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2361:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2362:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2363:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2364:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2365:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2366:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2367:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.147! raeburn  2368:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2369:     } else {
                   2370:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2371:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2372:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2373:     }
1.976     raeburn  2374:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2375:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2376:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2377:         } else {
                   2378:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2379:         }
1.1172.2.6  raeburn  2380:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2381:         foreach my $item (@usertools) {
                   2382:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2383:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2384:             }
                   2385:         }
1.1172.2.29  raeburn  2386:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2387:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2388:         }
1.976     raeburn  2389:     }
1.985     raeburn  2390:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2391:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2392:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2393:         }
                   2394:     }
1.1172.2.9  raeburn  2395:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2396:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2397:     }
1.989     raeburn  2398:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2399:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2400:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2401:         }
                   2402:     }
1.1047    raeburn  2403:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2404:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2405:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2406:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2407:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2408:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2409:         }
1.1172.2.41  raeburn  2410:         foreach my $type (@coursetypes) {
                   2411:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2412:                 unless ($type eq 'community') {
                   2413:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2414:                 }
                   2415:             }
                   2416:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2417:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2418:             }
1.1172.2.60  raeburn  2419:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2420:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2421:                     $domdefaults{$type.'postsubtimeout'} =
                   2422:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2423:                 }
                   2424:             }
1.1172.2.30  raeburn  2425:         }
1.1172.2.67  raeburn  2426:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2427:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2428:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2429:                 if (@clonecodes) {
                   2430:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2431:                 }
                   2432:             }
                   2433:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2434:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2435:         }
1.1172.2.103  raeburn  2436:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2437:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2438:         }
1.1047    raeburn  2439:     }
1.1073    raeburn  2440:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2441:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2442:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2443:         }
                   2444:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2445:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2446:         }
1.1172.2.62  raeburn  2447:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2448:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2449:         }
1.1172.2.137  raeburn  2450:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2451:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2452:         }
1.1073    raeburn  2453:     }
1.1172.2.41  raeburn  2454:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2455:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2456:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2457:                             'approval','limit');
                   2458:             foreach my $type (@coursetypes) {
                   2459:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2460:                     my @mgrdc = ();
                   2461:                     foreach my $item (@settings) {
                   2462:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2463:                             push(@mgrdc,$item);
                   2464:                         }
                   2465:                     }
                   2466:                     if (@mgrdc) {
                   2467:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2468:                     }
                   2469:                 }
                   2470:             }
                   2471:         }
                   2472:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2473:             foreach my $type (@coursetypes) {
                   2474:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2475:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2476:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2477:                     }
                   2478:                 }
                   2479:             }
                   2480:         }
                   2481:     }
1.1172.2.46  raeburn  2482:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2483:         $domdefaults{'catauth'} = 'std';
                   2484:         $domdefaults{'catunauth'} = 'std';
                   2485:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2486:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2487:         }
                   2488:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2489:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2490:         }
                   2491:     }
1.1172.2.76  raeburn  2492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2493:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2494:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2495:     }
1.1172.2.89  raeburn  2496:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2497:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2498:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2499:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2500:         }
                   2501:     }
1.1172.2.142  raeburn  2502:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2503:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2504:             if ($domconfig{'wafproxy'}{$item}) {
                   2505:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2506:             }
                   2507:         }
                   2508:     }
1.1172.2.23  raeburn  2509:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2510:     return %domdefaults;
                   2511: }
                   2512: 
1.1172.2.106  raeburn  2513: sub get_dom_cats {
                   2514:     my ($dom) = @_;
                   2515:     return unless (&domain($dom));
                   2516:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2517:     unless (defined($cached)) {
                   2518:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2519:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2520:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2521:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2522:             } else {
                   2523:                 $cats = {};
                   2524:             }
                   2525:         } else {
                   2526:             $cats = {};
                   2527:         }
                   2528:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2529:     }
                   2530:     return $cats;
                   2531: }
                   2532: 
                   2533: sub get_dom_instcats {
                   2534:     my ($dom) = @_;
                   2535:     return unless (&domain($dom));
                   2536:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2537:     unless (defined($cached)) {
                   2538:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2539:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2540:         if ($totcodes > 0) {
                   2541:             my $caller = 'global';
                   2542:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2543:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2544:                 $instcats = {
                   2545:                                 codes => \%codes,
                   2546:                                 codetitles => \@codetitles,
                   2547:                                 cat_titles => \%cat_titles,
                   2548:                                 cat_order => \%cat_order,
                   2549:                             };
                   2550:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2551:             }
                   2552:         }
                   2553:     }
                   2554:     return $instcats;
                   2555: }
                   2556: 
                   2557: sub retrieve_instcodes {
                   2558:     my ($coursecodes,$dom) = @_;
                   2559:     my $totcodes;
                   2560:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2561:     foreach my $course (keys(%courses)) {
                   2562:         if (ref($courses{$course}) eq 'HASH') {
                   2563:             if ($courses{$course}{'inst_code'} ne '') {
                   2564:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2565:                 $totcodes ++;
                   2566:             }
                   2567:         }
                   2568:     }
                   2569:     return $totcodes;
                   2570: }
                   2571: 
1.1172.2.113  raeburn  2572: # --------------------------------------------- Get domain config for passwords
                   2573: 
                   2574: sub get_passwdconf {
                   2575:     my ($dom) = @_;
                   2576:     my (%passwdconf,$gotconf,$lookup);
                   2577:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2578:     if (defined($cached)) {
                   2579:         if (ref($result) eq 'HASH') {
                   2580:             %passwdconf = %{$result};
                   2581:             $gotconf = 1;
                   2582:         }
                   2583:     }
                   2584:     unless ($gotconf) {
                   2585:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2586:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2587:             %passwdconf = %{$domconfig{'passwords'}};
                   2588:         }
                   2589:         my $cachetime = 24*60*60;
                   2590:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2591:     }
                   2592:     return %passwdconf;
                   2593: }
                   2594: 
1.344     www      2595: # --------------------------------------------------- Assign a key to a student
                   2596: 
                   2597: sub assign_access_key {
1.364     www      2598: #
                   2599: # a valid key looks like uname:udom#comments
                   2600: # comments are being appended
                   2601: #
1.498     www      2602:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2603:     $kdom=
1.620     albertel 2604:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2605:     $knum=
1.620     albertel 2606:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2607:     $cdom=
1.620     albertel 2608:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2609:     $cnum=
1.620     albertel 2610:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2611:     $udom=$env{'user.name'} unless (defined($udom));
                   2612:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2613:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2614:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2615:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2616:                                                   # assigned to this person
                   2617:                                                   # - this should not happen,
1.345     www      2618:                                                   # unless something went wrong
                   2619:                                                   # the first time around
                   2620: # ready to assign
1.364     www      2621:         $logentry=$1.'; '.$logentry;
1.496     www      2622:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2623:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2624: # key now belongs to user
1.346     www      2625: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2626:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2627:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2628:                 return 'ok';
                   2629:             } else {
                   2630:                 return 
                   2631:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2632: 	    }
                   2633:         } else {
                   2634:             return 'error: Could not assign key, try again later.';
                   2635:         }
1.364     www      2636:     } elsif (!$existing{$ckey}) {
1.345     www      2637: # the key does not exist
                   2638: 	return 'error: The key does not exist';
                   2639:     } else {
                   2640: # the key is somebody else's
                   2641: 	return 'error: The key is already in use';
                   2642:     }
1.344     www      2643: }
                   2644: 
1.364     www      2645: # ------------------------------------------ put an additional comment on a key
                   2646: 
                   2647: sub comment_access_key {
                   2648: #
                   2649: # a valid key looks like uname:udom#comments
                   2650: # comments are being appended
                   2651: #
                   2652:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2653:     $cdom=
1.620     albertel 2654:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2655:     $cnum=
1.620     albertel 2656:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2657:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2658:     if ($existing{$ckey}) {
                   2659:         $existing{$ckey}.='; '.$logentry;
                   2660: # ready to assign
1.367     www      2661:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2662:                                                  $cdom,$cnum) eq 'ok') {
                   2663: 	    return 'ok';
                   2664:         } else {
                   2665: 	    return 'error: Count not store comment.';
                   2666:         }
                   2667:     } else {
                   2668: # the key does not exist
                   2669: 	return 'error: The key does not exist';
                   2670:     }
                   2671: }
                   2672: 
1.344     www      2673: # ------------------------------------------------------ Generate a set of keys
                   2674: 
                   2675: sub generate_access_keys {
1.364     www      2676:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2677:     $cdom=
1.620     albertel 2678:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2679:     $cnum=
1.620     albertel 2680:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2681:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2682:     unless (($cdom) && ($cnum)) { return 0; }
                   2683:     if ($number>10000) { return 0; }
                   2684:     sleep(2); # make sure don't get same seed twice
                   2685:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2686:     my $total=0;
                   2687:     for (my $i=1;$i<=$number;$i++) {
                   2688:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2689:                   sprintf("%lx",int(100000*rand)).'-'.
                   2690:                   sprintf("%lx",int(100000*rand));
                   2691:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2692:        $newkey=~s/0/h/g; # and also 0 and O
                   2693:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2694:        if ($existing{$newkey}) {
                   2695:            $i--;
                   2696:        } else {
1.364     www      2697: 	  if (&put('accesskeys',
                   2698:               { $newkey => '# generated '.localtime().
1.620     albertel 2699:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2700:                            '; '.$logentry },
                   2701: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2702:               $total++;
                   2703: 	  }
                   2704:        }
                   2705:     }
1.620     albertel 2706:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2707:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2708:     return $total;
                   2709: }
                   2710: 
                   2711: # ------------------------------------------------------- Validate an accesskey
                   2712: 
                   2713: sub validate_access_key {
                   2714:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2715:     $cdom=
1.620     albertel 2716:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2717:     $cnum=
1.620     albertel 2718:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2719:     $udom=$env{'user.domain'} unless (defined($udom));
                   2720:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2721:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2722:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2723: }
                   2724: 
                   2725: # ------------------------------------- Find the section of student in a course
1.652     albertel 2726: sub devalidate_getsection_cache {
                   2727:     my ($udom,$unam,$courseid)=@_;
                   2728:     my $hashid="$udom:$unam:$courseid";
                   2729:     &devalidate_cache_new('getsection',$hashid);
                   2730: }
1.298     matthew  2731: 
1.815     albertel 2732: sub courseid_to_courseurl {
                   2733:     my ($courseid) = @_;
                   2734:     #already url style courseid
                   2735:     return $courseid if ($courseid =~ m{^/});
                   2736: 
                   2737:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2738: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2739: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2740: 	return "/$cdom/$cnum";
                   2741:     }
                   2742: 
                   2743:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2744:     if (exists($courseinfo{'num'})) {
                   2745: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2746:     }
                   2747: 
                   2748:     return undef;
                   2749: }
                   2750: 
1.298     matthew  2751: sub getsection {
                   2752:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2753:     my $cachetime=1800;
1.551     albertel 2754: 
                   2755:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2756:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2757:     if (defined($cached)) { return $result; }
                   2758: 
1.298     matthew  2759:     my %Pending; 
                   2760:     my %Expired;
                   2761:     #
                   2762:     # Each role can either have not started yet (pending), be active, 
                   2763:     #    or have expired.
                   2764:     #
                   2765:     # If there is an active role, we are done.
                   2766:     #
                   2767:     # If there is more than one role which has not started yet, 
                   2768:     #     choose the one which will start sooner
                   2769:     # If there is one role which has not started yet, return it.
                   2770:     #
                   2771:     # If there is more than one expired role, choose the one which ended last.
                   2772:     # If there is a role which has expired, return it.
                   2773:     #
1.815     albertel 2774:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2775:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2776:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2777:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2778:         my $section=$1;
                   2779:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2780:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2781:         my $now=time;
1.548     albertel 2782:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2783:             $Expired{$end}=$section;
                   2784:             next;
                   2785:         }
1.548     albertel 2786:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2787:             $Pending{$start}=$section;
                   2788:             next;
                   2789:         }
1.599     albertel 2790:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2791:     }
                   2792:     #
                   2793:     # Presumedly there will be few matching roles from the above
                   2794:     # loop and the sorting time will be negligible.
                   2795:     if (scalar(keys(%Pending))) {
                   2796:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2797:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2798:     } 
                   2799:     if (scalar(keys(%Expired))) {
                   2800:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2801:         my $time = pop(@sorted);
1.599     albertel 2802:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2803:     }
1.599     albertel 2804:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2805: }
1.70      www      2806: 
1.599     albertel 2807: sub save_cache {
                   2808:     &purge_remembered();
1.722     albertel 2809:     #&Apache::loncommon::validate_page();
1.620     albertel 2810:     undef(%env);
1.780     albertel 2811:     undef($env_loaded);
1.599     albertel 2812: }
1.452     albertel 2813: 
1.599     albertel 2814: my $to_remember=-1;
                   2815: my %remembered;
                   2816: my %accessed;
                   2817: my $kicks=0;
                   2818: my $hits=0;
1.849     albertel 2819: sub make_key {
                   2820:     my ($name,$id) = @_;
1.872     albertel 2821:     if (length($id) > 65 
                   2822: 	&& length(&escape($id)) > 200) {
                   2823: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2824:     }
1.849     albertel 2825:     return &escape($name.':'.$id);
                   2826: }
                   2827: 
1.599     albertel 2828: sub devalidate_cache_new {
                   2829:     my ($name,$id,$debug) = @_;
                   2830:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2831:     my $remembered_id=$name.':'.$id;
1.849     albertel 2832:     $id=&make_key($name,$id);
1.599     albertel 2833:     $memcache->delete($id);
1.1172.2.81  raeburn  2834:     delete($remembered{$remembered_id});
                   2835:     delete($accessed{$remembered_id});
1.599     albertel 2836: }
                   2837: 
                   2838: sub is_cached_new {
                   2839:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2840:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2841:                                      # keys in %remembered hash, which persists for
                   2842:                                      # duration of request (no restriction on key length).
                   2843:     if (exists($remembered{$remembered_id})) {
                   2844: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2845: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2846: 	$hits++;
1.1172.2.81  raeburn  2847: 	return ($remembered{$remembered_id},1);
1.599     albertel 2848:     }
1.1172.2.81  raeburn  2849:     $id=&make_key($name,$id);
1.599     albertel 2850:     my $value = $memcache->get($id);
                   2851:     if (!(defined($value))) {
                   2852: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2853: 	return (undef,undef);
1.416     albertel 2854:     }
1.599     albertel 2855:     if ($value eq '__undef__') {
                   2856: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2857: 	$value=undef;
                   2858:     }
1.1172.2.81  raeburn  2859:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2860:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2861:     return ($value,1);
                   2862: }
                   2863: 
                   2864: sub do_cache_new {
                   2865:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2866:     my $remembered_id=$name.':'.$id;
1.849     albertel 2867:     $id=&make_key($name,$id);
1.599     albertel 2868:     my $setvalue=$value;
                   2869:     if (!defined($setvalue)) {
                   2870: 	$setvalue='__undef__';
                   2871:     }
1.623     albertel 2872:     if (!defined($time) ) {
                   2873: 	$time=600;
                   2874:     }
1.599     albertel 2875:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2876:     my $result = $memcache->set($id,$setvalue,$time);
                   2877:     if (! $result) {
1.872     albertel 2878: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2879: 	$memcache->disconnect_all();
1.872     albertel 2880:     }
1.600     albertel 2881:     # need to make a copy of $value
1.1172.2.81  raeburn  2882:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2883:     return $value;
                   2884: }
                   2885: 
                   2886: sub make_room {
1.1172.2.81  raeburn  2887:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2888: 
1.1172.2.81  raeburn  2889:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2890:                                     : $value;
1.599     albertel 2891:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2892:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2893:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2894:     my $to_kick;
                   2895:     my $max_time=0;
                   2896:     foreach my $other (keys(%accessed)) {
                   2897: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2898: 	    $to_kick=$other;
                   2899: 	    $max_time=&tv_interval($accessed{$other});
                   2900: 	}
                   2901:     }
                   2902:     delete($remembered{$to_kick});
                   2903:     delete($accessed{$to_kick});
                   2904:     $kicks++;
                   2905:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2906:     return;
                   2907: }
                   2908: 
1.599     albertel 2909: sub purge_remembered {
1.604     albertel 2910:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2911:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2912:     undef(%remembered);
                   2913:     undef(%accessed);
1.428     albertel 2914: }
1.70      www      2915: # ------------------------------------- Read an entry from a user's environment
                   2916: 
                   2917: sub userenvironment {
                   2918:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2919:     my $items;
                   2920:     foreach my $item (@what) {
                   2921:         $items.=&escape($item).'&';
                   2922:     }
                   2923:     $items=~s/\&$//;
1.70      www      2924:     my %returnhash=();
1.1009    raeburn  2925:     my $uhome = &homeserver($unam,$udom);
                   2926:     unless ($uhome eq 'no_host') {
                   2927:         my @answer=split(/\&/, 
                   2928:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2929:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2930:             return %returnhash;
                   2931:         }
1.1009    raeburn  2932:         my $i;
                   2933:         for ($i=0;$i<=$#what;$i++) {
                   2934: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2935:         }
1.70      www      2936:     }
                   2937:     return %returnhash;
1.1       albertel 2938: }
                   2939: 
1.617     albertel 2940: # ---------------------------------------------------------- Get a studentphoto
                   2941: sub studentphoto {
                   2942:     my ($udom,$unam,$ext) = @_;
                   2943:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2944:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2945:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2946:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2947:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2948:             } else {
                   2949:                 my ($result,$perm_reqd)=
1.707     albertel 2950: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2951:                 if ($result eq 'ok') {
                   2952:                     if (!($perm_reqd eq 'yes')) {
                   2953:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2954:                     }
                   2955:                 }
                   2956:             }
                   2957:         }
                   2958:     } else {
                   2959:         my ($result,$perm_reqd) = 
1.707     albertel 2960: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2961:         if ($result eq 'ok') {
                   2962:             if (!($perm_reqd eq 'yes')) {
                   2963:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2964:             }
                   2965:         }
                   2966:     }
                   2967:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2968: }
                   2969: 
                   2970: sub retrievestudentphoto {
                   2971:     my ($udom,$unam,$ext,$type) = @_;
                   2972:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2973:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2974:     if ($ret eq 'ok') {
                   2975:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2976:         if ($type eq 'thumbnail') {
                   2977:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2978:         }
                   2979:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2980:         return $tokenurl;
                   2981:     } else {
                   2982:         if ($type eq 'thumbnail') {
                   2983:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2984:         } else { 
                   2985:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2986:         }
1.617     albertel 2987:     }
                   2988: }
                   2989: 
1.263     www      2990: # -------------------------------------------------------------------- New chat
                   2991: 
                   2992: sub chatsend {
1.724     raeburn  2993:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2994:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2995:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2996:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2997:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2998: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2999: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3000: }
                   3001: 
                   3002: # ------------------------------------------ Find current version of a resource
                   3003: 
                   3004: sub getversion {
                   3005:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3006:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3007:     return &currentversion(&filelocation('',$fname));
                   3008: }
                   3009: 
                   3010: sub currentversion {
                   3011:     my $fname=shift;
                   3012:     my $author=$fname;
                   3013:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3014:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3015:     my $home=&homeserver($uname,$udom);
1.292     www      3016:     if ($home eq 'no_host') { 
                   3017:         return -1; 
                   3018:     }
1.1112    www      3019:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3020:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3021: 	return -1;
                   3022:     }
1.1112    www      3023:     return $answer;
1.263     www      3024: }
                   3025: 
1.1111    www      3026: #
                   3027: # Return special version number of resource if set by override, empty otherwise
                   3028: #
                   3029: sub usedversion {
                   3030:     my $fname=shift;
                   3031:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3032:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3033:     if ($urlversion) { return $urlversion; }
                   3034:     return '';
                   3035: }
                   3036: 
1.1       albertel 3037: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3038: 
1.1       albertel 3039: sub subscribe {
                   3040:     my $fname=shift;
1.761     raeburn  3041:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3042:     $fname=~s/[\n\r]//g;
1.1       albertel 3043:     my $author=$fname;
                   3044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3045:     my ($udom,$uname)=split(/\//,$author);
                   3046:     my $home=homeserver($uname,$udom);
1.335     albertel 3047:     if ($home eq 'no_host') {
                   3048:         return 'not_found';
1.1       albertel 3049:     }
                   3050:     my $answer=reply("sub:$fname",$home);
1.64      www      3051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3052: 	$answer.=' by '.$home;
                   3053:     }
1.1       albertel 3054:     return $answer;
                   3055: }
                   3056:     
1.8       www      3057: # -------------------------------------------------------------- Replicate file
                   3058: 
                   3059: sub repcopy {
                   3060:     my $filename=shift;
1.23      www      3061:     $filename=~s/\/+/\//g;
1.1142    raeburn  3062:     my $londocroot = $perlvar{'lonDocRoot'};
                   3063:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3064:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3065:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3066: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3067: 	return &repcopy_userfile($filename);
                   3068:     }
1.532     albertel 3069:     $filename=~s/[\n\r]//g;
1.8       www      3070:     my $transname="$filename.in.transfer";
1.828     www      3071: # FIXME: this should flock
1.607     raeburn  3072:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3073:     my $remoteurl=subscribe($filename);
1.64      www      3074:     if ($remoteurl =~ /^con_lost by/) {
                   3075: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3076:            return 'unavailable';
1.8       www      3077:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3078: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3079: 	   return 'not_found';
1.64      www      3080:     } elsif ($remoteurl =~ /^rejected by/) {
                   3081: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3082:            return 'forbidden';
1.20      www      3083:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3084:            return 'ok';
1.8       www      3085:     } else {
1.290     www      3086:         my $author=$filename;
                   3087:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3088:         my ($udom,$uname)=split(/\//,$author);
                   3089:         my $home=homeserver($uname,$udom);
                   3090:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3091:            my @parts=split(/\//,$filename);
                   3092:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3093:            if ($path ne "$londocroot/res") {
1.8       www      3094:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3095: 	       return 'bad_request';
1.8       www      3096:            }
                   3097:            my $count;
                   3098:            for ($count=5;$count<$#parts;$count++) {
                   3099:                $path.="/$parts[$count]";
                   3100:                if ((-e $path)!=1) {
                   3101: 		   mkdir($path,0777);
                   3102:                }
                   3103:            }
                   3104:            my $ua=new LWP::UserAgent;
                   3105:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3106:            my $response=$ua->request($request,$transname);
                   3107:            if ($response->is_error()) {
                   3108: 	       unlink($transname);
                   3109:                my $message=$response->status_line;
1.672     albertel 3110:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3111:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3112:                return 'unavailable';
1.8       www      3113:            } else {
1.16      www      3114: 	       if ($remoteurl!~/\.meta$/) {
                   3115:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3116:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3117:                   if ($mresponse->is_error()) {
                   3118: 		      unlink($filename.'.meta');
                   3119:                       &logthis(
1.672     albertel 3120:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3121:                   }
                   3122: 	       }
1.8       www      3123:                rename($transname,$filename);
1.607     raeburn  3124:                return 'ok';
1.8       www      3125:            }
1.290     www      3126:        }
1.8       www      3127:     }
1.330     www      3128: }
                   3129: 
1.1172.2.124  raeburn  3130: # ------------------------------------------------- Unsubscribe from a resource
                   3131: 
                   3132: sub unsubscribe {
                   3133:     my ($fname) = @_;
                   3134:     my $answer;
                   3135:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3136:     $fname=~s/[\n\r]//g;
                   3137:     my $author=$fname;
                   3138:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3139:     my ($udom,$uname)=split(/\//,$author);
                   3140:     my $home=homeserver($uname,$udom);
                   3141:     if ($home eq 'no_host') {
                   3142:         $answer = 'no_host';
                   3143:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3144:         $answer = 'home';
                   3145:     } else {
1.1172.2.125  raeburn  3146:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3147:     }
                   3148:     return $answer;
                   3149: }
                   3150: 
1.330     www      3151: # ------------------------------------------------ Get server side include body
                   3152: sub ssi_body {
1.381     albertel 3153:     my ($filelink,%form)=@_;
1.606     matthew  3154:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3155:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3156:     }
1.953     www      3157:     my $output='';
                   3158:     my $response;
1.980     raeburn  3159:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3160:        ($output,$response)=&externalssi($filelink);
1.953     www      3161:     } else {
1.1004    droeschl 3162:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3163:        $filelink .= 'inhibitmenu=yes';
1.953     www      3164:        ($output,$response)=&ssi($filelink,%form);
                   3165:     }
1.778     albertel 3166:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3167:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3168:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3169:     if (wantarray) {
                   3170:         return ($output, $response);
                   3171:     } else {
                   3172:         return $output;
                   3173:     }
1.8       www      3174: }
                   3175: 
1.15      www      3176: # --------------------------------------------------------- Server Side Include
                   3177: 
1.782     albertel 3178: sub absolute_url {
1.1172.2.145  raeburn  3179:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3180:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3181:     if ($host_name eq '') {
                   3182: 	$host_name = $ENV{'SERVER_NAME'};
                   3183:     }
1.1172.2.145  raeburn  3184:     if ($unalias) {
                   3185:         my $alias = &get_proxy_alias();
                   3186:         if ($alias eq $host_name) {
                   3187:             my $lonhost = $perlvar{'lonHostID'};
                   3188:             my $hostname = &hostname($lonhost);
                   3189:             my $lcproto;
                   3190:             if (($keep_proto) || ($hostname eq '')) {
                   3191:                 $lcproto = $protocol;
                   3192:             } else {
                   3193:                 $lcproto = $protocol{$lonhost};
                   3194:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3195:                 $lcproto .= '://';
                   3196:             }
                   3197:             unless ($hostname eq '') {
                   3198:                 return $lcproto.$hostname;
                   3199:             }
                   3200:         }
                   3201:     } 
1.782     albertel 3202:     return $protocol.$host_name;
                   3203: }
                   3204: 
1.942     foxr     3205: #
                   3206: #   Server side include.
                   3207: # Parameters:
                   3208: #  fn     Possibly encrypted resource name/id.
                   3209: #  form   Hash that describes how the rendering should be done
                   3210: #         and other things.
1.944     foxr     3211: # Returns:
1.950     raeburn  3212: #   Scalar context: The content of the response.
                   3213: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3214: #     
1.15      www      3215: sub ssi {
                   3216: 
1.944     foxr     3217:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3218:     my ($host,$request,$response);
                   3219:     $host = &absolute_url('',1);
1.711     albertel 3220: 
                   3221:     $form{'no_update_last_known'}=1;
1.895     albertel 3222:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3223:     if (%form) {
1.1172.2.145  raeburn  3224:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3225:       $request->content(join('&',map {
                   3226:             my $name = escape($_);
                   3227:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3228:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3229:             : &escape($form{$_}) );
                   3230:         } keys(%form)));
1.23      www      3231:     } else {
1.1172.2.145  raeburn  3232:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3233:     }
                   3234: 
1.15      www      3235:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3236: 
1.1172.2.101  raeburn  3237:     if (($env{'request.course.id'}) &&
                   3238:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3239:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3240:         ($form{'grade_symb'} ne '') &&
                   3241:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3242:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3243:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3244:             my $ua=new LWP::UserAgent;
                   3245:             $ua->local_address('127.0.0.1');
                   3246:             $response = $ua->request($request);
                   3247:         } else {
                   3248:             {
                   3249:                 require LWP::Protocol::http;
                   3250:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3251:                 my $ua=new LWP::UserAgent;
                   3252:                 $response = $ua->request($request);
                   3253:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3254:             }
                   3255:         }
                   3256:     } else {
                   3257:         my $ua=new LWP::UserAgent;
                   3258:         $response = $ua->request($request);
                   3259:     }
1.944     foxr     3260:     if (wantarray) {
1.1172.2.3  raeburn  3261: 	return ($response->content, $response);
1.944     foxr     3262:     } else {
1.1172.2.3  raeburn  3263: 	return $response->content;
1.942     foxr     3264:     }
1.324     www      3265: }
                   3266: 
                   3267: sub externalssi {
                   3268:     my ($url)=@_;
                   3269:     my $ua=new LWP::UserAgent;
                   3270:     my $request=new HTTP::Request('GET',$url);
                   3271:     my $response=$ua->request($request);
1.954     raeburn  3272:     if (wantarray) {
                   3273:         return ($response->content, $response);
                   3274:     } else {
                   3275:         return $response->content;
                   3276:     }
1.15      www      3277: }
1.254     www      3278: 
1.1172.2.98  raeburn  3279: # If the local copy of a replicated resource is outdated, trigger a
                   3280: # connection from the homeserver to flush the delayed queue. If no update
                   3281: # happens, remove local copies of outdated resource (and corresponding
                   3282: # metadata file).
                   3283: 
                   3284: sub remove_stale_resfile {
                   3285:     my ($url) = @_;
                   3286:     my $removed;
                   3287:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3288:         my $audom = $1;
                   3289:         my $auname = $2;
                   3290:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3291:             my $homeserver = &homeserver($auname,$audom);
                   3292:             unless (($homeserver eq 'no_host') ||
                   3293:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3294:                 my $fname = &filelocation('',$url);
                   3295:                 if (-e $fname) {
                   3296:                     my $hostname = &hostname($homeserver);
                   3297:                     if ($hostname) {
1.1172.2.120  raeburn  3298:                         my $protocol = $protocol{$homeserver};
                   3299:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3300:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3301:                         my $ua=new LWP::UserAgent;
                   3302:                         $ua->timeout(5);
1.1172.2.98  raeburn  3303:                         my $request=new HTTP::Request('HEAD',$uri);
                   3304:                         my $response=$ua->request($request);
                   3305:                         if ($response->is_success()) {
                   3306:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3307:                             my $locmodtime = (stat($fname))[9];
                   3308:                             if ($locmodtime < $remmodtime) {
                   3309:                                 my $stale;
                   3310:                                 my $answer = &reply('pong',$homeserver);
                   3311:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3312:                                     sleep(0.2);
                   3313:                                     $locmodtime = (stat($fname))[9];
                   3314:                                     if ($locmodtime < $remmodtime) {
                   3315:                                         my $posstransfer = $fname.'.in.transfer';
                   3316:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3317:                                             $removed = 1;
                   3318:                                         } else {
                   3319:                                             $stale = 1;
                   3320:                                         }
                   3321:                                     } else {
                   3322:                                         $removed = 1;
                   3323:                                     }
                   3324:                                 } else {
                   3325:                                     $stale = 1;
                   3326:                                 }
                   3327:                                 if ($stale) {
1.1172.2.124  raeburn  3328:                                     if (unlink($fname)) {
                   3329:                                         if ($uri!~/\.meta$/) {
                   3330:                                             if (-e $fname.'.meta') {
                   3331:                                                 unlink($fname.'.meta');
                   3332:                                             }
                   3333:                                         }
                   3334:                                         my $unsubresult = &unsubscribe($fname);
                   3335:                                         unless ($unsubresult eq 'ok') {
                   3336:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3337:                                         }
                   3338:                                         $removed = 1;
1.1172.2.98  raeburn  3339:                                     }
                   3340:                                 }
                   3341:                             }
                   3342:                         }
                   3343:                     }
                   3344:                 }
                   3345:             }
                   3346:         }
                   3347:     }
                   3348:     return $removed;
                   3349: }
                   3350: 
1.492     albertel 3351: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3352: 
                   3353: sub allowuploaded {
                   3354:     my ($srcurl,$url)=@_;
                   3355:     $url=&clutter(&declutter($url));
                   3356:     my $dir=$url;
                   3357:     $dir=~s/\/[^\/]+$//;
                   3358:     my %httpref=();
                   3359:     my $httpurl=&hreflocation('',$url);
                   3360:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3361:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3362: }
1.477     raeburn  3363: 
1.1172.2.13  raeburn  3364: #
                   3365: # Determine if the current user should be able to edit a particular resource,
                   3366: # when viewing in course context.
                   3367: # (a) When viewing resource used to determine if "Edit" item is included in
                   3368: #     Functions.
                   3369: # (b) When displaying folder contents in course editor, used to determine if
                   3370: #     "Edit" link will be displayed alongside resource.
                   3371: #
                   3372: #  input: six args -- filename (decluttered), course number, course domain,
                   3373: #                   url, symb (if registered) and group (if this is a group
                   3374: #                   item -- e.g., bulletin board, group page etc.).
                   3375: #  output: array of five scalars --
                   3376: #          $cfile -- url for file editing if editable on current server
                   3377: #          $home -- homeserver of resource (i.e., for author if published,
                   3378: #                                           or course if uploaded.).
                   3379: #          $switchserver --  1 if server switch will be needed.
                   3380: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3381: #          $forceview -- 1 if icon/link should be to go to view mode
                   3382: #
                   3383: 
                   3384: sub can_edit_resource {
                   3385:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3386:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3387: #
                   3388: # For aboutme pages user can only edit his/her own.
                   3389: #
                   3390:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3391:         my ($sdom,$sname) = ($1,$2);
                   3392:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3393:             $home = $env{'user.home'};
                   3394:             $cfile = $resurl;
                   3395:             if ($env{'form.forceedit'}) {
                   3396:                 $forceview = 1;
                   3397:             } else {
                   3398:                 $forceedit = 1;
                   3399:             }
                   3400:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3401:         } else {
                   3402:             return;
                   3403:         }
                   3404:     }
                   3405: 
                   3406:     if ($env{'request.course.id'}) {
                   3407:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3408:         if ($group ne '') {
                   3409: # if this is a group homepage or group bulletin board, check group privs
                   3410:             my $allowed = 0;
                   3411:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3412:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3413:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3414:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3415:                     $allowed = 1;
                   3416:                 }
                   3417:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3418:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3419:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3420:                     $allowed = 1;
                   3421:                 }
                   3422:             }
                   3423:             if ($allowed) {
                   3424:                 $home=&homeserver($cnum,$cdom);
                   3425:                 if ($env{'form.forceedit'}) {
                   3426:                     $forceview = 1;
                   3427:                 } else {
                   3428:                     $forceedit = 1;
                   3429:                 }
                   3430:                 $cfile = $resurl;
                   3431:             } else {
                   3432:                 return;
                   3433:             }
                   3434:         } else {
1.1172.2.15  raeburn  3435:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3436:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3437:                     return;
                   3438:                 }
                   3439:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3440: #
                   3441: # No edit allowed where CC has switched to student role.
                   3442: #
                   3443:                 return;
                   3444:             }
                   3445:         }
                   3446:     }
                   3447: 
                   3448:     if ($file ne '') {
                   3449:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3450:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3451:                 $uploaded = 1;
                   3452:                 $incourse = 1;
                   3453:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3454:                     $cfile = &hreflocation('',$file);
                   3455:                     if ($env{'form.forceedit'}) {
                   3456:                         $forceview = 1;
                   3457:                     } else {
                   3458:                         $forceedit = 1;
                   3459:                     }
                   3460:                 }
                   3461:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3462:                 $incourse = 1;
                   3463:                 if ($env{'form.forceedit'}) {
                   3464:                     $forceview = 1;
                   3465:                 } else {
                   3466:                     $forceedit = 1;
                   3467:                 }
                   3468:                 $cfile = $resurl;
                   3469:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3470:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3471:                     $incourse = 1;
                   3472:                     if ($env{'form.forceedit'}) {
                   3473:                         $forceview = 1;
                   3474:                     } else {
                   3475:                         $forceedit = 1;
                   3476:                     }
                   3477:                     $cfile = $resurl;
                   3478:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3479:                     $incourse = 1;
                   3480:                     $cfile = $resurl.'/smpedit';
                   3481:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3482:                     $incourse = 1;
                   3483:                     if ($env{'form.forceedit'}) {
                   3484:                         $forceview = 1;
                   3485:                     } else {
                   3486:                         $forceedit = 1;
                   3487:                     }
                   3488:                     $cfile = $resurl;
1.1172.2.122  raeburn  3489:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3490:                     my ($map,$id,$res) = &decode_symb($symb);
                   3491:                     if ($map =~ /\.page$/) {
                   3492:                         $incourse = 1;
                   3493:                         if ($env{'form.forceedit'}) {
                   3494:                             $forceview = 1;
                   3495:                             $cfile = $map;
                   3496:                         } else {
                   3497:                             $forceedit = 1;
                   3498:                             $cfile =  '/adm/wrapper'.$resurl;
                   3499:                         }
                   3500:                     }
1.1172.2.15  raeburn  3501:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3502:                     $incourse = 1;
                   3503:                     if ($env{'form.forceedit'}) {
                   3504:                         $forceview = 1;
                   3505:                     } else {
                   3506:                         $forceedit = 1;
                   3507:                     }
                   3508:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3509:                 }
                   3510:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3511:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3512:                 if (&is_on_map($template)) {
                   3513:                     $incourse = 1;
                   3514:                     $forceview = 1;
                   3515:                     $cfile = $template;
                   3516:                 }
                   3517:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3518:                 $incourse = 1;
                   3519:                 if ($env{'form.forceedit'}) {
                   3520:                     $forceview = 1;
                   3521:                 } else {
                   3522:                     $forceedit = 1;
                   3523:                 }
                   3524:                 $cfile = $resurl;
1.1172.2.13  raeburn  3525:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3526:                 $incourse = 1;
                   3527:                 $forceview = 1;
                   3528:                 if ($symb) {
                   3529:                     my ($map,$id,$res)=&decode_symb($symb);
                   3530:                     $env{'request.symb'} = $symb;
                   3531:                     $cfile = &clutter($res);
                   3532:                 } else {
                   3533:                     $cfile = $env{'form.suppurl'};
                   3534:                     $cfile =~ s{^http://}{};
                   3535:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3536:                 }
1.1172.2.31  raeburn  3537:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3538:                 if ($env{'form.forceedit'}) {
                   3539:                     $forceview = 1;
                   3540:                 } else {
                   3541:                     $forceedit = 1;
                   3542:                 }
                   3543:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3544:             }
                   3545:         }
                   3546:         if ($uploaded || $incourse) {
                   3547:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3548:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3549:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3550:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3551:             # Check that the user has permission to edit this resource
                   3552:             my $setpriv = 1;
                   3553:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3554:             if (defined($cfudom)) {
                   3555:                 $home=&homeserver($cfuname,$cfudom);
                   3556:                 $cfile=$file;
                   3557:             }
                   3558:         }
                   3559:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3560:             (($home ne '') && ($home ne 'no_host'))) {
                   3561:             my @ids=&current_machine_ids();
                   3562:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3563:                 $switchserver=1;
                   3564:             }
                   3565:         }
                   3566:     }
                   3567:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3568: }
                   3569: 
                   3570: sub is_course_upload {
                   3571:     my ($file,$cnum,$cdom) = @_;
                   3572:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3573:     $uploadpath =~ s{^\/}{};
                   3574:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3575:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3576:         return 1;
                   3577:     }
                   3578:     return;
                   3579: }
                   3580: 
                   3581: sub in_course {
                   3582:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3583:     if ($hideprivileged) {
                   3584:         my $skipuser;
1.1172.2.23  raeburn  3585:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3586:         my @possdoms = ($cdom);
                   3587:         if ($coursehash{'checkforpriv'}) {
                   3588:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3589:         }
                   3590:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3591:             $skipuser = 1;
                   3592:             if ($coursehash{'nothideprivileged'}) {
                   3593:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3594:                     my $user;
                   3595:                     if ($item =~ /:/) {
                   3596:                         $user = $item;
                   3597:                     } else {
                   3598:                         $user = join(':',split(/[\@]/,$item));
                   3599:                     }
                   3600:                     if ($user eq $uname.':'.$udom) {
                   3601:                         undef($skipuser);
                   3602:                         last;
                   3603:                     }
                   3604:                 }
                   3605:             }
                   3606:             if ($skipuser) {
                   3607:                 return 0;
                   3608:             }
                   3609:         }
                   3610:     }
                   3611:     $type ||= 'any';
                   3612:     if (!defined($cdom) || !defined($cnum)) {
                   3613:         my $cid  = $env{'request.course.id'};
                   3614:         $cdom = $env{'course.'.$cid.'.domain'};
                   3615:         $cnum = $env{'course.'.$cid.'.num'};
                   3616:     }
                   3617:     my $typesref;
                   3618:     if (($type eq 'any') || ($type eq 'all')) {
                   3619:         $typesref = ['active','previous','future'];
                   3620:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3621:         $typesref = [$type];
                   3622:     }
                   3623:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3624:                               $typesref,undef,[$cdom]);
                   3625:     my ($tmp) = keys(%roles);
                   3626:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3627:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3628:     if (@course_roles > 0) {
                   3629:         return 1;
                   3630:     }
                   3631:     return 0;
                   3632: }
                   3633: 
1.478     albertel 3634: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3635: # input: action, courseID, current domain, intended
1.637     raeburn  3636: #        path to file, source of file, instruction to parse file for objects,
                   3637: #        ref to hash for embedded objects,
                   3638: #        ref to hash for codebase of java objects.
1.1095    raeburn  3639: #        reference to scalar to accommodate mime type determined
                   3640: #          from File::MMagic if $parser = parse.
1.637     raeburn  3641: #
1.485     raeburn  3642: # output: url to file (if action was uploaddoc), 
                   3643: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3644: #
1.478     albertel 3645: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3646: # course.
1.477     raeburn  3647: #
1.478     albertel 3648: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3649: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3650: #          course's home server.
1.477     raeburn  3651: #
1.478     albertel 3652: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3653: #          be copied from $source (current location) to 
                   3654: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3655: #         and will then be copied to
                   3656: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3657: #         course's home server.
1.485     raeburn  3658: #
1.481     raeburn  3659: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3660: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3661: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3662: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3663: #         in course's home server.
1.637     raeburn  3664: #
1.477     raeburn  3665: 
                   3666: sub process_coursefile {
1.1095    raeburn  3667:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3668:         $mimetype)=@_;
1.477     raeburn  3669:     my $fetchresult;
1.638     albertel 3670:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3671:     if ($action eq 'propagate') {
1.638     albertel 3672:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3673: 			     $home);
1.481     raeburn  3674:     } else {
1.477     raeburn  3675:         my $fpath = '';
                   3676:         my $fname = $file;
1.478     albertel 3677:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3678:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3679:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3680:         if ($action eq 'copy') {
                   3681:             if ($source eq '') {
                   3682:                 $fetchresult = 'no source file';
                   3683:                 return $fetchresult;
                   3684:             } else {
                   3685:                 my $destination = $filepath.'/'.$fname;
                   3686:                 rename($source,$destination);
                   3687:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3688:                                  $home);
1.481     raeburn  3689:             }
                   3690:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3691:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3692:             print $fh $env{'form.'.$source};
1.481     raeburn  3693:             close($fh);
1.637     raeburn  3694:             if ($parser eq 'parse') {
1.1024    raeburn  3695:                 my $mm = new File::MMagic;
1.1095    raeburn  3696:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3697:                 if ($type eq 'text/html') {
1.1024    raeburn  3698:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3699:                     unless ($parse_result eq 'ok') {
                   3700:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3701:                     }
1.637     raeburn  3702:                 }
1.1095    raeburn  3703:                 if (ref($mimetype)) {
                   3704:                     $$mimetype = $type;
                   3705:                 } 
1.637     raeburn  3706:             }
1.477     raeburn  3707:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3708:                                  $home);
1.481     raeburn  3709:             if ($fetchresult eq 'ok') {
                   3710:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3711:             } else {
                   3712:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3713:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3714:                 return '/adm/notfound.html';
                   3715:             }
1.477     raeburn  3716:         }
                   3717:     }
1.485     raeburn  3718:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3719:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3720:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3721:     }
                   3722:     return $fetchresult;
                   3723: }
                   3724: 
1.637     raeburn  3725: sub build_filepath {
                   3726:     my ($fpath) = @_;
                   3727:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3728:     unless ($fpath eq '') {
                   3729:         my @parts=split('/',$fpath);
                   3730:         foreach my $part (@parts) {
                   3731:             $filepath.= '/'.$part;
                   3732:             if ((-e $filepath)!=1) {
                   3733:                 mkdir($filepath,0777);
                   3734:             }
                   3735:         }
                   3736:     }
                   3737:     return $filepath;
                   3738: }
                   3739: 
                   3740: sub store_edited_file {
1.638     albertel 3741:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3742:     my $file = $primary_url;
                   3743:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3744:     my $fpath = '';
                   3745:     my $fname = $file;
                   3746:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3747:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3748:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3749:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3750:     print $fh $content;
                   3751:     close($fh);
1.638     albertel 3752:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3753:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3754: 			  $home);
1.637     raeburn  3755:     if ($$fetchresult eq 'ok') {
                   3756:         return '/uploaded/'.$fpath.'/'.$fname;
                   3757:     } else {
1.638     albertel 3758:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3759: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3760:         return '/adm/notfound.html';
                   3761:     }
                   3762: }
                   3763: 
1.531     albertel 3764: sub clean_filename {
1.831     albertel 3765:     my ($fname,$args)=@_;
1.315     www      3766: # Replace Windows backslashes by forward slashes
1.257     www      3767:     $fname=~s/\\/\//g;
1.831     albertel 3768:     if (!$args->{'keep_path'}) {
                   3769:         # Get rid of everything but the actual filename
                   3770: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3771:     }
1.315     www      3772: # Replace spaces by underscores
                   3773:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3774: # Transliterate non-ascii text to ascii
                   3775:     my $lang = &Apache::lonlocal::current_language();
                   3776:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3777: # Replace all other weird characters by nothing
1.831     albertel 3778:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3779: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3780: # numbers
                   3781:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3782: # Replace three or more adjacent underscores with one for consistency
                   3783: # with loncfile::filename_check() so complete url can be extracted by
                   3784: # lonnet::decode_symb()
                   3785:     $fname=~s/_{3,}/_/g;
1.531     albertel 3786:     return $fname;
                   3787: }
1.1172.2.110  raeburn  3788: 
1.1051    raeburn  3789: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3790: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3791: # image with the same aspect ratio as the original, but with dimensions which do 
                   3792: # not exceed $resizewidth and $resizeheight.
                   3793:  
1.984     neumanie 3794: sub resizeImage {
1.1051    raeburn  3795:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3796:     my $ima = Image::Magick->new;
                   3797:     my $resized;
                   3798:     if (-e $img_path) {
                   3799:         $ima->Read($img_path);
                   3800:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3801:             my $width = $ima->Get('width');
                   3802:             my $height = $ima->Get('height');
                   3803:             if ($width > $resizewidth) {
                   3804: 	        my $factor = $width/$resizewidth;
                   3805:                 my $newheight = $height/$factor;
                   3806:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3807:                 $resized = 1;
                   3808:             }
                   3809:         }
                   3810:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3811:             my $width = $ima->Get('width');
                   3812:             my $height = $ima->Get('height');
                   3813:             if ($height > $resizeheight) {
                   3814:                 my $factor = $height/$resizeheight;
                   3815:                 my $newwidth = $width/$factor;
                   3816:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3817:                 $resized = 1;
                   3818:             }
                   3819:         }
                   3820:         if ($resized) {
                   3821:             $ima->Write($img_path);
                   3822:         }
                   3823:     }
                   3824:     return;
1.977     amueller 3825: }
                   3826: 
1.608     albertel 3827: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3828: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3829: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3830: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3831: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3832: #                   if 'coursedoc': upload to the current course
                   3833: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3834: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3835: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3836: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3837: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3838: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3839: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3840: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3841: #        $allfiles - reference to hash for embedded objects
                   3842: #        $codebase - reference to hash for codebase of java objects
                   3843: #        $desuname - username for permanent storage of uploaded file
                   3844: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3845: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3846: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3847: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3848: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3849: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3850: #                    from File::MMagic.
1.858     raeburn  3851: # 
1.686     albertel 3852: # output: url of file in userspace, or error: <message> 
                   3853: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3854: 
1.531     albertel 3855: sub userfileupload {
1.1090    raeburn  3856:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3857:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3858:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3859:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3860:     $fname=&clean_filename($fname);
1.1090    raeburn  3861:     # See if there is anything left
1.257     www      3862:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3863:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3864:     if ($fname =~ /^\./) {
                   3865:         my ($s,$usec) = &gettimeofday();
                   3866:         while (length($usec) < 6) {
                   3867:             $usec = '0'.$usec;
                   3868:         }
                   3869:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3870:     }
1.1090    raeburn  3871:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3872:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3873:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3874:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3875:         my $now = time;
1.1090    raeburn  3876:         my $filepath;
1.1095    raeburn  3877:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3878:              $filepath = 'tmp/helprequests/'.$now;
                   3879:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3880:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3881:                          '_'.$env{'user.domain'}.'/pending';
                   3882:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3883:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3884:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3885:                 $docudom = $destudom;
                   3886:             } else {
                   3887:                 $docudom = $env{'user.domain'};
                   3888:             }
1.1172.2.96  raeburn  3889:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3890:                 $docuname = $destuname;
                   3891:             } else {
                   3892:                 $docuname = $env{'user.name'};
                   3893:             }
                   3894:             if (exists($env{'form.group'})) {
                   3895:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3896:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3897:             }
                   3898:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3899:             if ($context eq 'canceloverwrite') {
                   3900:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3901:                 if (-e  $tempfile) {
                   3902:                     my @info = stat($tempfile);
                   3903:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3904:                         unlink($tempfile);
                   3905:                     }
                   3906:                 }
                   3907:                 return;
1.523     raeburn  3908:             }
                   3909:         }
1.1090    raeburn  3910:         # Create the directory if not present
1.741     raeburn  3911:         my @parts=split(/\//,$filepath);
                   3912:         my $fullpath = $perlvar{'lonDaemons'};
                   3913:         for (my $i=0;$i<@parts;$i++) {
                   3914:             $fullpath .= '/'.$parts[$i];
                   3915:             if ((-e $fullpath)!=1) {
                   3916:                 mkdir($fullpath,0777);
                   3917:             }
                   3918:         }
1.1172.2.96  raeburn  3919:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3920:         print $fh $env{'form.'.$formname};
                   3921:         close($fh);
1.1090    raeburn  3922:         if ($context eq 'existingfile') {
                   3923:             my @info = stat($fullpath.'/'.$fname);
                   3924:             return ($fullpath.'/'.$fname,$info[9]);
                   3925:         } else {
                   3926:             return $fullpath.'/'.$fname;
                   3927:         }
1.523     raeburn  3928:     }
1.995     raeburn  3929:     if ($subdir eq 'scantron') {
                   3930:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3931:     } else {
1.995     raeburn  3932:         $fname="$subdir/$fname";
                   3933:     }
1.1090    raeburn  3934:     if ($context eq 'coursedoc') {
1.638     albertel 3935: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3936: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3937:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3938:             return &finishuserfileupload($docuname,$docudom,
                   3939: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3940: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3941:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3942:         } else {
1.1172.2.21  raeburn  3943:             if ($env{'form.folder'}) {
                   3944:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3945:             }
1.638     albertel 3946:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3947: 				       $fname,$formname,$parser,
1.1095    raeburn  3948: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3949:         }
1.719     banghart 3950:     } elsif (defined($destuname)) {
                   3951:         my $docuname=$destuname;
                   3952:         my $docudom=$destudom;
1.860     raeburn  3953: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3954: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3955:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3956:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3957:     } else {
1.638     albertel 3958:         my $docuname=$env{'user.name'};
                   3959:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3960:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3961:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3962:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3963:         }
1.860     raeburn  3964: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3965: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3966:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3967:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3968:     }
1.271     www      3969: }
                   3970: 
                   3971: sub finishuserfileupload {
1.860     raeburn  3972:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3973:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3974:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3975:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3976:   
1.860     raeburn  3977:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3978:     $file=$fname;
                   3979:     if ($fname=~m|/|) {
                   3980:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3981: 	$path.=$fnamepath.'/';
                   3982:     }
1.259     www      3983:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3984:     my $count;
                   3985:     for ($count=4;$count<=$#parts;$count++) {
                   3986:         $filepath.="/$parts[$count]";
                   3987:         if ((-e $filepath)!=1) {
                   3988: 	    mkdir($filepath,0777);
                   3989:         }
                   3990:     }
1.984     neumanie 3991: 
1.258     www      3992: # Save the file
                   3993:     {
1.1172.2.96  raeburn  3994: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3995: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3996: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3997: 	    return '/adm/notfound.html';
                   3998: 	}
1.1090    raeburn  3999:         if ($context eq 'overwrite') {
1.1117    foxr     4000:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4001:             my $target = $filepath.'/'.$file;
                   4002:             if (-e $source) {
                   4003:                 my @info = stat($source);
                   4004:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4005:                     unless (&File::Copy::move($source,$target)) {
                   4006:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4007:                         return "Moving from $source failed";
                   4008:                     }
                   4009:                 } else {
                   4010:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4011:                 }
                   4012:             } else {
                   4013:                 return "Temporary file: $source missing";
                   4014:             }
                   4015:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4016: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4017: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4018: 	    return '/adm/notfound.html';
                   4019: 	}
1.570     albertel 4020: 	close(FH);
1.1051    raeburn  4021:         if ($resizewidth && $resizeheight) {
                   4022:             my $mm = new File::MMagic;
                   4023:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4024:             if ($mime_type =~ m{^image/}) {
                   4025: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4026:             }  
1.977     amueller 4027: 	}
1.258     www      4028:     }
1.1152    raeburn  4029:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4030:         if (ref($mimetype)) {
                   4031:             if ($$mimetype eq '') {
                   4032:                 my $mm = new File::MMagic;
                   4033:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4034:                 $$mimetype = $type;
                   4035:             }
                   4036:         }
                   4037:     }
1.1172.2.109  raeburn  4038:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4039:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4040:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4041:                                                        $allfiles,$codebase);
                   4042:             unless ($parse_result eq 'ok') {
                   4043:                 &logthis('Failed to parse '.$filepath.$file.
                   4044: 	   	         ' for embedded media: '.$parse_result); 
                   4045:             }
1.637     raeburn  4046:         }
1.1172.2.109  raeburn  4047:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4048:         my $format = $env{'form.scantron_format'};
                   4049:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4050:     }
1.860     raeburn  4051:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4052:         my $input = $filepath.'/'.$file;
                   4053:         my $output = $filepath.'/'.'tn-'.$file;
                   4054:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4055:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4056:         system({$args[0]} @args);
1.860     raeburn  4057:         if (-e $filepath.'/'.'tn-'.$file) {
                   4058:             $fetchthumb  = 1; 
                   4059:         }
                   4060:     }
1.858     raeburn  4061:  
1.259     www      4062: # Notify homeserver to grep it
                   4063: #
1.984     neumanie 4064:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4065:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4066:     if ($fetchresult eq 'ok') {
1.860     raeburn  4067:         if ($fetchthumb) {
                   4068:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4069:             if ($thumbresult ne 'ok') {
                   4070:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4071:                          $docuhome.': '.$thumbresult);
                   4072:             }
                   4073:         }
1.259     www      4074: #
1.258     www      4075: # Return the URL to it
1.494     albertel 4076:         return '/uploaded/'.$path.$file;
1.263     www      4077:     } else {
1.494     albertel 4078:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4079: 		 ': '.$fetchresult);
1.263     www      4080:         return '/adm/notfound.html';
1.858     raeburn  4081:     }
1.493     albertel 4082: }
                   4083: 
1.637     raeburn  4084: sub extract_embedded_items {
1.961     raeburn  4085:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4086:     my @state = ();
1.1164    raeburn  4087:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4088:     my %javafiles = (
                   4089:                       codebase => '',
                   4090:                       code => '',
                   4091:                       archive => ''
                   4092:                     );
                   4093:     my %mediafiles = (
                   4094:                       src => '',
                   4095:                       movie => '',
                   4096:                      );
1.648     raeburn  4097:     my $p;
                   4098:     if ($content) {
                   4099:         $p = HTML::LCParser->new($content);
                   4100:     } else {
1.961     raeburn  4101:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4102:     }
1.641     albertel 4103:     while (my $t=$p->get_token()) {
1.640     albertel 4104: 	if ($t->[0] eq 'S') {
                   4105: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4106: 	    push(@state, $tagname);
1.648     raeburn  4107:             if (lc($tagname) eq 'allow') {
                   4108:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4109:             }
1.640     albertel 4110: 	    if (lc($tagname) eq 'img') {
                   4111: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4112: 	    }
1.886     albertel 4113: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4114:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4115: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4116:                 }
1.886     albertel 4117: 	    }
1.645     raeburn  4118:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4119:                 my $src;
1.645     raeburn  4120:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4121:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4122:                 } else {
1.1164    raeburn  4123:                     if ($attr->{'src'} ne '') {
                   4124:                         $src = $attr->{'src'};
                   4125:                         &add_filetype($allfiles,$src,'src');
                   4126:                     }
                   4127:                 }
                   4128:                 my $text = $p->get_trimmed_text();
                   4129:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4130:                     my @swfargs = split(/,/,$1);
                   4131:                     foreach my $item (@swfargs) {
                   4132:                         $item =~ s/["']//g;
                   4133:                         $item =~ s/^\s+//;
                   4134:                         $item =~ s/\s+$//;
                   4135:                     }
                   4136:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4137:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4138:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4139:                         } else {
                   4140:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4141:                         }
                   4142:                     }
1.645     raeburn  4143:                 }
                   4144:             }
                   4145:             if (lc($tagname) eq 'link') {
                   4146:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4147:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4148:                 }
                   4149:             }
1.640     albertel 4150: 	    if (lc($tagname) eq 'object' ||
                   4151: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4152: 		foreach my $item (keys(%javafiles)) {
                   4153: 		    $javafiles{$item} = '';
                   4154: 		}
1.1164    raeburn  4155:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4156:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4157:                 }
1.640     albertel 4158: 	    }
                   4159: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4160: 		my $name = lc($attr->{'name'});
                   4161: 		foreach my $item (keys(%javafiles)) {
                   4162: 		    if ($name eq $item) {
                   4163: 			$javafiles{$item} = $attr->{'value'};
                   4164: 			last;
                   4165: 		    }
                   4166: 		}
1.1164    raeburn  4167:                 my $pathfrom;
1.640     albertel 4168: 		foreach my $item (keys(%mediafiles)) {
                   4169: 		    if ($name eq $item) {
1.1164    raeburn  4170:                         $pathfrom = $attr->{'value'};
                   4171:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4172: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4173: 			last;
                   4174: 		    }
                   4175: 		}
1.1164    raeburn  4176:                 if ($name eq 'flashvars') {
                   4177:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4178:                 }
                   4179:                 if ($pathfrom ne '') {
                   4180:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4181:                                          $pathfrom);
                   4182:                 }
1.640     albertel 4183: 	    }
                   4184: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4185: 		foreach my $item (keys(%javafiles)) {
                   4186: 		    if ($attr->{$item}) {
                   4187: 			$javafiles{$item} = $attr->{$item};
                   4188: 			last;
                   4189: 		    }
                   4190: 		}
                   4191: 		foreach my $item (keys(%mediafiles)) {
                   4192: 		    if ($attr->{$item}) {
                   4193: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4194: 			last;
                   4195: 		    }
                   4196: 		}
1.1164    raeburn  4197:                 if (lc($tagname) eq 'embed') {
                   4198:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4199:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4200:                                              $attr->{'src'});
                   4201:                     }
                   4202:                 }
1.640     albertel 4203: 	    }
1.1172.2.35  raeburn  4204:             if (lc($tagname) eq 'iframe') {
                   4205:                 my $src = $attr->{'src'} ;
                   4206:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4207:                     &add_filetype($allfiles,$src,'src');
                   4208:                 } elsif ($src =~ m{^/}) {
                   4209:                     if ($env{'request.course.id'}) {
                   4210:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4211:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4212:                         my $url = &hreflocation('',$fullpath);
                   4213:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4214:                             my $relpath = $1;
                   4215:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4216:                                 &add_filetype($allfiles,$1,'src');
                   4217:                             }
                   4218:                         }
                   4219:                     }
                   4220:                 }
                   4221:             }
1.1164    raeburn  4222:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4223:                 pop(@state);
1.1164    raeburn  4224:             }
1.640     albertel 4225: 	} elsif ($t->[0] eq 'E') {
                   4226: 	    my ($tagname) = ($t->[1]);
                   4227: 	    if ($javafiles{'codebase'} ne '') {
                   4228: 		$javafiles{'codebase'} .= '/';
                   4229: 	    }  
                   4230: 	    if (lc($tagname) eq 'applet' ||
                   4231: 		lc($tagname) eq 'object' ||
                   4232: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4233: 		) {
                   4234: 		foreach my $item (keys(%javafiles)) {
                   4235: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4236: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4237: 			&add_filetype($allfiles,$file,$item);
                   4238: 		    }
                   4239: 		}
                   4240: 	    } 
                   4241: 	    pop @state;
                   4242: 	}
                   4243:     }
1.1164    raeburn  4244:     foreach my $id (sort(keys(%flashvars))) {
                   4245:         if ($shockwave{$id} ne '') {
                   4246:             my @pairs = split(/\&/,$flashvars{$id});
                   4247:             foreach my $pair (@pairs) {
                   4248:                 my ($key,$value) = split(/\=/,$pair);
                   4249:                 if ($key eq 'thumb') {
                   4250:                     &add_filetype($allfiles,$value,$key);
                   4251:                 } elsif ($key eq 'content') {
                   4252:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4253:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4254:                     if ($ext ne '') {
                   4255:                         &add_filetype($allfiles,$path.$value,$ext);
                   4256:                     }
                   4257:                 }
                   4258:             }
                   4259:         }
                   4260:     }
1.637     raeburn  4261:     return 'ok';
                   4262: }
                   4263: 
1.639     albertel 4264: sub add_filetype {
                   4265:     my ($allfiles,$file,$type)=@_;
                   4266:     if (exists($allfiles->{$file})) {
                   4267: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4268: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4269: 	}
                   4270:     } else {
                   4271: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4272:     }
                   4273: }
                   4274: 
1.1164    raeburn  4275: sub embedded_dependency {
                   4276:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4277:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4278:         if (($identifier ne '') &&
                   4279:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4280:             ($pathfrom ne '')) {
                   4281:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4282:             foreach my $dep (@{$related->{$identifier}}) {
                   4283:                 &add_filetype($allfiles,$path.$dep,'object');
                   4284:             }
                   4285:         }
                   4286:     }
                   4287:     return;
                   4288: }
                   4289: 
1.1172.2.109  raeburn  4290: sub bubblesheet_converter {
                   4291:     my ($cdom,$fullpath,$config,$format) = @_;
                   4292:     if ((&domain($cdom) ne '') &&
                   4293:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4294:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4295:         my (%csvcols,%csvoptions);
                   4296:         if (ref($config->{'fields'}) eq 'HASH') {
                   4297:             %csvcols = %{$config->{'fields'}};
                   4298:         }
                   4299:         if (ref($config->{'options'}) eq 'HASH') {
                   4300:             %csvoptions = %{$config->{'options'}};
                   4301:         }
                   4302:         my %csvbynum = reverse(%csvcols);
                   4303:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4304:         if (keys(%scantronconf)) {
                   4305:             my %bynum = (
                   4306:                           $scantronconf{CODEstart} => 'CODEstart',
                   4307:                           $scantronconf{IDstart}   => 'IDstart',
                   4308:                           $scantronconf{PaperID}   => 'PaperID',
                   4309:                           $scantronconf{FirstName} => 'FirstName',
                   4310:                           $scantronconf{LastName}  => 'LastName',
                   4311:                           $scantronconf{Qstart}    => 'Qstart',
                   4312:                         );
                   4313:             my @ordered;
                   4314:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4315:                 push(@ordered,$bynum{$item});
                   4316:             }
                   4317:             my %mapstart = (
                   4318:                               CODEstart => 'CODE',
                   4319:                               IDstart   => 'ID',
                   4320:                               PaperID   => 'PaperID',
                   4321:                               FirstName => 'FirstName',
                   4322:                               LastName  => 'LastName',
                   4323:                               Qstart    => 'FirstQuestion',
                   4324:                            );
                   4325:             my %maplength = (
                   4326:                               CODEstart => 'CODElength',
                   4327:                               IDstart   => 'IDlength',
                   4328:                               PaperID   => 'PaperIDlength',
                   4329:                               FirstName => 'FirstNamelength',
                   4330:                               LastName  => 'LastNamelength',
                   4331:             );
                   4332:             if (open(my $fh,'<',$fullpath)) {
                   4333:                 my $output;
                   4334:                 my %lettdig = &letter_to_digits();
                   4335:                 my %diglett = reverse(%lettdig);
                   4336:                 my $numletts = scalar(keys(%lettdig));
                   4337:                 my $num = 0;
                   4338:                 while (my $line=<$fh>) {
                   4339:                     $num ++;
                   4340:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4341:                     $line =~ s{[\r\n]+$}{};
                   4342:                     my %found;
1.1172.2.143  raeburn  4343:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4344:                     my ($qstart,$record);
                   4345:                     for (my $i=0; $i<@values; $i++) {
                   4346:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4347:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4348:                             if ($values[$i] eq '') {
                   4349:                                 $values[$i] = $scantronconf{'Qoff'};
                   4350:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4351:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4352:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4353:                                 }
                   4354:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4355:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4356:                                     $values[$i] = $diglett{$values[$i]};
                   4357:                                 }
                   4358:                             } else {
                   4359:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4360:                                     my $digit;
                   4361:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4362:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4363:                                         if ($values[$i] eq 'J') {
                   4364:                                             $digit += $numletts;
                   4365:                                         }
                   4366:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4367:                                         $digit = $values[$i]-1;
                   4368:                                         if ($values[$i] eq '0') {
                   4369:                                             $digit += $numletts;
                   4370:                                         }
                   4371:                                     }
                   4372:                                     my $qval='';
                   4373:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4374:                                         if ($j == $digit) {
                   4375:                                             $qval .= $scantronconf{'Qon'};
                   4376:                                         } else {
                   4377:                                             $qval .= $scantronconf{'Qoff'};
                   4378:                                         }
                   4379:                                     }
                   4380:                                     $values[$i] = $qval;
                   4381:                                 }
                   4382:                             }
                   4383:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4384:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4385:                             }
                   4386:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4387:                             if ($numblank > 0) {
                   4388:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4389:                             }
                   4390:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4391:                                 $qstart = $i;
                   4392:                                 $found{$csvbynum{$i}} = $values[$i];
                   4393:                             } else {
                   4394:                                 $found{'FirstQuestion'} .= $values[$i];
                   4395:                             }
                   4396:                         } elsif (exists($csvbynum{$i})) {
                   4397:                             if ($csvoptions{'rem'}) {
                   4398:                                 $values[$i] =~ s/^\s+//;
                   4399:                             }
                   4400:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4401:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4402:                                     $values[$i] = '0'.$values[$i];
                   4403:                                 }
                   4404:                             }
                   4405:                             $found{$csvbynum{$i}} = $values[$i];
                   4406:                         }
                   4407:                     }
                   4408:                     foreach my $item (@ordered) {
                   4409:                         my $currlength = 1+length($record);
                   4410:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4411:                         if ($numspaces > 0) {
                   4412:                             $record .= (' ' x $numspaces);
                   4413:                         }
                   4414:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4415:                             unless ($item eq 'Qstart') {
                   4416:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4417:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4418:                                 }
                   4419:                             }
                   4420:                             $record .= $found{$mapstart{$item}};
                   4421:                         }
                   4422:                     }
                   4423:                     $output .= "$record\n";
                   4424:                 }
                   4425:                 close($fh);
                   4426:                 if ($output) {
                   4427:                     if (open(my $fh,'>',$fullpath)) {
                   4428:                         print $fh $output;
                   4429:                         close($fh);
                   4430:                     }
                   4431:                 }
                   4432:             }
                   4433:         }
                   4434:         return;
                   4435:     }
                   4436: }
                   4437: 
                   4438: sub letter_to_digits {
                   4439:     my %lettdig = (
                   4440:                     A => 1,
                   4441:                     B => 2,
                   4442:                     C => 3,
                   4443:                     D => 4,
                   4444:                     E => 5,
                   4445:                     F => 6,
                   4446:                     G => 7,
                   4447:                     H => 8,
                   4448:                     I => 9,
                   4449:                     J => 0,
                   4450:                   );
                   4451:     return %lettdig;
                   4452: }
                   4453: 
                   4454: sub get_scantron_config {
                   4455:     my ($which,$cdom) = @_;
                   4456:     my @lines = &get_scantronformat_file($cdom);
                   4457:     my %config;
                   4458:     #FIXME probably should move to XML it has already gotten a bit much now
                   4459:     foreach my $line (@lines) {
                   4460:         my ($name,$descrip)=split(/:/,$line);
                   4461:         if ($name ne $which ) { next; }
                   4462:         chomp($line);
                   4463:         my @config=split(/:/,$line);
                   4464:         $config{'name'}=$config[0];
                   4465:         $config{'description'}=$config[1];
                   4466:         $config{'CODElocation'}=$config[2];
                   4467:         $config{'CODEstart'}=$config[3];
                   4468:         $config{'CODElength'}=$config[4];
                   4469:         $config{'IDstart'}=$config[5];
                   4470:         $config{'IDlength'}=$config[6];
                   4471:         $config{'Qstart'}=$config[7];
                   4472:         $config{'Qlength'}=$config[8];
                   4473:         $config{'Qoff'}=$config[9];
                   4474:         $config{'Qon'}=$config[10];
                   4475:         $config{'PaperID'}=$config[11];
                   4476:         $config{'PaperIDlength'}=$config[12];
                   4477:         $config{'FirstName'}=$config[13];
                   4478:         $config{'FirstNamelength'}=$config[14];
                   4479:         $config{'LastName'}=$config[15];
                   4480:         $config{'LastNamelength'}=$config[16];
                   4481:         $config{'BubblesPerRow'}=$config[17];
                   4482:         last;
                   4483:     }
                   4484:     return %config;
                   4485: }
                   4486: 
                   4487: sub get_scantronformat_file {
                   4488:     my ($cdom) = @_;
                   4489:     if ($cdom eq '') {
                   4490:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4491:     }
                   4492:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4493:     my $gottab = 0;
                   4494:     my @lines;
                   4495:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4496:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4497:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4498:             if ($formatfile ne '-1') {
                   4499:                 @lines = split("\n",$formatfile,-1);
                   4500:                 $gottab = 1;
                   4501:             }
                   4502:         }
                   4503:     }
                   4504:     if (!$gottab) {
                   4505:         my $confname = $cdom.'-domainconfig';
                   4506:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4507:         my $formatfile = &getfile($default);
                   4508:         if ($formatfile ne '-1') {
                   4509:             @lines = split("\n",$formatfile,-1);
                   4510:             $gottab = 1;
                   4511:         }
                   4512:     }
                   4513:     if (!$gottab) {
                   4514:         my @domains = &current_machine_domains();
                   4515:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4516:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4517:                 @lines = <$fh>;
                   4518:                 close($fh);
                   4519:             }
                   4520:         } else {
                   4521:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4522:                 @lines = <$fh>;
                   4523:                 close($fh);
                   4524:             }
                   4525:         }
                   4526:     }
                   4527:     return @lines;
                   4528: }
                   4529: 
1.493     albertel 4530: sub removeuploadedurl {
1.984     neumanie 4531:     my ($url)=@_;	
                   4532:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4533:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4534: }
                   4535: 
                   4536: sub removeuserfile {
                   4537:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4538:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4539:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4540:     if ($result eq 'ok') {	
1.798     raeburn  4541:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4542:             my $metafile = $fname.'.meta';
                   4543:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4544: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 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.257     www      4553: }
1.15      www      4554: 
1.530     albertel 4555: sub mkdiruserfile {
                   4556:     my ($docuname,$docudom,$dir)=@_;
                   4557:     my $home=&homeserver($docuname,$docudom);
                   4558:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4559: }
                   4560: 
1.531     albertel 4561: sub renameuserfile {
                   4562:     my ($docuname,$docudom,$old,$new)=@_;
                   4563:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4564:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4565:                         &escape("$old").':'.&escape("$new"),$home);
                   4566:     if ($result eq 'ok') {
                   4567:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4568:             my $oldmeta = $old.'.meta';
                   4569:             my $newmeta = $new.'.meta';
                   4570:             my $metaresult = 
                   4571:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4572: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4573:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4574:             my $sqlresult = 
1.823     albertel 4575:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4576:                                         'portfolio_metadata',$group,
                   4577:                                         'delete');
1.798     raeburn  4578:         }
                   4579:     }
                   4580:     return $result;
1.531     albertel 4581: }
                   4582: 
1.14      www      4583: # ------------------------------------------------------------------------- Log
                   4584: 
                   4585: sub log {
                   4586:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4587:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4588: }
                   4589: 
                   4590: # ------------------------------------------------------------------ Course Log
1.352     www      4591: #
                   4592: # This routine flushes several buffers of non-mission-critical nature
                   4593: #
1.157     www      4594: 
                   4595: sub flushcourselogs {
1.352     www      4596:     &logthis('Flushing log buffers');
                   4597: #
                   4598: # course logs
                   4599: # This is a log of all transactions in a course, which can be used
                   4600: # for data mining purposes
                   4601: #
                   4602: # It also collects the courseid database, which lists last transaction
                   4603: # times and course titles for all courseids
                   4604: #
                   4605:     my %courseidbuffer=();
1.921     raeburn  4606:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4607:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4608: 		          &escape($courselogs{$crsid}),
                   4609: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4610: 	    delete $courselogs{$crsid};
                   4611:         } else {
                   4612:             &logthis('Failed to flush log buffer for '.$crsid);
                   4613:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4614:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4615:                         " exceeded maximum size, deleting.</font>");
                   4616:                delete $courselogs{$crsid};
                   4617:             }
1.352     www      4618:         }
1.920     raeburn  4619:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4620:             'description' => $coursedescrbuf{$crsid},
                   4621:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4622:             'type'        => $coursetypebuf{$crsid},
                   4623:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4624:         };
1.191     harris41 4625:     }
1.352     www      4626: #
                   4627: # Write course id database (reverse lookup) to homeserver of courses 
                   4628: # Is used in pickcourse
                   4629: #
1.840     albertel 4630:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4631:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4632:                                     $courseidbuffer{$crs_home},
                   4633:                                     $crs_home,'timeonly');
1.352     www      4634:     }
                   4635: #
                   4636: # File accesses
                   4637: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4638: #
1.449     matthew  4639:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4640:         if ($entry =~ /___count$/) {
                   4641:             my ($dom,$name);
1.807     albertel 4642:             ($dom,$name,undef)=
1.811     albertel 4643: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4644:             if (! defined($dom) || $dom eq '' || 
                   4645:                 ! defined($name) || $name eq '') {
1.620     albertel 4646:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4647: #
                   4648: # FIXME 11/29/2021
                   4649: # Typo in rev. 1.458 (2003/12/09)??
                   4650: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4651: #
                   4652: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4653: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4654: # in a nohist_accesscount.db file for the user rather than the course.
                   4655: #
                   4656: # That said there is a lot of noise in the data being stored.
                   4657: # So counts for prtspool/  and adm/ etc. are recorded.
                   4658: #
                   4659: # A review of which items ending '___count' are written to %accesshash should likely be
                   4660: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4661: #
                   4662: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4663: # accesses for things which are not published resources, regardless of course, and
                   4664: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4665: # anyone in the course for things which are not published resources.
                   4666: #
                   4667: # For an author, nohist_accesscount.db ends up having records for other items
                   4668: # mixed up with the legitimate access counts for the author's published resources.
                   4669: #
1.620     albertel 4670:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4671:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4672:             }
1.450     matthew  4673:             my $value = $accesshash{$entry};
                   4674:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4675:             my %temphash=($url => $value);
1.449     matthew  4676:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4677:             if ($result eq 'ok') {
                   4678:                 delete $accesshash{$entry};
                   4679:             }
                   4680:         } else {
1.811     albertel 4681:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4682:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4683:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4684:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4685:                 delete $accesshash{$entry};
                   4686:             }
1.185     www      4687:         }
1.191     harris41 4688:     }
1.352     www      4689: #
                   4690: # Roles
                   4691: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4692: #
1.800     albertel 4693:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4694:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4695: 	    split(/\:/,$entry);
                   4696:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4697:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4698:                 $rudom,$runame) eq 'ok') {
                   4699: 	    delete $userrolehash{$entry};
                   4700:         }
                   4701:     }
1.662     raeburn  4702: #
1.1172.2.90  raeburn  4703: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4704: #
                   4705:     my %domrolebuffer = ();
1.1000    raeburn  4706:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4707:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4708:         if ($domrolebuffer{$rudom}) {
                   4709:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4710:                       '='.&escape($domainrolehash{$entry});
                   4711:         } else {
                   4712:             $domrolebuffer{$rudom}.=&escape($entry).
                   4713:                       '='.&escape($domainrolehash{$entry});
                   4714:         }
                   4715:         delete $domainrolehash{$entry};
                   4716:     }
                   4717:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4718:         my %servers;
                   4719:         if (defined(&domain($dom,'primary'))) {
                   4720:             my $primary=&domain($dom,'primary');
                   4721:             my $hostname=&hostname($primary);
                   4722:             $servers{$primary} = $hostname;
                   4723:         } else {
                   4724:             %servers = &get_servers($dom,'library');
                   4725:         }
1.841     albertel 4726: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4727: 	    if (&reply('domroleput:'.$dom.':'.
                   4728: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4729: 	        last;
                   4730: 	    } else {
1.841     albertel 4731: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4732: 	    }
1.662     raeburn  4733:         }
                   4734:     }
1.186     www      4735:     $dumpcount++;
1.157     www      4736: }
                   4737: 
                   4738: sub courselog {
                   4739:     my $what=shift;
1.158     www      4740:     $what=time.':'.$what;
1.620     albertel 4741:     unless ($env{'request.course.id'}) { return ''; }
                   4742:     $coursedombuf{$env{'request.course.id'}}=
                   4743:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4744:     $coursenumbuf{$env{'request.course.id'}}=
                   4745:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4746:     $coursehombuf{$env{'request.course.id'}}=
                   4747:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4748:     $coursedescrbuf{$env{'request.course.id'}}=
                   4749:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4750:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4751:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4752:     $courseownerbuf{$env{'request.course.id'}}=
                   4753:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4754:     $coursetypebuf{$env{'request.course.id'}}=
                   4755:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4756:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4757: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4758:     } else {
1.620     albertel 4759: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4760:     }
1.620     albertel 4761:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4762: 	&flushcourselogs();
                   4763:     }
1.158     www      4764: }
                   4765: 
                   4766: sub courseacclog {
                   4767:     my $fnsymb=shift;
1.620     albertel 4768:     unless ($env{'request.course.id'}) { return ''; }
                   4769:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4770:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4771:         $what.=':POST';
1.583     matthew  4772:         # FIXME: Probably ought to escape things....
1.800     albertel 4773: 	foreach my $key (keys(%env)) {
                   4774:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4775:                 my $formitem = $1;
                   4776:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4777:                     $what.=':'.$formitem.'='.$env{$key};
                   4778:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4779:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4780:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4781:                     } else {
                   4782:                         $what.=':'.$formitem.'='.$env{$key};
                   4783:                     }
1.975     raeburn  4784:                 }
1.158     www      4785:             }
1.191     harris41 4786:         }
1.583     matthew  4787:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4788:         # FIXME: We should not be depending on a form parameter that someone
                   4789:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4790:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4791:             $what.= ':POST';
                   4792:             # FIXME: Probably ought to escape things....
                   4793:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4794:                                  'crsdiscuss') {
1.620     albertel 4795:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4796:             }
                   4797:         }
1.158     www      4798:     }
                   4799:     &courselog($what);
1.149     www      4800: }
                   4801: 
1.185     www      4802: sub countacc {
                   4803:     my $url=&declutter(shift);
1.458     matthew  4804:     return if (! defined($url) || $url eq '');
1.620     albertel 4805:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4806: #
                   4807: # Mark that this url was used in this course
                   4808: #
1.620     albertel 4809:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4810: #
                   4811: # Increase the access count for this resource in this child process
                   4812: #
1.281     www      4813:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4814:     $accesshash{$key}++;
1.185     www      4815: }
1.349     www      4816: 
1.361     www      4817: sub linklog {
                   4818:     my ($from,$to)=@_;
                   4819:     $from=&declutter($from);
                   4820:     $to=&declutter($to);
                   4821:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4822:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4823: }
1.1160    www      4824: 
                   4825: sub statslog {
                   4826:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4827:     if ($users<2) { return; }
                   4828:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4829:             'course'       => $env{'request.course.id'},
                   4830:             'sections'     => '"all"',
                   4831:             'num_students' => $users,
                   4832:             'part'         => $part,
                   4833:             'symb'         => $symb,
                   4834:             'mean_tries'   => $av_attempts,
                   4835:             'deg_of_diff'  => $degdiff});
                   4836:     foreach my $key (keys(%dynstore)) {
                   4837:         $accesshash{$key}=$dynstore{$key};
                   4838:     }
                   4839: }
1.361     www      4840:   
1.349     www      4841: sub userrolelog {
                   4842:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4843:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4844:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4845:        $userrolehash
                   4846:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4847:                     =$tend.':'.$tstart;
1.662     raeburn  4848:     }
1.1169    droeschl 4849:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4850:        $userrolehash
                   4851:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4852:                     =$tend.':'.$tstart;
                   4853:     }
1.1172.2.90  raeburn  4854:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4855:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4856:        $domainrolehash
                   4857:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4858:                     = $tend.':'.$tstart;
                   4859:     }
1.351     www      4860: }
                   4861: 
1.957     raeburn  4862: sub courserolelog {
                   4863:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4864:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4865:         my $cdom = $1;
                   4866:         my $cnum = $2;
                   4867:         my $sec = $3;
                   4868:         my $namespace = 'rolelog';
                   4869:         my %storehash = (
                   4870:                            role    => $trole,
                   4871:                            start   => $tstart,
                   4872:                            end     => $tend,
                   4873:                            selfenroll => $selfenroll,
                   4874:                            context    => $context,
                   4875:                         );
                   4876:         if ($trole eq 'gr') {
                   4877:             $namespace = 'groupslog';
                   4878:             $storehash{'group'} = $sec;
                   4879:         } else {
                   4880:             $storehash{'section'} = $sec;
                   4881:         }
                   4882:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4883:                    $domain,$cnum,$cdom);
                   4884:         if (($trole ne 'st') || ($sec ne '')) {
                   4885:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4886:         }
                   4887:     }
                   4888:     return;
                   4889: }
                   4890: 
1.1172.2.9  raeburn  4891: sub domainrolelog {
                   4892:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4893:     if ($area =~ m{^/($match_domain)/$}) {
                   4894:         my $cdom = $1;
                   4895:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4896:         my $namespace = 'rolelog';
                   4897:         my %storehash = (
                   4898:                            role    => $trole,
                   4899:                            start   => $tstart,
                   4900:                            end     => $tend,
                   4901:                            context => $context,
                   4902:                         );
                   4903:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4904:                    $domain,$domconfiguser,$cdom);
                   4905:     }
                   4906:     return;
                   4907: 
                   4908: }
                   4909: 
                   4910: sub coauthorrolelog {
                   4911:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4912:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4913:         my $audom = $1;
                   4914:         my $auname = $2;
                   4915:         my $namespace = 'rolelog';
                   4916:         my %storehash = (
                   4917:                            role    => $trole,
                   4918:                            start   => $tstart,
                   4919:                            end     => $tend,
                   4920:                            context => $context,
                   4921:                         );
                   4922:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4923:                    $domain,$auname,$audom);
                   4924:     }
                   4925:     return;
                   4926: }
                   4927: 
1.351     www      4928: sub get_course_adv_roles {
1.948     raeburn  4929:     my ($cid,$codes) = @_;
1.620     albertel 4930:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4931:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4932:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4933:     my %nothide=();
1.800     albertel 4934:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4935:         if ($user !~ /:/) {
                   4936: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4937:         } else {
                   4938:             $nothide{$user}=1;
                   4939:         }
1.470     www      4940:     }
1.1172.2.23  raeburn  4941:     my @possdoms = ($coursehash{'domain'});
                   4942:     if ($coursehash{'checkforpriv'}) {
                   4943:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4944:     }
1.351     www      4945:     my %returnhash=();
                   4946:     my %dumphash=
                   4947:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4948:     my $now=time;
1.997     raeburn  4949:     my %privileged;
1.1000    raeburn  4950:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4951: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4952:         if (($tstart) && ($tstart<0)) { next; }
                   4953:         if (($tend) && ($tend<$now)) { next; }
                   4954:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4955:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4956: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4957:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4958:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4959: 	if ($role eq 'cr') { next; }
1.948     raeburn  4960:         if ($codes) {
                   4961:             if ($section) { $role .= ':'.$section; }
                   4962:             if ($returnhash{$role}) {
                   4963:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4964:             } else {
                   4965:                 $returnhash{$role}=$username.':'.$domain;
                   4966:             }
1.351     www      4967:         } else {
1.988     raeburn  4968:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4969:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4970:             if ($returnhash{$key}) {
                   4971: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4972:             } else {
                   4973:                 $returnhash{$key}=$username.':'.$domain;
                   4974:             }
1.351     www      4975:         }
1.948     raeburn  4976:     }
1.400     www      4977:     return %returnhash;
                   4978: }
                   4979: 
                   4980: sub get_my_roles {
1.937     raeburn  4981:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4982:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4983:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4984:     my (%dumphash,%nothide);
1.1086    raeburn  4985:     if ($context eq 'userroles') {
1.1166    raeburn  4986:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4987:     } else {
1.1172.2.23  raeburn  4988:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4989:         if ($hidepriv) {
                   4990:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4991:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4992:                 if ($user !~ /:/) {
                   4993:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4994:                 } else {
                   4995:                     $nothide{$user} = 1;
                   4996:                 }
                   4997:             }
                   4998:         }
1.858     raeburn  4999:     }
1.400     www      5000:     my %returnhash=();
                   5001:     my $now=time;
1.999     raeburn  5002:     my %privileged;
1.800     albertel 5003:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5004:         my ($role,$tend,$tstart);
                   5005:         if ($context eq 'userroles') {
1.1149    raeburn  5006:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5007: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5008:         } else {
                   5009:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5010:         }
1.400     www      5011:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5012:         my $status = 'active';
1.939     raeburn  5013:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5014:             $status = 'previous';
                   5015:         } 
                   5016:         if (($tstart) && ($now<$tstart)) {
                   5017:             $status = 'future';
                   5018:         }
                   5019:         if (ref($types) eq 'ARRAY') {
                   5020:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5021:                 next;
                   5022:             } 
                   5023:         } else {
                   5024:             if ($status ne 'active') {
                   5025:                 next;
                   5026:             }
                   5027:         }
1.867     raeburn  5028:         my ($rolecode,$username,$domain,$section,$area);
                   5029:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5030:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5031:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5032:         } else {
                   5033:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5034:         }
1.832     raeburn  5035:         if (ref($roledoms) eq 'ARRAY') {
                   5036:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5037:                 next;
                   5038:             }
                   5039:         }
                   5040:         if (ref($roles) eq 'ARRAY') {
                   5041:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5042:                 if ($role =~ /^cr\//) {
                   5043:                     if (!grep(/^cr$/,@{$roles})) {
                   5044:                         next;
                   5045:                     }
1.1104    raeburn  5046:                 } elsif ($role =~ /^gr\//) {
                   5047:                     if (!grep(/^gr$/,@{$roles})) {
                   5048:                         next;
                   5049:                     }
1.922     raeburn  5050:                 } else {
                   5051:                     next;
                   5052:                 }
1.832     raeburn  5053:             }
1.867     raeburn  5054:         }
1.937     raeburn  5055:         if ($hidepriv) {
1.1172.2.23  raeburn  5056:             my @privroles = ('dc','su');
1.999     raeburn  5057:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5058:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5059:             } else {
1.1172.2.23  raeburn  5060:                 my $possdoms = [$domain];
                   5061:                 if (ref($roledoms) eq 'ARRAY') {
                   5062:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5063:                 }
1.1172.2.23  raeburn  5064:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5065:                     if (!$nothide{$username.':'.$domain}) {
                   5066:                         next;
                   5067:                     }
                   5068:                 }
1.937     raeburn  5069:             }
                   5070:         }
1.933     raeburn  5071:         if ($withsec) {
                   5072:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5073:                 $tstart.':'.$tend;
                   5074:         } else {
                   5075:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5076:         }
1.832     raeburn  5077:     }
1.373     www      5078:     return %returnhash;
1.399     www      5079: }
                   5080: 
1.1172.2.89  raeburn  5081: sub get_all_adhocroles {
                   5082:     my ($dom) = @_;
                   5083:     my @roles_by_num = ();
                   5084:     my %domdefaults = &get_domain_defaults($dom);
                   5085:     my (%description,%access_in_dom,%access_info);
                   5086:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5087:         my $count = 0;
                   5088:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5089:         my %ordered;
                   5090:         foreach my $role (sort(keys(%domcurrent))) {
                   5091:             my ($order,$desc,$access_in_dom);
                   5092:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5093:                 $order = $domcurrent{$role}{'order'};
                   5094:                 $desc = $domcurrent{$role}{'desc'};
                   5095:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5096:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5097:             }
                   5098:             if ($order eq '') {
                   5099:                 $order = $count;
                   5100:             }
                   5101:             $ordered{$order} = $role;
                   5102:             if ($desc ne '') {
                   5103:                 $description{$role} = $desc;
                   5104:             } else {
                   5105:                 $description{$role}= $role;
                   5106:             }
                   5107:             $count++;
                   5108:         }
                   5109:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5110:             push(@roles_by_num,$ordered{$item});
                   5111:         }
                   5112:     }
                   5113:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5114: }
                   5115: 
                   5116: sub get_my_adhocroles {
                   5117:     my ($cid,$checkreg) = @_;
                   5118:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5119:     if ($env{'request.course.id'} eq $cid) {
                   5120:         $cdom = $env{'course.'.$cid.'.domain'};
                   5121:         $cnum = $env{'course.'.$cid.'.num'};
                   5122:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5123:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5124:         $cdom = $1;
                   5125:         $cnum = $2;
                   5126:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5127:                                      $cdom,$cnum);
                   5128:     }
                   5129:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5130:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5131:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5132:         if ($rosterhash{$user} ne '') {
                   5133:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5134:             return ([],{}) if ($type eq 'auto');
                   5135:         }
                   5136:     }
                   5137:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5138:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5139:             my $then=$env{'user.login.time'};
                   5140:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5141:             if (!$update) {
                   5142:                 $update = $then;
                   5143:             }
                   5144:             my @liveroles;
                   5145:             foreach my $role ('dh','da') {
                   5146:                 if ($env{"user.role.$role./$cdom/"}) {
                   5147:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5148:                     my $limit = $update;
                   5149:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5150:                         $limit = $then;
                   5151:                     }
                   5152:                     my $activerole = 1;
                   5153:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5154:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5155:                     if ($activerole) {
                   5156:                         push(@liveroles,$role);
                   5157:                     }
                   5158:                 }
                   5159:             }
                   5160:             if (@liveroles) {
1.1172.2.89  raeburn  5161:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5162:                     my ($accessref,$accessinfo,%access_in_dom);
                   5163:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5164:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5165:                         if (@{$roles_by_num}) {
                   5166:                             my %settings;
                   5167:                             if ($env{'request.course.id'} eq $cid) {
                   5168:                                 foreach my $envkey (keys(%env)) {
                   5169:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5170:                                         $settings{$1} = $env{$envkey};
                   5171:                                     }
                   5172:                                 }
                   5173:                             } else {
                   5174:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5175:                             }
                   5176:                             my %setincrs;
                   5177:                             if ($settings{'internal.adhocaccess'}) {
                   5178:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5179:                             }
                   5180:                             my @statuses;
                   5181:                             if ($env{'environment.inststatus'}) {
                   5182:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5183:                             }
                   5184:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5185:                             if (ref($accessref) eq 'HASH') {
                   5186:                                 %access_in_dom = %{$accessref};
                   5187:                             }
                   5188:                             foreach my $role (@{$roles_by_num}) {
                   5189:                                 my ($curraccess,@okstatus,@personnel);
                   5190:                                 if ($setincrs{$role}) {
                   5191:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5192:                                     if ($curraccess eq 'status') {
                   5193:                                         @okstatus = split(/\&/,$rest);
                   5194:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5195:                                         @personnel = split(/\&/,$rest);
                   5196:                                     }
                   5197:                                 } else {
                   5198:                                     $curraccess = $access_in_dom{$role};
                   5199:                                     if (ref($accessinfo) eq 'HASH') {
                   5200:                                         if ($curraccess eq 'status') {
                   5201:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5202:                                                 @okstatus = @{$accessinfo->{$role}};
                   5203:                                             }
                   5204:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5205:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5206:                                                 @personnel = @{$accessinfo->{$role}};
                   5207:                                             }
                   5208:                                         }
                   5209:                                     }
                   5210:                                 }
                   5211:                                 if ($curraccess eq 'none') {
                   5212:                                     next;
                   5213:                                 } elsif ($curraccess eq 'all') {
                   5214:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5215:                                 } elsif ($curraccess eq 'dh') {
                   5216:                                     if (grep(/^dh$/,@liveroles)) {
                   5217:                                         push(@possroles,$role);
                   5218:                                     } else {
                   5219:                                         next;
                   5220:                                     }
                   5221:                                 } elsif ($curraccess eq 'da') {
                   5222:                                     if (grep(/^da$/,@liveroles)) {
                   5223:                                         push(@possroles,$role);
                   5224:                                     } else {
                   5225:                                         next;
                   5226:                                     }
1.1172.2.89  raeburn  5227:                                 } elsif ($curraccess eq 'status') {
                   5228:                                     if (@okstatus) {
                   5229:                                         if (!@statuses) {
                   5230:                                             if (grep(/^default$/,@okstatus)) {
                   5231:                                                 push(@possroles,$role);
                   5232:                                             }
                   5233:                                         } else {
                   5234:                                             foreach my $status (@okstatus) {
                   5235:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5236:                                                     push(@possroles,$role);
                   5237:                                                     last;
                   5238:                                                 }
                   5239:                                             }
                   5240:                                         }
                   5241:                                     }
                   5242:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5243:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5244:                                         if ($curraccess eq 'exc') {
                   5245:                                             push(@possroles,$role);
                   5246:                                         }
                   5247:                                     } elsif ($curraccess eq 'inc') {
                   5248:                                         push(@possroles,$role);
                   5249:                                     }
                   5250:                                 }
                   5251:                             }
                   5252:                         }
                   5253:                     }
                   5254:                 }
                   5255:             }
                   5256:         }
                   5257:     }
                   5258:     unless (ref($description) eq 'HASH') {
                   5259:         if (ref($roles_by_num) eq 'ARRAY') {
                   5260:             my %desc;
                   5261:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5262:             $description = \%desc;
                   5263:         } else {
                   5264:             $description = {};
                   5265:         }
                   5266:     }
                   5267:     return (\@possroles,$description);
                   5268: }
                   5269: 
1.399     www      5270: # ----------------------------------------------------- Frontpage Announcements
                   5271: #
                   5272: #
                   5273: 
                   5274: sub postannounce {
                   5275:     my ($server,$text)=@_;
1.844     albertel 5276:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5277:     unless ($text=~/\w/) { $text=''; }
                   5278:     return &reply('setannounce:'.&escape($text),$server);
                   5279: }
                   5280: 
                   5281: sub getannounce {
1.448     albertel 5282: 
1.1172.2.96  raeburn  5283:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5284: 	my $announcement='';
1.800     albertel 5285: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5286: 	close($fh);
1.399     www      5287: 	if ($announcement=~/\w/) { 
                   5288: 	    return 
                   5289:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5290:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5291: 	} else {
                   5292: 	    return '';
                   5293: 	}
                   5294:     } else {
                   5295: 	return '';
                   5296:     }
1.351     www      5297: }
1.353     www      5298: 
                   5299: # ---------------------------------------------------------- Course ID routines
                   5300: # Deal with domain's nohist_courseid.db files
                   5301: #
                   5302: 
                   5303: sub courseidput {
1.921     raeburn  5304:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5305:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5306:     my $outcome;
                   5307:     if ($caller eq 'timeonly') {
                   5308:         my $cids = '';
                   5309:         foreach my $item (keys(%$storehash)) {
                   5310:             $cids.=&escape($item).'&';
                   5311:         }
                   5312:         $cids=~s/\&$//;
                   5313:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5314:                           $coursehome);       
                   5315:     } else {
                   5316:         my $items = '';
                   5317:         foreach my $item (keys(%$storehash)) {
                   5318:             $items.= &escape($item).'='.
                   5319:                      &freeze_escape($$storehash{$item}).'&';
                   5320:         }
                   5321:         $items=~s/\&$//;
                   5322:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5323:                           $coursehome);
1.918     raeburn  5324:     }
                   5325:     if ($outcome eq 'unknown_cmd') {
                   5326:         my $what;
                   5327:         foreach my $cid (keys(%$storehash)) {
                   5328:             $what .= &escape($cid).'=';
1.921     raeburn  5329:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5330:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5331:             }
                   5332:             $what =~ s/\:$/&/;
                   5333:         }
                   5334:         $what =~ s/\&$//;  
                   5335:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5336:     } else {
                   5337:         return $outcome;
                   5338:     }
1.353     www      5339: }
                   5340: 
                   5341: sub courseiddump {
1.921     raeburn  5342:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5343:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5344:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5345:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5346:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5347:     my $as_hash = 1;
                   5348:     my %returnhash;
                   5349:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5350:     my %libserv = &all_library();
                   5351:     foreach my $tryserver (keys(%libserv)) {
                   5352:         if ( (  $hostidflag == 1 
                   5353: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5354: 	     || (!defined($hostidflag)) ) {
                   5355: 
1.918     raeburn  5356: 	    if (($domfilter eq '') ||
                   5357: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5358:                 my $rep;
                   5359:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5360:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5361:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5362:                                 &escape($descfilter), &escape($instcodefilter),
                   5363:                                 &escape($ownerfilter), &escape($coursefilter),
                   5364:                                 &escape($typefilter), &escape($regexp_ok),
                   5365:                                 $as_hash, &escape($selfenrollonly),
                   5366:                                 &escape($catfilter), $showhidden, $caller,
                   5367:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5368:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5369:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5370:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5371:                 } else {
                   5372:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5373:                              $sincefilter.':'.&escape($descfilter).':'.
                   5374:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5375:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5376:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5377:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5378:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5379:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5380:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5381:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5382:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5383:                 }
                   5384: 
1.918     raeburn  5385:                 my @pairs=split(/\&/,$rep);
                   5386:                 foreach my $item (@pairs) {
                   5387:                     my ($key,$value)=split(/\=/,$item,2);
                   5388:                     $key = &unescape($key);
                   5389:                     next if ($key =~ /^error: 2 /);
                   5390:                     my $result = &thaw_unescape($value);
                   5391:                     if (ref($result) eq 'HASH') {
                   5392:                         $returnhash{$key}=$result;
                   5393:                     } else {
1.921     raeburn  5394:                         my @responses = split(/:/,$value);
                   5395:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5396:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5397:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5398:                         }
1.1008    raeburn  5399:                     }
1.353     www      5400:                 }
                   5401:             }
                   5402:         }
                   5403:     }
                   5404:     return %returnhash;
                   5405: }
                   5406: 
1.1055    raeburn  5407: sub courselastaccess {
                   5408:     my ($cdom,$cnum,$hostidref) = @_;
                   5409:     my %returnhash;
                   5410:     if ($cdom && $cnum) {
                   5411:         my $chome = &homeserver($cnum,$cdom);
                   5412:         if ($chome ne 'no_host') {
                   5413:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5414:             &extract_lastaccess(\%returnhash,$rep);
                   5415:         }
                   5416:     } else {
                   5417:         if (!$cdom) { $cdom=''; }
                   5418:         my %libserv = &all_library();
                   5419:         foreach my $tryserver (keys(%libserv)) {
                   5420:             if (ref($hostidref) eq 'ARRAY') {
                   5421:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5422:             } 
                   5423:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5424:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5425:                 &extract_lastaccess(\%returnhash,$rep);
                   5426:             }
                   5427:         }
                   5428:     }
                   5429:     return %returnhash;
                   5430: }
                   5431: 
                   5432: sub extract_lastaccess {
                   5433:     my ($returnhash,$rep) = @_;
                   5434:     if (ref($returnhash) eq 'HASH') {
                   5435:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5436:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5437:                  $rep eq '') {
                   5438:             my @pairs=split(/\&/,$rep);
                   5439:             foreach my $item (@pairs) {
                   5440:                 my ($key,$value)=split(/\=/,$item,2);
                   5441:                 $key = &unescape($key);
                   5442:                 next if ($key =~ /^error: 2 /);
                   5443:                 $returnhash->{$key} = &thaw_unescape($value);
                   5444:             }
                   5445:         }
                   5446:     }
                   5447:     return;
                   5448: }
                   5449: 
1.658     raeburn  5450: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5451: 
                   5452: sub dcmailput {
1.685     raeburn  5453:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5454:     my $status = &Apache::lonnet::critical(
1.740     www      5455:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5456:        &escape($message),$server);
1.662     raeburn  5457:     return $status;
                   5458: }
                   5459: 
1.658     raeburn  5460: sub dcmaildump {
                   5461:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5462:     my %returnhash=();
1.846     albertel 5463: 
                   5464:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5465:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5466:                                                          &escape($enddate).':';
                   5467: 	my @esc_senders=map { &escape($_)} @$senders;
                   5468: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5469: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5470:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5471:             if (($key) && ($value)) {
                   5472:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5473:             }
                   5474:         }
                   5475:     }
                   5476:     return %returnhash;
                   5477: }
1.662     raeburn  5478: # ---------------------------------------------------------- Domain roles
                   5479: 
                   5480: sub get_domain_roles {
                   5481:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5482:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5483:         $startdate = '.';
                   5484:     }
1.1018    raeburn  5485:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5486:         $enddate = '.';
                   5487:     }
1.922     raeburn  5488:     my $rolelist;
                   5489:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5490:         $rolelist = join('&',@{$roles});
1.922     raeburn  5491:     }
1.662     raeburn  5492:     my %personnel = ();
1.841     albertel 5493: 
                   5494:     my %servers = &get_servers($dom,'library');
                   5495:     foreach my $tryserver (keys(%servers)) {
                   5496: 	%{$personnel{$tryserver}}=();
                   5497: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5498: 					    &escape($startdate).':'.
                   5499: 					    &escape($enddate).':'.
                   5500: 					    &escape($rolelist), $tryserver))) {
                   5501: 	    my ($key,$value) = split(/\=/,$line,2);
                   5502: 	    if (($key) && ($value)) {
                   5503: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5504: 	    }
                   5505: 	}
1.662     raeburn  5506:     }
                   5507:     return %personnel;
                   5508: }
1.658     raeburn  5509: 
1.1172.2.89  raeburn  5510: sub get_active_domroles {
                   5511:     my ($dom,$roles) = @_;
                   5512:     return () unless (ref($roles) eq 'ARRAY');
                   5513:     my $now = time;
                   5514:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5515:     my %domroles;
                   5516:     foreach my $server (keys(%dompersonnel)) {
                   5517:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5518:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5519:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5520:         }
                   5521:     }
                   5522:     return %domroles;
                   5523: }
                   5524: 
1.1057    www      5525: # ----------------------------------------------------------- Interval timing 
1.149     www      5526: 
1.1153    www      5527: {
                   5528: # Caches needed for speedup of navmaps
                   5529: # We don't want to cache this for very long at all (5 seconds at most)
                   5530: # 
                   5531: # The user for whom we cache
                   5532: my $cachedkey='';
                   5533: # The cached times for this user
                   5534: my %cachedtimes=();
                   5535: # When this was last done
1.1172.2.66  raeburn  5536: my $cachedtime='';
1.1153    www      5537: 
                   5538: sub load_all_first_access {
1.1154    raeburn  5539:     my ($uname,$udom)=@_;
1.1156    www      5540:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5541:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5542:         return;
                   5543:     }
                   5544:     $cachedtime=time;
                   5545:     $cachedkey=$uname.':'.$udom;
                   5546:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5547: }
                   5548: 
1.504     albertel 5549: sub get_first_access {
1.1162    raeburn  5550:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5551:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5552:     if ($argsymb) { $symb=$argsymb; }
                   5553:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5554:     if ($argmap) { $map = $argmap; }
1.926     albertel 5555:     if ($type eq 'course') {
                   5556: 	$res='course';
                   5557:     } elsif ($type eq 'map') {
1.588     albertel 5558: 	$res=&symbread($map);
                   5559:     } else {
                   5560: 	$res=$symb;
                   5561:     }
1.1153    www      5562:     &load_all_first_access($uname,$udom);
                   5563:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5564: }
                   5565: 
                   5566: sub set_first_access {
1.1162    raeburn  5567:     my ($type,$interval)=@_;
1.790     albertel 5568:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5569:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5570:     if ($type eq 'course') {
                   5571: 	$res='course';
                   5572:     } elsif ($type eq 'map') {
1.588     albertel 5573: 	$res=&symbread($map);
                   5574:     } else {
                   5575: 	$res=$symb;
                   5576:     }
1.1153    www      5577:     $cachedkey='';
1.1162    raeburn  5578:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5579:     if ($firstaccess) {
                   5580:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5581:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5582:                  "in $courseid");
                   5583:         return 'already_set';
                   5584:     } else {
1.1162    raeburn  5585:         my $start = time;
                   5586: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5587:                           $udom,$uname);
                   5588:         if ($putres eq 'ok') {
                   5589:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5590:                  $udom,$uname); 
                   5591:             &appenv(
                   5592:                      {
                   5593:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5594:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5595:                      }
                   5596:                   );
1.1172.2.97  raeburn  5597:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5598:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5599:             }
1.1172.2.102  raeburn  5600:         } elsif ($putres ne 'refused') {
                   5601:             &logthis("Result: $putres when attempting to set first access time ".
                   5602:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5603:         }
                   5604:         return $putres;
1.505     albertel 5605:     }
                   5606:     return 'already_set';
1.504     albertel 5607: }
1.1153    www      5608: }
1.1172.2.32  raeburn  5609: 
                   5610: sub checkout {
                   5611:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5612:     my $now=time;
                   5613:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5614:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5615:     my $infostr=&escape(
                   5616:                  'CHECKOUTTOKEN&'.
                   5617:                  $tuname.'&'.
                   5618:                  $tudom.'&'.
                   5619:                  $tcrsid.'&'.
                   5620:                  $symb.'&'.
1.1172.2.134  raeburn  5621:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5622:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5623:     if ($token=~/^error\:/) {
                   5624:         &logthis("<font color=\"blue\">WARNING: ".
                   5625:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5626:                  "</font>");
                   5627:         return '';
                   5628:     }
                   5629: 
                   5630:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5631:     $token=~tr/a-z/A-Z/;
                   5632: 
                   5633:     my %infohash=('resource.0.outtoken' => $token,
                   5634:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5635:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5636: 
                   5637:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5638:        return '';
                   5639:     } else {
                   5640:         &logthis("<font color=\"blue\">WARNING: ".
                   5641:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5642:                  "</font>");
                   5643:     }
                   5644: 
                   5645:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5646:                          &escape('Checkout '.$infostr.' - '.
                   5647:                                                  $token)) ne 'ok') {
                   5648:         return '';
                   5649:     } else {
                   5650:         &logthis("<font color=\"blue\">WARNING: ".
                   5651:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5652:                  "</font>");
                   5653:     }
                   5654:     return $token;
                   5655: }
                   5656: 
                   5657: # ------------------------------------------------------------ Check in an item
                   5658: 
                   5659: sub checkin {
                   5660:     my $token=shift;
                   5661:     my $now=time;
                   5662:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5663:     $lonhost=~tr/A-Z/a-z/;
                   5664:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5665:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5666:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5667:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5668:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5669: 
                   5670:     unless (($tuname) && ($tudom)) {
                   5671:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5672:         return '';
                   5673:     }
                   5674: 
                   5675:     unless (&allowed('mgr',$tcrsid)) {
                   5676:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5677:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5678:         return '';
                   5679:     }
                   5680: 
                   5681:     my %infohash=('resource.0.intoken' => $token,
                   5682:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5683:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5684: 
                   5685:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5686:        return '';
                   5687:     }
                   5688: 
                   5689:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5690:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5691:         return '';
                   5692:     }
                   5693: 
                   5694:     return ($symb,$tuname,$tudom,$tcrsid);
                   5695: }
                   5696: 
1.110     www      5697: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5698: 
                   5699: sub expirespread {
                   5700:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5701:     my $cid=$env{'request.course.id'}; 
1.110     www      5702:     if ($cid) {
                   5703:        my $now=time;
                   5704:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5705:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5706:                             $env{'course.'.$cid.'.num'}.
1.110     www      5707: 	        	    ':nohist_expirationdates:'.
                   5708:                             &escape($key).'='.$now,
1.620     albertel 5709:                             $env{'course.'.$cid.'.home'})
1.110     www      5710:     }
                   5711:     return 'ok';
1.14      www      5712: }
                   5713: 
1.109     www      5714: # ----------------------------------------------------- Devalidate Spreadsheets
                   5715: 
                   5716: sub devalidate {
1.325     www      5717:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5718:     my $cid=$env{'request.course.id'}; 
1.109     www      5719:     if ($cid) {
1.391     matthew  5720:         # delete the stored spreadsheets for
                   5721:         # - the student level sheet of this user in course's homespace
                   5722:         # - the assessment level sheet for this resource 
                   5723:         #   for this user in user's homespace
1.553     albertel 5724: 	# - current conditional state info
1.325     www      5725: 	my $key=$uname.':'.$udom.':';
1.109     www      5726:         my $status=
1.299     matthew  5727: 	    &del('nohist_calculatedsheets',
1.391     matthew  5728: 		 [$key.'studentcalc:'],
1.620     albertel 5729: 		 $env{'course.'.$cid.'.domain'},
                   5730: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5731: 		.' '.
                   5732: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5733: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5734:         unless ($status eq 'ok ok') {
                   5735:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5736:                     $uname.' at '.$udom.' for '.
1.109     www      5737: 		    $symb.': '.$status);
1.133     albertel 5738:         }
1.553     albertel 5739: 	&delenv('user.state.'.$cid);
1.109     www      5740:     }
                   5741: }
                   5742: 
1.265     albertel 5743: sub get_scalar {
                   5744:     my ($string,$end) = @_;
                   5745:     my $value;
                   5746:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5747: 	$value = $1;
                   5748:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5749: 	$value = $1;
                   5750:     }
                   5751:     return &unescape($value);
                   5752: }
                   5753: 
                   5754: sub array2str {
                   5755:   my (@array) = @_;
                   5756:   my $result=&arrayref2str(\@array);
                   5757:   $result=~s/^__ARRAY_REF__//;
                   5758:   $result=~s/__END_ARRAY_REF__$//;
                   5759:   return $result;
                   5760: }
                   5761: 
1.204     albertel 5762: sub arrayref2str {
                   5763:   my ($arrayref) = @_;
1.265     albertel 5764:   my $result='__ARRAY_REF__';
1.204     albertel 5765:   foreach my $elem (@$arrayref) {
1.265     albertel 5766:     if(ref($elem) eq 'ARRAY') {
                   5767:       $result.=&arrayref2str($elem).'&';
                   5768:     } elsif(ref($elem) eq 'HASH') {
                   5769:       $result.=&hashref2str($elem).'&';
                   5770:     } elsif(ref($elem)) {
                   5771:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5772:     } else {
                   5773:       $result.=&escape($elem).'&';
                   5774:     }
                   5775:   }
                   5776:   $result=~s/\&$//;
1.265     albertel 5777:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5778:   return $result;
                   5779: }
                   5780: 
1.168     albertel 5781: sub hash2str {
1.204     albertel 5782:   my (%hash) = @_;
                   5783:   my $result=&hashref2str(\%hash);
1.265     albertel 5784:   $result=~s/^__HASH_REF__//;
                   5785:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5786:   return $result;
                   5787: }
                   5788: 
                   5789: sub hashref2str {
                   5790:   my ($hashref)=@_;
1.265     albertel 5791:   my $result='__HASH_REF__';
1.800     albertel 5792:   foreach my $key (sort(keys(%$hashref))) {
                   5793:     if (ref($key) eq 'ARRAY') {
                   5794:       $result.=&arrayref2str($key).'=';
                   5795:     } elsif (ref($key) eq 'HASH') {
                   5796:       $result.=&hashref2str($key).'=';
                   5797:     } elsif (ref($key)) {
1.265     albertel 5798:       $result.='=';
1.800     albertel 5799:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5800:     } else {
1.1132    raeburn  5801: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5802:     }
                   5803: 
1.800     albertel 5804:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5805:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5806:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5807:       $result.=&hashref2str($hashref->{$key}).'&';
                   5808:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5809:        $result.='&';
1.800     albertel 5810:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5811:     } else {
1.800     albertel 5812:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5813:     }
                   5814:   }
1.168     albertel 5815:   $result=~s/\&$//;
1.265     albertel 5816:   $result .= '__END_HASH_REF__';
1.168     albertel 5817:   return $result;
                   5818: }
                   5819: 
                   5820: sub str2hash {
1.265     albertel 5821:     my ($string)=@_;
                   5822:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5823:     return %$hash;
                   5824: }
                   5825: 
                   5826: sub str2hashref {
1.168     albertel 5827:   my ($string) = @_;
1.265     albertel 5828: 
                   5829:   my %hash;
                   5830: 
                   5831:   if($string !~ /^__HASH_REF__/) {
                   5832:       if (! ($string eq '' || !defined($string))) {
                   5833: 	  $hash{'error'}='Not hash reference';
                   5834:       }
                   5835:       return (\%hash, $string);
                   5836:   }
                   5837: 
                   5838:   $string =~ s/^__HASH_REF__//;
                   5839: 
                   5840:   while($string !~ /^__END_HASH_REF__/) {
                   5841:       #key
                   5842:       my $key='';
                   5843:       if($string =~ /^__HASH_REF__/) {
                   5844:           ($key, $string)=&str2hashref($string);
                   5845:           if(defined($key->{'error'})) {
                   5846:               $hash{'error'}='Bad data';
                   5847:               return (\%hash, $string);
                   5848:           }
                   5849:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5850:           ($key, $string)=&str2arrayref($string);
                   5851:           if($key->[0] eq 'Array reference error') {
                   5852:               $hash{'error'}='Bad data';
                   5853:               return (\%hash, $string);
                   5854:           }
                   5855:       } else {
                   5856:           $string =~ s/^(.*?)=//;
1.267     albertel 5857: 	  $key=&unescape($1);
1.265     albertel 5858:       }
                   5859:       $string =~ s/^=//;
                   5860: 
                   5861:       #value
                   5862:       my $value='';
                   5863:       if($string =~ /^__HASH_REF__/) {
                   5864:           ($value, $string)=&str2hashref($string);
                   5865:           if(defined($value->{'error'})) {
                   5866:               $hash{'error'}='Bad data';
                   5867:               return (\%hash, $string);
                   5868:           }
                   5869:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5870:           ($value, $string)=&str2arrayref($string);
                   5871:           if($value->[0] eq 'Array reference error') {
                   5872:               $hash{'error'}='Bad data';
                   5873:               return (\%hash, $string);
                   5874:           }
                   5875:       } else {
                   5876: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5877:       }
                   5878:       $string =~ s/^&//;
                   5879: 
                   5880:       $hash{$key}=$value;
1.204     albertel 5881:   }
1.265     albertel 5882: 
                   5883:   $string =~ s/^__END_HASH_REF__//;
                   5884: 
                   5885:   return (\%hash, $string);
1.204     albertel 5886: }
                   5887: 
                   5888: sub str2array {
1.265     albertel 5889:     my ($string)=@_;
                   5890:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5891:     return @$array;
                   5892: }
                   5893: 
                   5894: sub str2arrayref {
1.204     albertel 5895:   my ($string) = @_;
1.265     albertel 5896:   my @array;
                   5897: 
                   5898:   if($string !~ /^__ARRAY_REF__/) {
                   5899:       if (! ($string eq '' || !defined($string))) {
                   5900: 	  $array[0]='Array reference error';
                   5901:       }
                   5902:       return (\@array, $string);
                   5903:   }
                   5904: 
                   5905:   $string =~ s/^__ARRAY_REF__//;
                   5906: 
                   5907:   while($string !~ /^__END_ARRAY_REF__/) {
                   5908:       my $value='';
                   5909:       if($string =~ /^__HASH_REF__/) {
                   5910:           ($value, $string)=&str2hashref($string);
                   5911:           if(defined($value->{'error'})) {
                   5912:               $array[0] ='Array reference error';
                   5913:               return (\@array, $string);
                   5914:           }
                   5915:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5916:           ($value, $string)=&str2arrayref($string);
                   5917:           if($value->[0] eq 'Array reference error') {
                   5918:               $array[0] ='Array reference error';
                   5919:               return (\@array, $string);
                   5920:           }
                   5921:       } else {
                   5922: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5923:       }
                   5924:       $string =~ s/^&//;
                   5925: 
                   5926:       push(@array, $value);
1.191     harris41 5927:   }
1.265     albertel 5928: 
                   5929:   $string =~ s/^__END_ARRAY_REF__//;
                   5930: 
                   5931:   return (\@array, $string);
1.168     albertel 5932: }
                   5933: 
1.167     albertel 5934: # -------------------------------------------------------------------Temp Store
                   5935: 
1.168     albertel 5936: sub tmpreset {
                   5937:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5938:   if (!$symb) {
                   5939:     $symb=&symbread();
1.620     albertel 5940:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5941:   }
                   5942:   $symb=escape($symb);
                   5943: 
1.620     albertel 5944:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5945:   $namespace=~s/\//\_/g;
                   5946:   $namespace=~s/\W//g;
                   5947: 
1.620     albertel 5948:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5949:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5950:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5951:       $stuname=&get_requestor_ip();
1.591     albertel 5952:   }
1.1117    foxr     5953:   my $path=LONCAPA::tempdir();
1.168     albertel 5954:   my %hash;
                   5955:   if (tie(%hash,'GDBM_File',
                   5956: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5957: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5958:     foreach my $key (keys(%hash)) {
1.180     albertel 5959:       if ($key=~ /:$symb/) {
1.168     albertel 5960: 	delete($hash{$key});
                   5961:       }
                   5962:     }
                   5963:   }
                   5964: }
                   5965: 
1.167     albertel 5966: sub tmpstore {
1.168     albertel 5967:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5968: 
                   5969:   if (!$symb) {
                   5970:     $symb=&symbread();
1.620     albertel 5971:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5972:   }
                   5973:   $symb=escape($symb);
                   5974: 
                   5975:   if (!$namespace) {
                   5976:     # I don't think we would ever want to store this for a course.
                   5977:     # it seems this will only be used if we don't have a course.
1.620     albertel 5978:     #$namespace=$env{'request.course.id'};
1.168     albertel 5979:     #if (!$namespace) {
1.620     albertel 5980:       $namespace=$env{'request.state'};
1.168     albertel 5981:     #}
                   5982:   }
                   5983:   $namespace=~s/\//\_/g;
                   5984:   $namespace=~s/\W//g;
1.620     albertel 5985:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5986:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5987:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5988:       $stuname=&get_requestor_ip();
1.591     albertel 5989:   }
1.168     albertel 5990:   my $now=time;
                   5991:   my %hash;
1.1117    foxr     5992:   my $path=LONCAPA::tempdir();
1.168     albertel 5993:   if (tie(%hash,'GDBM_File',
                   5994: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5995: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5996:     $hash{"version:$symb"}++;
                   5997:     my $version=$hash{"version:$symb"};
                   5998:     my $allkeys=''; 
                   5999:     foreach my $key (keys(%$storehash)) {
                   6000:       $allkeys.=$key.':';
1.591     albertel 6001:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6002:     }
                   6003:     $hash{"$version:$symb:timestamp"}=$now;
                   6004:     $allkeys.='timestamp';
                   6005:     $hash{"$version:keys:$symb"}=$allkeys;
                   6006:     if (untie(%hash)) {
                   6007:       return 'ok';
                   6008:     } else {
                   6009:       return "error:$!";
                   6010:     }
                   6011:   } else {
                   6012:     return "error:$!";
                   6013:   }
                   6014: }
1.167     albertel 6015: 
1.168     albertel 6016: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6017: 
1.168     albertel 6018: sub tmprestore {
                   6019:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6020: 
1.168     albertel 6021:   if (!$symb) {
                   6022:     $symb=&symbread();
1.620     albertel 6023:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6024:   }
                   6025:   $symb=escape($symb);
                   6026: 
1.620     albertel 6027:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6028: 
1.620     albertel 6029:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6030:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6031:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6032:       $stuname=&get_requestor_ip();
1.591     albertel 6033:   }
1.168     albertel 6034:   my %returnhash;
                   6035:   $namespace=~s/\//\_/g;
                   6036:   $namespace=~s/\W//g;
                   6037:   my %hash;
1.1117    foxr     6038:   my $path=LONCAPA::tempdir();
1.168     albertel 6039:   if (tie(%hash,'GDBM_File',
                   6040: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6041: 	  &GDBM_READER(),0640)) {
1.168     albertel 6042:     my $version=$hash{"version:$symb"};
                   6043:     $returnhash{'version'}=$version;
                   6044:     my $scope;
                   6045:     for ($scope=1;$scope<=$version;$scope++) {
                   6046:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6047:       my @keys=split(/:/,$vkeys);
                   6048:       my $key;
                   6049:       $returnhash{"$scope:keys"}=$vkeys;
                   6050:       foreach $key (@keys) {
1.591     albertel 6051: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6052: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6053:       }
                   6054:     }
1.168     albertel 6055:     if (!(untie(%hash))) {
                   6056:       return "error:$!";
                   6057:     }
                   6058:   } else {
                   6059:     return "error:$!";
                   6060:   }
                   6061:   return %returnhash;
1.167     albertel 6062: }
                   6063: 
1.9       www      6064: # ----------------------------------------------------------------------- Store
                   6065: 
                   6066: sub store {
1.1172.2.64  raeburn  6067:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6068:     my $home='';
                   6069: 
1.168     albertel 6070:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6071: 
1.213     www      6072:     $symb=&symbclean($symb);
1.122     albertel 6073:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6074: 
1.620     albertel 6075:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6076:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6077: 
                   6078:     &devalidate($symb,$stuname,$domain);
1.109     www      6079: 
                   6080:     $symb=escape($symb);
1.187     www      6081:     if (!$namespace) { 
1.620     albertel 6082:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6083:           return ''; 
                   6084:        } 
                   6085:     }
1.620     albertel 6086:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6087: 
1.1172.2.138  raeburn  6088:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6089:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6090: 
1.12      www      6091:     my $namevalue='';
1.800     albertel 6092:     foreach my $key (keys(%$storehash)) {
                   6093:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6094:     }
1.12      www      6095:     $namevalue=~s/\&$//;
1.187     www      6096:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6097:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6098: }
                   6099: 
1.47      www      6100: # -------------------------------------------------------------- Critical Store
                   6101: 
                   6102: sub cstore {
1.1172.2.64  raeburn  6103:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6104:     my $home='';
                   6105: 
1.168     albertel 6106:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6107: 
1.213     www      6108:     $symb=&symbclean($symb);
1.122     albertel 6109:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6110: 
1.620     albertel 6111:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6112:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6113: 
                   6114:     &devalidate($symb,$stuname,$domain);
1.109     www      6115: 
                   6116:     $symb=escape($symb);
1.187     www      6117:     if (!$namespace) { 
1.620     albertel 6118:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6119:           return ''; 
                   6120:        } 
                   6121:     }
1.620     albertel 6122:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6123: 
1.1172.2.138  raeburn  6124:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6125:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6126: 
1.47      www      6127:     my $namevalue='';
1.800     albertel 6128:     foreach my $key (keys(%$storehash)) {
                   6129:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6130:     }
1.47      www      6131:     $namevalue=~s/\&$//;
1.187     www      6132:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6133:     return critical
1.1172.2.64  raeburn  6134:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6135: }
                   6136: 
1.9       www      6137: # --------------------------------------------------------------------- Restore
                   6138: 
                   6139: sub restore {
1.124     www      6140:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6141:     my $home='';
                   6142: 
1.168     albertel 6143:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6144: 
1.122     albertel 6145:     if (!$symb) {
1.1172.2.26  raeburn  6146:         return if ($namespace eq 'courserequests');
                   6147:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6148:     } else {
1.1172.2.26  raeburn  6149:         unless ($namespace eq 'courserequests') {
                   6150:             $symb=&escape(&symbclean($symb));
                   6151:         }
1.122     albertel 6152:     }
1.188     www      6153:     if (!$namespace) { 
1.620     albertel 6154:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6155:           return ''; 
                   6156:        } 
                   6157:     }
1.620     albertel 6158:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6159:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6160:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6161:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6162: 
1.12      www      6163:     my %returnhash=();
1.800     albertel 6164:     foreach my $line (split(/\&/,$answer)) {
                   6165: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6166:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6167:     }
1.75      www      6168:     my $version;
                   6169:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6170:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6171:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6172:        }
1.75      www      6173:     }
1.13      www      6174:     return %returnhash;
1.34      www      6175: }
                   6176: 
                   6177: # ---------------------------------------------------------- Course Description
1.1118    foxr     6178: #
                   6179: #  
1.34      www      6180: 
                   6181: sub coursedescription {
1.731     albertel 6182:     my ($courseid,$args)=@_;
1.34      www      6183:     $courseid=~s/^\///;
1.49      www      6184:     $courseid=~s/\_/\//g;
1.34      www      6185:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6186:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6187:     my $normalid=$cdomain.'_'.$cnum;
                   6188:     # need to always cache even if we get errors otherwise we keep 
                   6189:     # trying and trying and trying to get the course description.
                   6190:     my %envhash=();
                   6191:     my %returnhash=();
1.731     albertel 6192:     
                   6193:     my $expiretime=600;
                   6194:     if ($env{'request.course.id'} eq $normalid) {
                   6195: 	$expiretime=120;
                   6196:     }
                   6197: 
                   6198:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6199:     if (!$args->{'freshen_cache'}
                   6200: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6201: 	foreach my $key (keys(%env)) {
                   6202: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6203: 	    my ($setting) = $1;
                   6204: 	    $returnhash{$setting} = $env{$key};
                   6205: 	}
                   6206: 	return %returnhash;
                   6207:     }
                   6208: 
1.1118    foxr     6209:     # get the data again
                   6210: 
1.731     albertel 6211:     if (!$args->{'one_time'}) {
                   6212: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6213:     }
1.811     albertel 6214: 
1.34      www      6215:     if ($chome ne 'no_host') {
1.302     albertel 6216:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6217:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6218: 	   my $username = $env{'user.name'}; # Defult username
                   6219: 	   if(defined $args->{'user'}) {
                   6220: 	       $username = $args->{'user'};
                   6221: 	   }
1.129     albertel 6222:            $returnhash{'home'}= $chome;
                   6223: 	   $returnhash{'domain'} = $cdomain;
                   6224: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6225:            if (!defined($returnhash{'type'})) {
                   6226:                $returnhash{'type'} = 'Course';
                   6227:            }
1.130     albertel 6228:            while (my ($name,$value) = each %returnhash) {
1.53      www      6229:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6230:            }
1.270     www      6231:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6232:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6233: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6234:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6235:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6236:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6237:        }
                   6238:     }
1.731     albertel 6239:     if (!$args->{'one_time'}) {
1.949     raeburn  6240: 	&appenv(\%envhash);
1.731     albertel 6241:     }
1.302     albertel 6242:     return %returnhash;
1.461     www      6243: }
                   6244: 
1.1080    raeburn  6245: sub update_released_required {
                   6246:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6247:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6248:         $cid = $env{'request.course.id'};
                   6249:         $cdom = $env{'course.'.$cid.'.domain'};
                   6250:         $cnum = $env{'course.'.$cid.'.num'};
                   6251:         $chome = $env{'course.'.$cid.'.home'};
                   6252:     }
                   6253:     if ($needsrelease) {
                   6254:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6255:         my $needsupdate;
                   6256:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6257:             $needsupdate = 1;
                   6258:         } else {
                   6259:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6260:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6261:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6262:                 $needsupdate = 1;
                   6263:             }
                   6264:         }
                   6265:         if ($needsupdate) {
                   6266:             my %needshash = (
                   6267:                              'internal.releaserequired' => $needsrelease,
                   6268:                             );
                   6269:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6270:             if ($putresult eq 'ok') {
                   6271:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6272:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6273:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6274:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6275:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6276:                 }
                   6277:             }
                   6278:         }
                   6279:     }
                   6280:     return;
                   6281: }
                   6282: 
1.461     www      6283: # -------------------------------------------------See if a user is privileged
                   6284: 
                   6285: sub privileged {
1.1172.2.23  raeburn  6286:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6287:     my $now = time;
1.1172.2.23  raeburn  6288:     my $roles;
                   6289:     if (ref($possroles) eq 'ARRAY') {
                   6290:         $roles = $possroles;
                   6291:     } else {
                   6292:         $roles = ['dc','su'];
                   6293:     }
                   6294:     if (ref($possdomains) eq 'ARRAY') {
                   6295:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6296:         foreach my $dom (@{$possdomains}) {
                   6297:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6298:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6299:                 foreach my $role (@{$roles}) {
                   6300:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6301:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6302:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6303:                             return 1 unless (($end && $end < $now) ||
                   6304:                                              ($start && $start > $now));
                   6305:                         }
                   6306:                     }
                   6307:                 }
                   6308:             }
                   6309:         }
                   6310:     } else {
                   6311:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6312:         my $now = time;
1.1170    droeschl 6313: 
1.1172.2.58  raeburn  6314:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6315:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6316:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6317:                 return 1 unless ($tend && $tend < $now)
                   6318:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6319:             }
1.1172.2.23  raeburn  6320:         }
                   6321:     }
1.461     www      6322:     return 0;
1.9       www      6323: }
1.1       albertel 6324: 
1.1172.2.23  raeburn  6325: sub privileged_by_domain {
                   6326:     my ($domains,$roles) = @_;
                   6327:     my %privileged = ();
                   6328:     my $cachetime = 60*60*24;
                   6329:     my $now = time;
                   6330:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6331:         return %privileged;
                   6332:     }
                   6333:     foreach my $dom (@{$domains}) {
                   6334:         next if (ref($privileged{$dom}) eq 'HASH');
                   6335:         my $needroles;
                   6336:         foreach my $role (@{$roles}) {
                   6337:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6338:             if (defined($cached)) {
                   6339:                 if (ref($result) eq 'HASH') {
                   6340:                     $privileged{$dom}{$role} = $result;
                   6341:                 }
                   6342:             } else {
                   6343:                 $needroles = 1;
                   6344:             }
                   6345:         }
                   6346:         if ($needroles) {
                   6347:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6348:             $privileged{$dom} = {};
                   6349:             foreach my $server (keys(%dompersonnel)) {
                   6350:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6351:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6352:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6353:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6354:                         next if ($end && $end < $now);
                   6355:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6356:                             $dompersonnel{$server}{$item};
                   6357:                     }
                   6358:                 }
                   6359:             }
                   6360:             if (ref($privileged{$dom}) eq 'HASH') {
                   6361:                 foreach my $role (@{$roles}) {
                   6362:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6363:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6364:                     } else {
                   6365:                         my %hash = ();
                   6366:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6367:                     }
                   6368:                 }
                   6369:             }
                   6370:         }
                   6371:     }
                   6372:     return %privileged;
                   6373: }
                   6374: 
1.103     harris41 6375: # -------------------------------------------------------- Get user privileges
1.11      www      6376: 
                   6377: sub rolesinit {
1.1169    droeschl 6378:     my ($domain, $username) = @_;
                   6379:     my %userroles = ('user.login.time' => time);
                   6380:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6381: 
                   6382:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6383:     # also, blocking can be triggered by an activating timer
                   6384:     # it's saved in the user's %env.
                   6385:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6386:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6387:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6388:         %timerintchk, %timerintenv);
                   6389: 
1.1162    raeburn  6390:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6391:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6392:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6393:     }
1.1169    droeschl 6394: 
1.1162    raeburn  6395:     foreach my $key (keys(%timerinterval)) {
                   6396:         my ($cid,$rest) = split(/\0/,$key);
                   6397:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6398:     }
1.1169    droeschl 6399: 
1.11      www      6400:     my %allroles=();
1.1162    raeburn  6401:     my %allgroups=();
1.11      www      6402: 
1.1172.2.58  raeburn  6403:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6404:         my $role = $rolesdump{$area};
                   6405:         $area =~ s/\_\w\w$//;
                   6406: 
                   6407:         my ($trole, $tend, $tstart, $group_privs);
                   6408: 
                   6409:         if ($role =~ /^cr/) {
                   6410:         # Custom role, defined by a user 
                   6411:         # e.g., user.role.cr/msu/smith/mynewrole
                   6412:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6413:                 $trole = $1;
                   6414:                 ($tend, $tstart) = split('_', $2);
                   6415:             } else {
                   6416:                 $trole = $role;
                   6417:             }
                   6418:         } elsif ($role =~ m|^gr/|) {
                   6419:         # Role of member in a group, defined within a course/community
                   6420:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6421:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6422:             next if $tstart eq '-1';
                   6423:             ($trole, $group_privs) = split(/\//, $trole);
                   6424:             $group_privs = &unescape($group_privs);
                   6425:         } else {
                   6426:         # Just a normal role, defined in roles.tab
                   6427:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6428:         }
                   6429: 
                   6430:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6431:                  $username);
                   6432:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6433: 
                   6434:         # role expired or not available yet?
                   6435:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6436:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6437: 
                   6438:         next if $area eq '' or $trole eq '';
                   6439: 
                   6440:         my $spec = "$trole.$area";
                   6441:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6442: 
                   6443:         if ($trole =~ /^cr\//) {
                   6444:         # Custom role, defined by a user
                   6445:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6446:         } elsif ($trole eq 'gr') {
                   6447:         # Role of a member in a group, defined within a course/community
                   6448:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6449:             next;
                   6450:         } else {
                   6451:         # Normal role, defined in roles.tab
                   6452:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6453:         }
                   6454: 
                   6455:         my $cid = $tdomain.'_'.$trest;
                   6456:         unless ($firstaccchk{$cid}) {
                   6457:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6458:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6459:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6460:                         $coursetimerstarts{$cid}{$item}; 
                   6461:                 }
                   6462:             }
                   6463:             $firstaccchk{$cid} = 1;
                   6464:         }
                   6465:         unless ($timerintchk{$cid}) {
                   6466:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6467:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6468:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6469:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6470:                 }
1.12      www      6471:             }
1.1169    droeschl 6472:             $timerintchk{$cid} = 1;
1.191     harris41 6473:         }
1.11      www      6474:     }
1.1169    droeschl 6475: 
1.1172.2.91  raeburn  6476:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6477:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6478:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6479:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6480: 
1.1162    raeburn  6481:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6482: }
                   6483: 
1.567     raeburn  6484: sub set_arearole {
1.1172.2.19  raeburn  6485:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6486:     unless ($nolog) {
1.567     raeburn  6487: # log the associated role with the area
1.1172.2.19  raeburn  6488:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6489:     }
1.743     albertel 6490:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6491: }
                   6492: 
                   6493: sub custom_roleprivs {
                   6494:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6495:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6496:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6497:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6498:         my ($rdummy,$roledef)=
                   6499:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6500:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6501:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6502:             if (defined($syspriv)) {
1.1043    raeburn  6503:                 if ($trest =~ /^$match_community$/) {
                   6504:                     $syspriv =~ s/bre\&S//; 
                   6505:                 }
1.567     raeburn  6506:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6507:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6508:             }
                   6509:             if ($tdomain ne '') {
                   6510:                 if (defined($dompriv)) {
                   6511:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6512:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6513:                 }
                   6514:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6515:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6516:                         my $rolename = $1;
                   6517:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6518:                     }
1.567     raeburn  6519:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6520:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6521:                 }
                   6522:             }
                   6523:         }
                   6524:     }
                   6525: }
                   6526: 
1.1172.2.89  raeburn  6527: sub course_adhocrole_privs {
                   6528:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6529:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6530:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6531:         my (%currprivs,%storeprivs);
                   6532:         foreach my $item (split(/:/,$coursepriv)) {
                   6533:             my ($priv,$restrict) = split(/\&/,$item);
                   6534:             $currprivs{$priv} = $restrict;
                   6535:         }
                   6536:         my (%possadd,%possremove,%full);
                   6537:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6538:             my ($priv,$restrict)=split(/\&/,$item);
                   6539:             $full{$priv} = $restrict;
                   6540:         }
                   6541:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6542:              next if ($item eq '');
                   6543:              my ($rule,$rest) = split(/=/,$item);
                   6544:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6545:              foreach my $priv (split(/:/,$rest)) {
                   6546:                  if ($priv ne '') {
                   6547:                      if ($rule eq 'off') {
                   6548:                          $possremove{$priv} = 1;
                   6549:                      } else {
                   6550:                          $possadd{$priv} = 1;
                   6551:                      }
                   6552:                  }
                   6553:              }
                   6554:          }
                   6555:          foreach my $priv (sort(keys(%full))) {
                   6556:              if (exists($currprivs{$priv})) {
                   6557:                  unless (exists($possremove{$priv})) {
                   6558:                      $storeprivs{$priv} = $currprivs{$priv};
                   6559:                  }
                   6560:              } elsif (exists($possadd{$priv})) {
                   6561:                  $storeprivs{$priv} = $full{$priv};
                   6562:              }
                   6563:          }
                   6564:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6565:      }
                   6566:      return $coursepriv;
                   6567: }
                   6568: 
1.678     raeburn  6569: sub group_roleprivs {
                   6570:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6571:     my $access = 1;
                   6572:     my $now = time;
                   6573:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6574:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6575:     if ($access) {
1.811     albertel 6576:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6577:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6578:     }
                   6579: }
1.567     raeburn  6580: 
                   6581: sub standard_roleprivs {
                   6582:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6583:     if (defined($pr{$trole.':s'})) {
                   6584:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6585:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6586:     }
                   6587:     if ($tdomain ne '') {
                   6588:         if (defined($pr{$trole.':d'})) {
                   6589:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6590:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6591:         }
                   6592:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6593:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6594:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6595:         }
                   6596:     }
                   6597: }
                   6598: 
                   6599: sub set_userprivs {
1.1064    raeburn  6600:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6601:     my $author=0;
                   6602:     my $adv=0;
1.1172.2.91  raeburn  6603:     my $rar=0;
1.678     raeburn  6604:     my %grouproles = ();
                   6605:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6606:         my @groupkeys; 
1.1000    raeburn  6607:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6608:             push(@groupkeys,$role);
                   6609:         }
                   6610:         if (ref($groups_roles) eq 'HASH') {
                   6611:             foreach my $key (keys(%{$groups_roles})) {
                   6612:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6613:                     push(@groupkeys,$key);
                   6614:                 }
                   6615:             }
                   6616:         }
                   6617:         if (@groupkeys > 0) {
                   6618:             foreach my $role (@groupkeys) {
                   6619:                 my ($trole,$area,$sec,$extendedarea);
                   6620:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6621:                     $trole = $1;
                   6622:                     $area = $2;
                   6623:                     $sec = $3;
                   6624:                     $extendedarea = $area.$sec;
                   6625:                     if (exists($$allgroups{$area})) {
                   6626:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6627:                             my $spec = $trole.'.'.$extendedarea;
                   6628:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6629:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6630:                         }
1.678     raeburn  6631:                     }
                   6632:                 }
                   6633:             }
                   6634:         }
                   6635:     }
1.800     albertel 6636:     foreach my $group (keys(%grouproles)) {
                   6637:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6638:     }
1.800     albertel 6639:     foreach my $role (keys(%{$allroles})) {
                   6640:         my %thesepriv;
1.941     raeburn  6641:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6642:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6643:             if ($item ne '') {
                   6644:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6645:                 if ($restrictions eq '') {
                   6646:                     $thesepriv{$privilege}='F';
                   6647:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6648:                     $thesepriv{$privilege}.=$restrictions;
                   6649:                 }
                   6650:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6651:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6652:             }
                   6653:         }
                   6654:         my $thesestr='';
1.1104    raeburn  6655:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6656: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6657: 	}
                   6658:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6659:     }
1.1172.2.91  raeburn  6660:     return ($author,$adv,$rar);
1.567     raeburn  6661: }
                   6662: 
1.994     raeburn  6663: sub role_status {
1.1104    raeburn  6664:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6665:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6666:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6667:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6668:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6669:             $$where = '/'.$two;
1.994     raeburn  6670:             $$trolecode=$$role.'.'.$$where;
                   6671:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6672:             $$tstatus='is';
1.1104    raeburn  6673:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6674:                 $$tstatus='future';
1.1034    raeburn  6675:                 if ($$tstart<$now) {
                   6676:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6677:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6678:                             my (%allroles,%allgroups,$group_privs,
                   6679:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6680:                             my %userroles = (
                   6681:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6682:                             );
1.1064    raeburn  6683:                             @rolecodes = ('cm'); 
1.1002    raeburn  6684:                             my $spec=$$role.'.'.$$where;
                   6685:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6686:                             if ($$role =~ /^cr\//) {
                   6687:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6688:                                 push(@rolecodes,'cr');
1.1002    raeburn  6689:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6690:                                 push(@rolecodes,$$role);
1.1002    raeburn  6691:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6692:                                                     $env{'user.name'});
1.1064    raeburn  6693:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6694:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6695:                                 $group_privs = &unescape($group_privs);
                   6696:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6697:                                 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  6698:                                 &get_groups_roles($tdomain,$trest,
                   6699:                                                   \%course_roles,\@rolecodes,
                   6700:                                                   \%groups_roles);
1.1002    raeburn  6701:                             } else {
1.1064    raeburn  6702:                                 push(@rolecodes,$$role);
1.1002    raeburn  6703:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6704:                             }
1.1172.2.91  raeburn  6705:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6706:                                                                    \%groups_roles);
1.1064    raeburn  6707:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6708:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6709:                         }
                   6710:                     }
1.1034    raeburn  6711:                     $$tstatus = 'is';
1.1002    raeburn  6712:                 }
1.994     raeburn  6713:             }
                   6714:             if ($$tend) {
1.1104    raeburn  6715:                 if ($$tend<$update) {
1.994     raeburn  6716:                     $$tstatus='expired';
                   6717:                 } elsif ($$tend<$now) {
                   6718:                     $$tstatus='will_not';
                   6719:                 }
                   6720:             }
                   6721:         }
                   6722:     }
                   6723: }
                   6724: 
1.1104    raeburn  6725: sub get_groups_roles {
                   6726:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6727:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6728:                   (ref($rolecodes) eq 'ARRAY') && 
                   6729:                   (ref($groups_roles) eq 'HASH')); 
                   6730:     if (keys(%{$cdom_courseroles}) > 0) {
                   6731:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6732:         if ($cdom ne '' && $cnum ne '') {
                   6733:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6734:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6735:                     my $crsrole = $1;
                   6736:                     my $crssec = $2;
                   6737:                     if ($crsrole =~ /^cr/) {
                   6738:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6739:                             push(@{$rolecodes},'cr');
                   6740:                         }
                   6741:                     } else {
                   6742:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6743:                             push(@{$rolecodes},$crsrole);
                   6744:                         }
                   6745:                     }
                   6746:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6747:                     if ($crssec ne '') {
                   6748:                         $rolekey .= "/$crssec";
                   6749:                     }
                   6750:                     $rolekey .= './';
                   6751:                     $groups_roles->{$rolekey} = $rolecodes;
                   6752:                 }
                   6753:             }
                   6754:         }
                   6755:     }
                   6756:     return;
                   6757: }
                   6758: 
                   6759: sub delete_env_groupprivs {
                   6760:     my ($where,$courseroles,$possroles) = @_;
                   6761:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6762:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6763:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6764:         %{$courseroles->{$udom}} =
                   6765:             &get_my_roles('','','userroles',['active'],
                   6766:                           $possroles,[$udom],1);
                   6767:     }
                   6768:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6769:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6770:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6771:             my $area = '/'.$cdom.'/'.$cnum;
                   6772:             my $privkey = "user.priv.$crsrole.$area";
                   6773:             if ($crssec ne '') {
                   6774:                 $privkey .= '/'.$crssec;
                   6775:             }
                   6776:             $privkey .= ".$area/$group";
                   6777:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6778:         }
                   6779:     }
                   6780:     return;
                   6781: }
                   6782: 
1.994     raeburn  6783: sub check_adhoc_privs {
1.1172.2.86  raeburn  6784:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6785:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6786:     if ($sec) {
                   6787:         $cckey .= '/'.$sec;
                   6788:     }
1.1172.2.9  raeburn  6789:     my $setprivs;
1.994     raeburn  6790:     if ($env{$cckey}) {
                   6791:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6792:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6793:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6794:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6795:             $setprivs = 1;
1.994     raeburn  6796:         }
                   6797:     } else {
1.1172.2.87  raeburn  6798:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6799:         $setprivs = 1;
1.994     raeburn  6800:     }
1.1172.2.9  raeburn  6801:     return $setprivs;
1.994     raeburn  6802: }
                   6803: 
                   6804: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6805: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6806:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6807:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6808:     if ($sec ne '') {
                   6809:         $area .= '/'.$sec;
                   6810:     }
1.994     raeburn  6811:     my $spec = $role.'.'.$area;
                   6812:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6813:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6814:     my %rolehash = ();
1.1172.2.89  raeburn  6815:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6816:         my $rolename = $1;
1.1172.2.84  raeburn  6817:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6818:         my %domdef = &get_domain_defaults($dcdom);
                   6819:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6820:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6821:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6822:             }
                   6823:         }
1.1172.2.84  raeburn  6824:     } else {
                   6825:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6826:     }
1.1172.2.91  raeburn  6827:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6828:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6829:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6830:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6831:         &appenv( {'request.role'        => $spec,
                   6832:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6833:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6834:                  }
                   6835:                );
                   6836:         my $tadv=0;
                   6837:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6838:         &appenv({'request.role.adv'    => $tadv});
                   6839:     }
1.994     raeburn  6840: }
                   6841: 
1.12      www      6842: # --------------------------------------------------------------- get interface
                   6843: 
                   6844: sub get {
1.131     albertel 6845:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6846:    my $items='';
1.800     albertel 6847:    foreach my $item (@$storearr) {
                   6848:        $items.=&escape($item).'&';
1.191     harris41 6849:    }
1.12      www      6850:    $items=~s/\&$//;
1.620     albertel 6851:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6852:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6853:    my $uhome=&homeserver($uname,$udomain);
                   6854: 
1.133     albertel 6855:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6856:    my @pairs=split(/\&/,$rep);
1.273     albertel 6857:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6858:      return @pairs;
                   6859:    }
1.15      www      6860:    my %returnhash=();
1.42      www      6861:    my $i=0;
1.800     albertel 6862:    foreach my $item (@$storearr) {
                   6863:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6864:       $i++;
1.191     harris41 6865:    }
1.15      www      6866:    return %returnhash;
1.27      www      6867: }
                   6868: 
                   6869: # --------------------------------------------------------------- del interface
                   6870: 
                   6871: sub del {
1.133     albertel 6872:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6873:    my $items='';
1.800     albertel 6874:    foreach my $item (@$storearr) {
                   6875:        $items.=&escape($item).'&';
1.191     harris41 6876:    }
1.984     neumanie 6877: 
1.27      www      6878:    $items=~s/\&$//;
1.620     albertel 6879:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6880:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6881:    my $uhome=&homeserver($uname,$udomain);
                   6882:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6883: }
                   6884: 
                   6885: # -------------------------------------------------------------- dump interface
                   6886: 
1.1172.2.22  raeburn  6887: sub unserialize {
                   6888:     my ($rep, $escapedkeys) = @_;
                   6889: 
                   6890:     return {} if $rep =~ /^error/;
                   6891: 
                   6892:     my %returnhash=();
                   6893:     foreach my $item (split(/\&/,$rep)) {
                   6894:         my ($key, $value) = split(/=/, $item, 2);
                   6895:         $key = unescape($key) unless $escapedkeys;
                   6896:         next if $key =~ /^error: 2 /;
                   6897:         $returnhash{$key} = &thaw_unescape($value);
                   6898:     }
                   6899:     return \%returnhash;
                   6900: }
                   6901: 
                   6902: # see Lond::dump_with_regexp
                   6903: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6904: sub dump {
1.1172.2.22  raeburn  6905:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6906:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6907:     if (!$uname) { $uname=$env{'user.name'}; }
                   6908:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6909: 
1.1172.2.55  raeburn  6910:     if ($regexp) {
                   6911:         $regexp=&escape($regexp);
                   6912:     } else {
                   6913:         $regexp='.';
                   6914:     }
1.1172.2.22  raeburn  6915:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6916:         # user is hosted on this machine
1.1172.2.55  raeburn  6917:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6918:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6919:         return %{&unserialize($reply, $escapedkeys)};
                   6920:     }
1.1166    raeburn  6921:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6922:     my @pairs=split(/\&/,$rep);
                   6923:     my %returnhash=();
1.1098    foxr     6924:     if (!($rep =~ /^error/ )) {
                   6925: 	foreach my $item (@pairs) {
                   6926: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6927:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6928: 	    next if ($key =~ /^error: 2 /);
                   6929: 	    $returnhash{$key}=&thaw_unescape($value);
                   6930: 	}
1.755     albertel 6931:     }
                   6932:     return %returnhash;
1.407     www      6933: }
                   6934: 
1.1098    foxr     6935: 
1.717     albertel 6936: # --------------------------------------------------------- dumpstore interface
                   6937: 
                   6938: sub dumpstore {
                   6939:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6940:    # same as dump but keys must be escaped. They may contain colon separated
                   6941:    # lists of values that may themself contain colons (e.g. symbs).
                   6942:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6943: }
                   6944: 
1.407     www      6945: # -------------------------------------------------------------- keys interface
                   6946: 
                   6947: sub getkeys {
                   6948:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6949:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6950:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6951:    my $uhome=&homeserver($uname,$udomain);
                   6952:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6953:    my @keyarray=();
1.800     albertel 6954:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6955:       next if ($key =~ /^error: 2 /);
1.800     albertel 6956:       push(@keyarray,&unescape($key));
1.407     www      6957:    }
                   6958:    return @keyarray;
1.318     matthew  6959: }
                   6960: 
1.319     matthew  6961: # --------------------------------------------------------------- currentdump
                   6962: sub currentdump {
1.328     matthew  6963:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6964:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6965:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6966:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6967:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6968:    my $rep;
                   6969: 
                   6970:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6971:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6972:                    $courseid)));
                   6973:    } else {
                   6974:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6975:    }
                   6976: 
1.318     matthew  6977:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6978:    #
1.318     matthew  6979:    my %returnhash=();
1.319     matthew  6980:    #
                   6981:    if ($rep eq "unknown_cmd") { 
                   6982:        # an old lond will not know currentdump
                   6983:        # Do a dump and make it look like a currentdump
1.822     albertel 6984:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6985:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6986:        my %hash = @tmp;
                   6987:        @tmp=();
1.424     matthew  6988:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6989:    } else {
                   6990:        my @pairs=split(/\&/,$rep);
1.800     albertel 6991:        foreach my $pair (@pairs) {
                   6992:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6993:            my ($symb,$param) = split(/:/,$key);
                   6994:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6995:                                                         &thaw_unescape($value);
1.319     matthew  6996:        }
1.191     harris41 6997:    }
1.12      www      6998:    return %returnhash;
1.424     matthew  6999: }
                   7000: 
                   7001: sub convert_dump_to_currentdump{
                   7002:     my %hash = %{shift()};
                   7003:     my %returnhash;
                   7004:     # Code ripped from lond, essentially.  The only difference
                   7005:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7006:     # we might run in to problems with parameter names =~ /^v\./
                   7007:     while (my ($key,$value) = each(%hash)) {
                   7008:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7009: 	$symb  = &unescape($symb);
                   7010: 	$param = &unescape($param);
1.424     matthew  7011:         next if ($v eq 'version' || $symb eq 'keys');
                   7012:         next if (exists($returnhash{$symb}) &&
                   7013:                  exists($returnhash{$symb}->{$param}) &&
                   7014:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7015:         $returnhash{$symb}->{$param}=$value;
                   7016:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7017:     }
                   7018:     #
                   7019:     # Remove all of the keys in the hashes which keep track of
                   7020:     # the version of the parameter.
                   7021:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7022:         # use a foreach because we are going to delete from the hash.
                   7023:         foreach my $key (keys(%$param_hash)) {
                   7024:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7025:         }
                   7026:     }
                   7027:     return \%returnhash;
1.12      www      7028: }
                   7029: 
1.627     albertel 7030: # ------------------------------------------------------ critical inc interface
                   7031: 
                   7032: sub cinc {
                   7033:     return &inc(@_,'critical');
                   7034: }
                   7035: 
1.449     matthew  7036: # --------------------------------------------------------------- inc interface
                   7037: 
                   7038: sub inc {
1.627     albertel 7039:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7040:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7041:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7042:     my $uhome=&homeserver($uname,$udomain);
                   7043:     my $items='';
                   7044:     if (! ref($store)) {
                   7045:         # got a single value, so use that instead
                   7046:         $items = &escape($store).'=&';
                   7047:     } elsif (ref($store) eq 'SCALAR') {
                   7048:         $items = &escape($$store).'=&';        
                   7049:     } elsif (ref($store) eq 'ARRAY') {
                   7050:         $items = join('=&',map {&escape($_);} @{$store});
                   7051:     } elsif (ref($store) eq 'HASH') {
                   7052:         while (my($key,$value) = each(%{$store})) {
                   7053:             $items.= &escape($key).'='.&escape($value).'&';
                   7054:         }
                   7055:     }
                   7056:     $items=~s/\&$//;
1.627     albertel 7057:     if ($critical) {
                   7058: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7059:     } else {
                   7060: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7061:     }
1.449     matthew  7062: }
                   7063: 
1.12      www      7064: # --------------------------------------------------------------- put interface
                   7065: 
                   7066: sub put {
1.134     albertel 7067:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7068:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7069:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7070:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7071:    my $items='';
1.800     albertel 7072:    foreach my $item (keys(%$storehash)) {
                   7073:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7074:    }
1.12      www      7075:    $items=~s/\&$//;
1.134     albertel 7076:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7077: }
                   7078: 
1.631     albertel 7079: # ------------------------------------------------------------ newput interface
                   7080: 
                   7081: sub newput {
                   7082:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7083:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7084:    if (!$uname) { $uname=$env{'user.name'}; }
                   7085:    my $uhome=&homeserver($uname,$udomain);
                   7086:    my $items='';
                   7087:    foreach my $key (keys(%$storehash)) {
                   7088:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7089:    }
                   7090:    $items=~s/\&$//;
                   7091:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7092: }
                   7093: 
                   7094: # ---------------------------------------------------------  putstore interface
                   7095: 
1.524     raeburn  7096: sub putstore {
1.1172.2.59  raeburn  7097:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7099:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7100:    my $uhome=&homeserver($uname,$udomain);
                   7101:    my $items='';
1.715     albertel 7102:    foreach my $key (keys(%$storehash)) {
                   7103:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7104:    }
1.715     albertel 7105:    $items=~s/\&$//;
1.716     albertel 7106:    my $esc_symb=&escape($symb);
                   7107:    my $esc_v=&escape($version);
1.715     albertel 7108:    my $reply =
1.716     albertel 7109:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7110: 	      $uhome);
1.1172.2.59  raeburn  7111:    if (($tolog) && ($reply eq 'ok')) {
                   7112:        my $namevalue='';
                   7113:        foreach my $key (keys(%{$storehash})) {
                   7114:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7115:        }
1.1172.2.134  raeburn  7116:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7117:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7118:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7119:                      '&version='.$esc_v.
                   7120:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7121:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7122:    }
1.715     albertel 7123:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7124:        # gfall back to way things use to be done
1.715     albertel 7125:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7126: 			    $uname);
1.524     raeburn  7127:    }
1.715     albertel 7128:    return $reply;
                   7129: }
                   7130: 
                   7131: sub old_putstore {
1.716     albertel 7132:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7133:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7134:     if (!$uname) { $uname=$env{'user.name'}; }
                   7135:     my $uhome=&homeserver($uname,$udomain);
                   7136:     my %newstorehash;
1.800     albertel 7137:     foreach my $item (keys(%$storehash)) {
                   7138: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7139: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7140:     }
                   7141:     my $items='';
                   7142:     my %allitems = ();
1.800     albertel 7143:     foreach my $item (keys(%newstorehash)) {
                   7144: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7145: 	    my $key = $1.':keys:'.$2;
                   7146: 	    $allitems{$key} .= $3.':';
                   7147: 	}
1.800     albertel 7148: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7149:     }
1.800     albertel 7150:     foreach my $item (keys(%allitems)) {
                   7151: 	$allitems{$item} =~ s/\:$//;
                   7152: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7153:     }
                   7154:     $items=~s/\&$//;
                   7155:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7156: }
                   7157: 
1.47      www      7158: # ------------------------------------------------------ critical put interface
                   7159: 
                   7160: sub cput {
1.134     albertel 7161:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7163:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7164:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7165:    my $items='';
1.800     albertel 7166:    foreach my $item (keys(%$storehash)) {
                   7167:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7168:    }
1.47      www      7169:    $items=~s/\&$//;
1.134     albertel 7170:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7171: }
                   7172: 
                   7173: # -------------------------------------------------------------- eget interface
                   7174: 
                   7175: sub eget {
1.133     albertel 7176:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7177:    my $items='';
1.800     albertel 7178:    foreach my $item (@$storearr) {
                   7179:        $items.=&escape($item).'&';
1.191     harris41 7180:    }
1.12      www      7181:    $items=~s/\&$//;
1.620     albertel 7182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7183:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7184:    my $uhome=&homeserver($uname,$udomain);
                   7185:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7186:    my @pairs=split(/\&/,$rep);
                   7187:    my %returnhash=();
1.42      www      7188:    my $i=0;
1.800     albertel 7189:    foreach my $item (@$storearr) {
                   7190:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7191:       $i++;
1.191     harris41 7192:    }
1.12      www      7193:    return %returnhash;
                   7194: }
                   7195: 
1.667     albertel 7196: # ------------------------------------------------------------ tmpput interface
                   7197: sub tmpput {
1.802     raeburn  7198:     my ($storehash,$server,$context)=@_;
1.667     albertel 7199:     my $items='';
1.800     albertel 7200:     foreach my $item (keys(%$storehash)) {
                   7201: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7202:     }
                   7203:     $items=~s/\&$//;
1.802     raeburn  7204:     if (defined($context)) {
                   7205:         $items .= ':'.&escape($context);
                   7206:     }
1.667     albertel 7207:     return &reply("tmpput:$items",$server);
                   7208: }
                   7209: 
                   7210: # ------------------------------------------------------------ tmpget interface
                   7211: sub tmpget {
1.688     albertel 7212:     my ($token,$server)=@_;
                   7213:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7214:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7215:     my %returnhash;
1.1172.2.85  raeburn  7216:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7217:         return %returnhash;
                   7218:     }
1.667     albertel 7219:     foreach my $item (split(/\&/,$rep)) {
                   7220: 	my ($key,$value)=split(/=/,$item);
                   7221: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7222:     }
                   7223:     return %returnhash;
                   7224: }
                   7225: 
1.1113    raeburn  7226: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7227: sub tmpdel {
                   7228:     my ($token,$server)=@_;
                   7229:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7230:     return &reply("tmpdel:$token",$server);
                   7231: }
                   7232: 
1.1172.2.13  raeburn  7233: # ------------------------------------------------------------ get_timebased_id
                   7234: 
                   7235: sub get_timebased_id {
                   7236:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7237:         $maxtries) = @_;
                   7238:     my ($newid,$error,$dellock);
                   7239:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7240:         return ('','ok','invalid call to get suffix');
                   7241:     }
                   7242: 
                   7243: # set defaults for any optional args for which values were not supplied
                   7244:     if ($who eq '') {
                   7245:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7246:     }
                   7247:     if (!$locktries) {
                   7248:         $locktries = 3;
                   7249:     }
                   7250:     if (!$maxtries) {
                   7251:         $maxtries = 10;
                   7252:     }
                   7253: 
                   7254:     if (($cdom eq '') || ($cnum eq '')) {
                   7255:         if ($env{'request.course.id'}) {
                   7256:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7257:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7258:         }
                   7259:         if (($cdom eq '') || ($cnum eq '')) {
                   7260:             return ('','ok','call to get suffix not in course context');
                   7261:         }
                   7262:     }
                   7263: 
                   7264: # construct locking item
                   7265:     my $lockhash = {
                   7266:                       $prefix."\0".'locked_'.$keyid => $who,
                   7267:                    };
                   7268:     my $tries = 0;
                   7269: 
                   7270: # attempt to get lock on nohist_$namespace file
                   7271:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7272:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7273:         $tries ++;
                   7274:         sleep 1;
                   7275:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7276:     }
                   7277: 
                   7278: # attempt to get unique identifier, based on current timestamp
                   7279:     if ($gotlock eq 'ok') {
                   7280:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7281:         my $id = time;
                   7282:         $newid = $id;
1.1172.2.56  raeburn  7283:         if ($idtype eq 'addcode') {
                   7284:             $newid .= &sixnum_code();
                   7285:         }
1.1172.2.13  raeburn  7286:         my $idtries = 0;
                   7287:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7288:             if ($idtype eq 'concat') {
                   7289:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7290:             } elsif ($idtype eq 'addcode') {
                   7291:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7292:             } else {
                   7293:                 $newid ++;
                   7294:             }
                   7295:             $idtries ++;
                   7296:         }
                   7297:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7298:             my %new_item =  (
                   7299:                               $prefix."\0".$newid => $who,
                   7300:                             );
                   7301:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7302:                                                  $cdom,$cnum);
                   7303:             if ($putresult ne 'ok') {
                   7304:                 undef($newid);
                   7305:                 $error = 'error saving new item: '.$putresult;
                   7306:             }
                   7307:         } else {
1.1172.2.56  raeburn  7308:              undef($newid);
1.1172.2.13  raeburn  7309:              $error = ('error: no unique suffix available for the new item ');
                   7310:         }
                   7311: #  remove lock
                   7312:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7313:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7314:     } else {
                   7315:         $error = "error: could not obtain lockfile\n";
                   7316:         $dellock = 'ok';
1.1172.2.58  raeburn  7317:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7318:             $dellock = 'nolock';
                   7319:         }
1.1172.2.13  raeburn  7320:     }
                   7321:     return ($newid,$dellock,$error);
                   7322: }
                   7323: 
1.1172.2.56  raeburn  7324: sub sixnum_code {
                   7325:     my $code;
                   7326:     for (0..6) {
                   7327:         $code .= int( rand(9) );
                   7328:     }
                   7329:     return $code;
                   7330: }
                   7331: 
1.765     albertel 7332: # -------------------------------------------------- portfolio access checking
                   7333: 
                   7334: sub portfolio_access {
1.1172.2.77  raeburn  7335:     my ($requrl,$clientip) = @_;
1.765     albertel 7336:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7337:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7338:     if ($result) {
                   7339:         my %setters;
                   7340:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7341:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7342:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7343:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7344:                 return 'B';
                   7345:             }
                   7346:         } else {
1.1172.2.142  raeburn  7347:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7348:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7349:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7350:                 return 'B';
                   7351:             }
                   7352:         }
                   7353:     }
1.765     albertel 7354:     if ($result eq 'ok') {
1.766     albertel 7355:        return 'F';
1.765     albertel 7356:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7357:        return 'A';
1.765     albertel 7358:     }
1.766     albertel 7359:     return '';
1.765     albertel 7360: }
                   7361: 
                   7362: sub get_portfolio_access {
1.1172.2.77  raeburn  7363:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7364: 
                   7365:     if (!ref($access_hash)) {
                   7366: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7367: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7368: 						   $file_name);
                   7369: 	$access_hash = $access_controls{$file_name};
                   7370:     }
                   7371: 
1.1172.2.77  raeburn  7372:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7373:     my $now = time;
                   7374:     if (ref($access_hash) eq 'HASH') {
                   7375:         foreach my $key (keys(%{$access_hash})) {
                   7376:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7377:             if ($start > $now) {
                   7378:                 next;
                   7379:             }
                   7380:             if ($end && $end<$now) {
                   7381:                 next;
                   7382:             }
                   7383:             if ($scope eq 'public') {
                   7384:                 $public = $key;
                   7385:                 last;
                   7386:             } elsif ($scope eq 'guest') {
                   7387:                 $guest = $key;
                   7388:             } elsif ($scope eq 'domains') {
                   7389:                 push(@domains,$key);
                   7390:             } elsif ($scope eq 'users') {
                   7391:                 push(@users,$key);
                   7392:             } elsif ($scope eq 'course') {
                   7393:                 push(@courses,$key);
                   7394:             } elsif ($scope eq 'group') {
                   7395:                 push(@groups,$key);
1.1172.2.77  raeburn  7396:             } elsif ($scope eq 'ip') {
                   7397:                 push(@ips,$key);
1.765     albertel 7398:             }
                   7399:         }
                   7400:         if ($public) {
                   7401:             return 'ok';
1.1172.2.77  raeburn  7402:         } elsif (@ips > 0) {
                   7403:             my $allowed;
                   7404:             foreach my $ipkey (@ips) {
                   7405:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7406:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7407:                         $allowed = 1;
                   7408:                         last;
                   7409:                     }
                   7410:                 }
                   7411:             }
                   7412:             if ($allowed) {
                   7413:                 return 'ok';
                   7414:             }
1.765     albertel 7415:         }
                   7416:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7417:             if ($guest) {
                   7418:                 return $guest;
                   7419:             }
                   7420:         } else {
                   7421:             if (@domains > 0) {
                   7422:                 foreach my $domkey (@domains) {
                   7423:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7424:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7425:                             return 'ok';
                   7426:                         }
                   7427:                     }
                   7428:                 }
                   7429:             }
                   7430:             if (@users > 0) {
                   7431:                 foreach my $userkey (@users) {
1.865     raeburn  7432:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7433:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7434:                             if (ref($item) eq 'HASH') {
                   7435:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7436:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7437:                                     return 'ok';
                   7438:                                 }
                   7439:                             }
                   7440:                         }
                   7441:                     } 
1.765     albertel 7442:                 }
                   7443:             }
                   7444:             my %roleshash;
                   7445:             my @courses_and_groups = @courses;
                   7446:             push(@courses_and_groups,@groups); 
                   7447:             if (@courses_and_groups > 0) {
                   7448:                 my (%allgroups,%allroles); 
                   7449:                 my ($start,$end,$role,$sec,$group);
                   7450:                 foreach my $envkey (%env) {
1.1060    raeburn  7451:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7452:                         my $cid = $2.'_'.$3; 
                   7453:                         if ($1 eq 'gr') {
                   7454:                             $group = $4;
                   7455:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7456:                         } else {
                   7457:                             if ($4 eq '') {
                   7458:                                 $sec = 'none';
                   7459:                             } else {
                   7460:                                 $sec = $4;
                   7461:                             }
                   7462:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7463:                         }
1.811     albertel 7464:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7465:                         my $cid = $2.'_'.$3;
                   7466:                         if ($4 eq '') {
                   7467:                             $sec = 'none';
                   7468:                         } else {
                   7469:                             $sec = $4;
                   7470:                         }
                   7471:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7472:                     }
                   7473:                 }
                   7474:                 if (keys(%allroles) == 0) {
                   7475:                     return;
                   7476:                 }
                   7477:                 foreach my $key (@courses_and_groups) {
                   7478:                     my %content = %{$$access_hash{$key}};
                   7479:                     my $cnum = $content{'number'};
                   7480:                     my $cdom = $content{'domain'};
                   7481:                     my $cid = $cdom.'_'.$cnum;
                   7482:                     if (!exists($allroles{$cid})) {
                   7483:                         next;
                   7484:                     }    
                   7485:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7486:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7487:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7488:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7489:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7490:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7491:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7492:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7493:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7494:                                         if (grep/^all$/,@sections) {
                   7495:                                             return 'ok';
                   7496:                                         } else {
                   7497:                                             if (grep/^$sec$/,@sections) {
                   7498:                                                 return 'ok';
                   7499:                                             }
                   7500:                                         }
                   7501:                                     }
                   7502:                                 }
                   7503:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7504:                                     if (grep/^none$/,@groups) {
                   7505:                                         return 'ok';
                   7506:                                     }
                   7507:                                 } else {
                   7508:                                     if (grep/^all$/,@groups) {
                   7509:                                         return 'ok';
                   7510:                                     } 
                   7511:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7512:                                         if (grep/^$group$/,@groups) {
                   7513:                                             return 'ok';
                   7514:                                         }
                   7515:                                     }
                   7516:                                 } 
                   7517:                             }
                   7518:                         }
                   7519:                     }
                   7520:                 }
                   7521:             }
                   7522:             if ($guest) {
                   7523:                 return $guest;
                   7524:             }
                   7525:         }
                   7526:     }
                   7527:     return;
                   7528: }
                   7529: 
                   7530: sub course_group_datechecker {
                   7531:     my ($dates,$now,$status) = @_;
                   7532:     my ($start,$end) = split(/\./,$dates);
                   7533:     if (!$start && !$end) {
                   7534:         return 'ok';
                   7535:     }
                   7536:     if (grep/^active$/,@{$status}) {
                   7537:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7538:             return 'ok';
                   7539:         }
                   7540:     }
                   7541:     if (grep/^previous$/,@{$status}) {
                   7542:         if ($end > $now ) {
                   7543:             return 'ok';
                   7544:         }
                   7545:     }
                   7546:     if (grep/^future$/,@{$status}) {
                   7547:         if ($start > $now) {
                   7548:             return 'ok';
                   7549:         }
                   7550:     }
                   7551:     return; 
                   7552: }
                   7553: 
                   7554: sub parse_portfolio_url {
                   7555:     my ($url) = @_;
                   7556: 
                   7557:     my ($type,$udom,$unum,$group,$file_name);
                   7558:     
1.823     albertel 7559:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7560: 	$type = 1;
                   7561:         $udom = $1;
                   7562:         $unum = $2;
                   7563:         $file_name = $3;
1.823     albertel 7564:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7565: 	$type = 2;
                   7566:         $udom = $1;
                   7567:         $unum = $2;
                   7568:         $group = $3;
                   7569:         $file_name = $3.'/'.$4;
                   7570:     }
                   7571:     if (wantarray) {
                   7572: 	return ($type,$udom,$unum,$file_name,$group);
                   7573:     }
                   7574:     return $type;
                   7575: }
                   7576: 
                   7577: sub is_portfolio_url {
                   7578:     my ($url) = @_;
                   7579:     return scalar(&parse_portfolio_url($url));
                   7580: }
                   7581: 
1.798     raeburn  7582: sub is_portfolio_file {
                   7583:     my ($file) = @_;
1.820     raeburn  7584:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7585:         return 1;
                   7586:     }
                   7587:     return;
                   7588: }
                   7589: 
1.976     raeburn  7590: sub usertools_access {
1.1084    raeburn  7591:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7592:     my ($access,%tools);
                   7593:     if ($context eq '') {
                   7594:         $context = 'tools';
                   7595:     }
                   7596:     if ($context eq 'requestcourses') {
                   7597:         %tools = (
                   7598:                       official   => 1,
                   7599:                       unofficial => 1,
1.1006    raeburn  7600:                       community  => 1,
1.1172.2.37  raeburn  7601:                       textbook   => 1,
1.985     raeburn  7602:                  );
1.1172.2.9  raeburn  7603:     } elsif ($context eq 'requestauthor') {
                   7604:         %tools = (
                   7605:                       requestauthor => 1,
                   7606:                  );
1.985     raeburn  7607:     } else {
                   7608:         %tools = (
                   7609:                       aboutme   => 1,
                   7610:                       blog      => 1,
1.1172.2.6  raeburn  7611:                       webdav    => 1,
1.985     raeburn  7612:                       portfolio => 1,
                   7613:                  );
                   7614:     }
1.976     raeburn  7615:     return if (!defined($tools{$tool}));
                   7616: 
1.1172.2.35  raeburn  7617:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7618:         $udom = $env{'user.domain'};
                   7619:         $uname = $env{'user.name'};
                   7620:     }
                   7621: 
1.978     raeburn  7622:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7623:         if ($action ne 'reload') {
1.985     raeburn  7624:             if ($context eq 'requestcourses') {
                   7625:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7626:             } elsif ($context eq 'requestauthor') {
                   7627:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7628:             } else {
                   7629:                 return $env{'environment.availabletools.'.$tool};
                   7630:             }
                   7631:         }
1.976     raeburn  7632:     }
                   7633: 
1.1172.2.9  raeburn  7634:     my ($toolstatus,$inststatus,$envkey);
                   7635:     if ($context eq 'requestauthor') {
                   7636:         $envkey = $context;
                   7637:     } else {
                   7638:         $envkey = $context.'.'.$tool;
                   7639:     }
1.976     raeburn  7640: 
1.985     raeburn  7641:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7642:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7643:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7644:         $inststatus = $env{'environment.inststatus'};
                   7645:     } else {
1.1084    raeburn  7646:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7647:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7648:             $inststatus = $userenvref->{'inststatus'};
                   7649:         } else {
1.1172.2.9  raeburn  7650:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7651:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7652:             $inststatus = $userenv{'inststatus'};
                   7653:         }
1.976     raeburn  7654:     }
                   7655: 
                   7656:     if ($toolstatus ne '') {
                   7657:         if ($toolstatus) {
                   7658:             $access = 1;
                   7659:         } else {
                   7660:             $access = 0;
                   7661:         }
                   7662:         return $access;
                   7663:     }
                   7664: 
1.1084    raeburn  7665:     my ($is_adv,%domdef);
                   7666:     if (ref($is_advref) eq 'HASH') {
                   7667:         $is_adv = $is_advref->{'is_adv'};
                   7668:     } else {
                   7669:         $is_adv = &is_advanced_user($udom,$uname);
                   7670:     }
                   7671:     if (ref($domdefref) eq 'HASH') {
                   7672:         %domdef = %{$domdefref};
                   7673:     } else {
                   7674:         %domdef = &get_domain_defaults($udom);
                   7675:     }
1.976     raeburn  7676:     if (ref($domdef{$tool}) eq 'HASH') {
                   7677:         if ($is_adv) {
                   7678:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7679:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7680:                     $access = 1;
                   7681:                 } else {
                   7682:                     $access = 0;
                   7683:                 }
                   7684:                 return $access;
                   7685:             }
                   7686:         }
                   7687:         if ($inststatus ne '') {
                   7688:             my ($hasaccess,$hasnoaccess);
                   7689:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7690:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7691:                     if ($domdef{$tool}{$affiliation}) {
                   7692:                         $hasaccess = 1;
                   7693:                     } else {
                   7694:                         $hasnoaccess = 1;
                   7695:                     }
                   7696:                 }
                   7697:             }
                   7698:             if ($hasaccess || $hasnoaccess) {
                   7699:                 if ($hasaccess) {
                   7700:                     $access = 1;
                   7701:                 } elsif ($hasnoaccess) {
                   7702:                     $access = 0; 
                   7703:                 }
                   7704:                 return $access;
                   7705:             }
                   7706:         } else {
                   7707:             if ($domdef{$tool}{'default'} ne '') {
                   7708:                 if ($domdef{$tool}{'default'}) {
                   7709:                     $access = 1;
                   7710:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7711:                     $access = 0;
                   7712:                 }
                   7713:                 return $access;
                   7714:             }
                   7715:         }
                   7716:     } else {
1.1172.2.6  raeburn  7717:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7718:             $access = 1;
                   7719:         } else {
                   7720:             $access = 0;
                   7721:         }
1.976     raeburn  7722:         return $access;
                   7723:     }
                   7724: }
                   7725: 
1.1050    raeburn  7726: sub is_course_owner {
                   7727:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7728:     if (($udom eq '') || ($uname eq '')) {
                   7729:         $udom = $env{'user.domain'};
                   7730:         $uname = $env{'user.name'};
                   7731:     }
                   7732:     unless (($udom eq '') || ($uname eq '')) {
                   7733:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7734:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7735:                 return 1;
                   7736:             } else {
                   7737:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7738:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7739:                     return 1;
                   7740:                 }
                   7741:             }
                   7742:         }
                   7743:     }
                   7744:     return;
                   7745: }
                   7746: 
1.976     raeburn  7747: sub is_advanced_user {
                   7748:     my ($udom,$uname) = @_;
1.1085    raeburn  7749:     if ($udom ne '' && $uname ne '') {
                   7750:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7751:             if (wantarray) {
                   7752:                 return ($env{'user.adv'},$env{'user.author'});
                   7753:             } else {
                   7754:                 return $env{'user.adv'};
                   7755:             }
1.1085    raeburn  7756:         }
                   7757:     }
1.976     raeburn  7758:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7759:     my %allroles;
1.1128    raeburn  7760:     my ($is_adv,$is_author);
1.976     raeburn  7761:     foreach my $role (keys(%roleshash)) {
                   7762:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7763:         my $area = '/'.$tdomain.'/'.$trest;
                   7764:         if ($sec ne '') {
                   7765:             $area .= '/'.$sec;
                   7766:         }
                   7767:         if (($area ne '') && ($trole ne '')) {
                   7768:             my $spec=$trole.'.'.$area;
                   7769:             if ($trole =~ /^cr\//) {
                   7770:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7771:             } elsif ($trole ne 'gr') {
                   7772:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7773:             }
1.1128    raeburn  7774:             if ($trole eq 'au') {
                   7775:                 $is_author = 1;
                   7776:             }
1.976     raeburn  7777:         }
                   7778:     }
                   7779:     foreach my $role (keys(%allroles)) {
                   7780:         last if ($is_adv);
                   7781:         foreach my $item (split(/:/,$allroles{$role})) {
                   7782:             if ($item ne '') {
                   7783:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7784:                 if ($privilege eq 'adv') {
                   7785:                     $is_adv = 1;
                   7786:                     last;
                   7787:                 }
                   7788:             }
                   7789:         }
                   7790:     }
1.1128    raeburn  7791:     if (wantarray) {
                   7792:         return ($is_adv,$is_author);
                   7793:     }
1.976     raeburn  7794:     return $is_adv;
                   7795: }
1.798     raeburn  7796: 
1.1035    raeburn  7797: sub check_can_request {
1.1036    raeburn  7798:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7799:     my $canreq = 0;
                   7800:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7801:     my @options = ('approval','validate','autolimit');
                   7802:     my $optregex = join('|',@options);
                   7803:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7804:         foreach my $type (@{$types}) {
                   7805:             if (&usertools_access($env{'user.name'},
                   7806:                                   $env{'user.domain'},
                   7807:                                   $type,undef,'requestcourses')) {
                   7808:                 $canreq ++;
1.1036    raeburn  7809:                 if (ref($request_domains) eq 'HASH') {
                   7810:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7811:                 }
1.1035    raeburn  7812:                 if ($dom eq $env{'user.domain'}) {
                   7813:                     $can_request->{$type} = 1;
                   7814:                 }
                   7815:             }
                   7816:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7817:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7818:                 if (@curr > 0) {
1.1036    raeburn  7819:                     foreach my $item (@curr) {
                   7820:                         if (ref($request_domains) eq 'HASH') {
                   7821:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7822:                             if ($otherdom ne '') {
                   7823:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7824:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7825:                                         push(@{$request_domains->{$type}},$otherdom);
                   7826:                                     }
                   7827:                                 } else {
                   7828:                                     push(@{$request_domains->{$type}},$otherdom);
                   7829:                                 }
                   7830:                             }
                   7831:                         }
                   7832:                     }
                   7833:                     unless($dom eq $env{'user.domain'}) {
                   7834:                         $canreq ++;
1.1035    raeburn  7835:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7836:                             $can_request->{$type} = 1;
                   7837:                         }
                   7838:                     }
                   7839:                 }
                   7840:             }
                   7841:         }
                   7842:     }
                   7843:     return $canreq;
                   7844: }
                   7845: 
1.341     www      7846: # ---------------------------------------------- Custom access rule evaluation
                   7847: 
                   7848: sub customaccess {
                   7849:     my ($priv,$uri)=@_;
1.807     albertel 7850:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7851:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7852:     $udom = &LONCAPA::clean_domain($udom);
                   7853:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7854:     my $access=0;
1.800     albertel 7855:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7856: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7857: 	if ($type eq 'user') {
                   7858: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7859: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7860: 		if ($tdom) {
                   7861: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7862: 		}
1.896     albertel 7863: 		if ($tuname) {
                   7864: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7865: 		}
                   7866: 		$access=($effect eq 'allow');
                   7867: 		last;
                   7868: 	    }
                   7869: 	} else {
                   7870: 	    if ($role) {
                   7871: 		if ($role ne $urole) { next; }
                   7872: 	    }
                   7873: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7874: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7875: 		if ($tdom) {
                   7876: 		    if ($tdom ne $udom) { next; }
                   7877: 		}
                   7878: 		if ($tcrs) {
                   7879: 		    if ($tcrs ne $ucrs) { next; }
                   7880: 		}
                   7881: 		if ($tsec) {
                   7882: 		    if ($tsec ne $usec) { next; }
                   7883: 		}
                   7884: 		$access=($effect eq 'allow');
                   7885: 		last;
                   7886: 	    }
                   7887: 	    if ($realm eq '' && $role eq '') {
                   7888: 		$access=($effect eq 'allow');
                   7889: 	    }
1.402     bowersj2 7890: 	}
1.341     www      7891:     }
                   7892:     return $access;
                   7893: }
                   7894: 
1.103     harris41 7895: # ------------------------------------------------- Check for a user privilege
1.12      www      7896: 
                   7897: sub allowed {
1.1172.2.126  raeburn  7898:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7899:     my $ver_orguri=$uri;
1.439     www      7900:     $uri=&deversion($uri);
1.152     www      7901:     my $orguri=$uri;
1.52      www      7902:     $uri=&declutter($uri);
1.809     raeburn  7903: 
1.810     raeburn  7904:     if ($priv eq 'evb') {
                   7905: # Evade communication block restrictions for specified role in a course
                   7906:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7907:             return $1;
                   7908:         } else {
                   7909:             return;
                   7910:         }
                   7911:     }
                   7912: 
1.620     albertel 7913:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7914: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7915:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7916: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7917: 	&& ($priv eq 'bre')) {
1.14      www      7918: 	return 'F';
1.159     www      7919:     }
                   7920: 
1.545     banghart 7921: # Free bre access to user's own portfolio contents
1.714     raeburn  7922:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7923:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7924: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7925:         my %setters;
1.1172.2.142  raeburn  7926:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   7927:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7928:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7929:             return 'B';
                   7930:         } else {
                   7931:             return 'F';
                   7932:         }
1.545     banghart 7933:     }
                   7934: 
1.762     raeburn  7935: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7936:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7937:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7938:         if (exists($env{'request.course.id'})) {
                   7939:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7940:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7941:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7942:                 my $courseprivid=$env{'request.course.id'};
                   7943:                 $courseprivid=~s/\_/\//;
                   7944:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7945:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7946:                     return $1; 
1.762     raeburn  7947:                 } else {
                   7948:                     if ($env{'request.course.sec'}) {
                   7949:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7950:                     }
                   7951:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7952:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7953:                         return $2;
                   7954:                     }
1.714     raeburn  7955:                 }
                   7956:             }
                   7957:         }
                   7958:     }
                   7959: 
1.159     www      7960: # Free bre to public access
                   7961: 
                   7962:     if ($priv eq 'bre') {
1.238     www      7963:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7964: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7965:            return 'F'; 
                   7966:         }
1.238     www      7967:         if ($copyright eq 'priv') {
                   7968:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7969: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7970: 		return '';
                   7971:             }
                   7972:         }
                   7973:         if ($copyright eq 'domain') {
                   7974:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7975: 	    unless (($env{'user.domain'} eq $1) ||
                   7976:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7977: 		return '';
                   7978:             }
1.262     matthew  7979:         }
1.620     albertel 7980:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7981:             # Library role, so allow browsing of resources in this domain.
                   7982:             return 'F';
1.238     www      7983:         }
1.341     www      7984:         if ($copyright eq 'custom') {
                   7985: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7986:         }
1.14      www      7987:     }
1.264     matthew  7988:     # Domain coordinator is trying to create a course
1.620     albertel 7989:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7990:         # uri is the requested domain in this case.
                   7991:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7992:         # a role of dc for the domain in question.
1.620     albertel 7993:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7994:     }
1.29      www      7995: 
1.52      www      7996:     my $thisallowed='';
                   7997:     my $statecond=0;
                   7998:     my $courseprivid='';
                   7999: 
1.1039    raeburn  8000:     my $ownaccess;
1.1043    raeburn  8001:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8002:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8003:         if ($uri eq '') {
                   8004:             $ownaccess = 1;
                   8005:         } else {
                   8006:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8007:                 my $udom = $env{'user.domain'};
                   8008:                 my $uname = $env{'user.name'};
                   8009:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8010:                     $ownaccess = 1;
1.1040    raeburn  8011:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8012:                     unless ($uri =~ m{\.\./}) {
                   8013:                         $ownaccess = 1;
                   8014:                     }
                   8015:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8016:                     my $now = time;
                   8017:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8018:                         my $adom = $1;
                   8019:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8020:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8021:                                 my ($start,$end) = split(/\./,$env{$key});
                   8022:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8023:                                     $ownaccess = 1;
                   8024:                                     last;
                   8025:                                 }
                   8026:                             }
                   8027:                         }
                   8028:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8029:                         my $adom = $1;
                   8030:                         my $aname = $2;
1.1042    raeburn  8031:                         foreach my $role ('ca','aa') { 
                   8032:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8033:                                 my ($start,$end) =
1.1172.2.142  raeburn  8034:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8035:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8036:                                     $ownaccess = 1;
                   8037:                                     last;
                   8038:                                 }
1.1039    raeburn  8039:                             }
                   8040:                         }
                   8041:                     }
                   8042:                 }
                   8043:             }
                   8044:         }
                   8045:     }
                   8046: 
1.52      www      8047: # Course
                   8048: 
1.620     albertel 8049:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8050:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8051:             $thisallowed.=$1;
                   8052:         }
1.52      www      8053:     }
1.29      www      8054: 
1.52      www      8055: # Domain
                   8056: 
1.620     albertel 8057:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8058:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8059:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8060:             $thisallowed.=$1;
                   8061:         }
1.12      www      8062:     }
1.52      www      8063: 
1.1141    raeburn  8064: # User who is not author or co-author might still be able to edit
                   8065: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8066:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8067:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8068:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8069:             $thisallowed.=$1;
                   8070:         }
                   8071:     }
                   8072: 
1.52      www      8073: # Course: uri itself is a course
1.66      www      8074:     my $courseuri=$uri;
                   8075:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8076:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8077: 
1.620     albertel 8078:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8079:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8080:         if ($priv eq 'mip') {
                   8081:             my $rem = $1;
                   8082:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8083:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8084:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8085:                 if ($cdom ne '') {
                   8086:                     my %passwdconf = &get_passwdconf($cdom);
                   8087:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8088:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8089:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8090:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8091:                                 unless (@inststatuses) {
                   8092:                                     @inststatuses = ('default');
                   8093:                                 }
                   8094:                                 foreach my $status (@inststatuses) {
                   8095:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8096:                                         $thisallowed.=$rem;
                   8097:                                     }
                   8098:                                 }
                   8099:                             }
                   8100:                         }
                   8101:                     }
                   8102:                 }
                   8103:             }
                   8104:         } else {
                   8105:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8106:                 $thisallowed.=$1;
                   8107:             }
1.1039    raeburn  8108:         }
1.12      www      8109:     }
1.29      www      8110: 
1.665     albertel 8111: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8112: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8113:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8114: 	$thisallowed='';
1.671     raeburn  8115:         my ($match)=&is_on_map($uri);
                   8116:         if ($match) {
                   8117:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8118:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8119:                 my $value = $1;
                   8120:                 if ($noblockcheck) {
                   8121:                     $thisallowed.=$value;
1.1162    raeburn  8122:                 } else {
1.1172.2.126  raeburn  8123:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8124:                     if (@blockers > 0) {
                   8125:                         $thisallowed = 'B';
                   8126:                     } else {
                   8127:                         $thisallowed.=$value;
                   8128:                     }
1.1162    raeburn  8129:                 }
1.671     raeburn  8130:             }
                   8131:         } else {
1.705     albertel 8132:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8133:             if ($refuri) {
                   8134:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8135:                     $thisallowed='F';
1.671     raeburn  8136:                 } else {
                   8137:                     $refuri=&declutter($refuri);
                   8138:                     my ($match) = &is_on_map($refuri);
                   8139:                     if ($match) {
1.1172.2.65  raeburn  8140:                         if ($noblockcheck) {
1.1162    raeburn  8141:                             $thisallowed='F';
1.1172.2.65  raeburn  8142:                         } else {
1.1172.2.127  raeburn  8143:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8144:                             if (@blockers > 0) {
                   8145:                                 $thisallowed = 'B';
                   8146:                             } else {
                   8147:                                 $thisallowed='F';
                   8148:                             }
1.1162    raeburn  8149:                         }
1.671     raeburn  8150:                     }
1.669     raeburn  8151:                 }
1.671     raeburn  8152:             }
                   8153:         }
1.314     www      8154:     }
1.492     albertel 8155: 
1.766     albertel 8156:     if ($priv eq 'bre'
                   8157: 	&& $thisallowed ne 'F' 
                   8158: 	&& $thisallowed ne '2'
                   8159: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8160: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8161:     }
                   8162:     
1.52      www      8163: # Full access at system, domain or course-wide level? Exit.
1.29      www      8164:     if ($thisallowed=~/F/) {
                   8165: 	return 'F';
                   8166:     }
                   8167: 
1.52      www      8168: # If this is generating or modifying users, exit with special codes
1.29      www      8169: 
1.643     www      8170:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8171: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8172: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8173: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8174: 	    unless ($auname) { return $thisallowed; }
                   8175: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8176: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8177: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8178: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8179: 	}
1.52      www      8180: 	return $thisallowed;
                   8181:     }
                   8182: #
1.103     harris41 8183: # Gathered so far: system, domain and course wide privileges
1.52      www      8184: #
                   8185: # Course: See if uri or referer is an individual resource that is part of 
                   8186: # the course
                   8187: 
1.620     albertel 8188:     if ($env{'request.course.id'}) {
1.232     www      8189: 
1.1172.2.115  raeburn  8190: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8191: 
                   8192:         if ($priv eq 'mip') {
                   8193:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8194:                 return $thisallowed;
                   8195:             } else {
                   8196:                 return '';
                   8197:             }
                   8198:         }
                   8199: 
1.620     albertel 8200:        $courseprivid=$env{'request.course.id'};
                   8201:        if ($env{'request.course.sec'}) {
                   8202:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8203:        }
                   8204:        $courseprivid=~s/\_/\//;
                   8205:        my $checkreferer=1;
1.232     www      8206:        my ($match,$cond)=&is_on_map($uri);
                   8207:        if ($match) {
                   8208:            $statecond=$cond;
1.620     albertel 8209:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8210:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8211:                my $value = $1;
                   8212:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8213:                    if ($noblockcheck) {
1.1162    raeburn  8214:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8215:                    } else {
1.1172.2.126  raeburn  8216:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8217:                        if (@blockers > 0) {
                   8218:                            $thisallowed = 'B';
                   8219:                        } else {
                   8220:                            $thisallowed.=$value;
                   8221:                        }
1.1162    raeburn  8222:                    }
                   8223:                } else {
                   8224:                    $thisallowed.=$value;
                   8225:                }
1.52      www      8226:                $checkreferer=0;
                   8227:            }
1.29      www      8228:        }
1.1172.2.126  raeburn  8229: 
1.148     www      8230:        if ($checkreferer) {
1.620     albertel 8231: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8232:             unless ($refuri) {
1.800     albertel 8233:                 foreach my $key (keys(%env)) {
                   8234: 		    if ($key=~/^httpref\..*\*/) {
                   8235: 			my $pattern=$key;
1.156     www      8236:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8237:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8238:                         $pattern=~s/\//\\\//g;
1.152     www      8239:                         if ($orguri=~/$pattern/) {
1.800     albertel 8240: 			    $refuri=$env{$key};
1.148     www      8241:                         }
                   8242:                     }
1.191     harris41 8243:                 }
1.148     www      8244:             }
1.232     www      8245: 
1.148     www      8246:          if ($refuri) { 
1.152     www      8247: 	  $refuri=&declutter($refuri);
1.232     www      8248:           my ($match,$cond)=&is_on_map($refuri);
                   8249:             if ($match) {
                   8250:               my $refstatecond=$cond;
1.620     albertel 8251:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8252:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8253:                   my $value = $1;
                   8254:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8255:                       if ($noblockcheck) {
1.1162    raeburn  8256:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8257:                       } else {
1.1172.2.127  raeburn  8258:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8259:                           if (@blockers > 0) {
                   8260:                               $thisallowed = 'B';
                   8261:                           } else {
                   8262:                               $thisallowed.=$value;
                   8263:                           }
1.1162    raeburn  8264:                       }
                   8265:                   } else {
                   8266:                       $thisallowed.=$value;
                   8267:                   }
1.53      www      8268:                   $uri=$refuri;
                   8269:                   $statecond=$refstatecond;
1.52      www      8270:               }
                   8271:           }
1.148     www      8272:         }
1.29      www      8273:        }
1.52      www      8274:    }
1.29      www      8275: 
1.52      www      8276: #
1.103     harris41 8277: # Gathered now: all privileges that could apply, and condition number
1.52      www      8278: # 
                   8279: #
                   8280: # Full or no access?
                   8281: #
1.29      www      8282: 
1.52      www      8283:     if ($thisallowed=~/F/) {
                   8284: 	return 'F';
                   8285:     }
1.29      www      8286: 
1.52      www      8287:     unless ($thisallowed) {
                   8288:         return '';
                   8289:     }
1.29      www      8290: 
1.52      www      8291: # Restrictions exist, deal with them
                   8292: #
                   8293: #   C:according to course preferences
                   8294: #   R:according to resource settings
                   8295: #   L:unless locked
                   8296: #   X:according to user session state
                   8297: #
                   8298: 
                   8299: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8300: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8301: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8302: # courses, and 2 minutes for current course, in which user has st or ta role
                   8303: # which is neither expired nor a future role (unless current course).
1.52      www      8304: 
1.1172.2.142  raeburn  8305:     my ($needlockcheck,$now,$crsonly);
1.52      www      8306:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8307:         $now = time;
                   8308:         if ($priv eq 'bre') {
                   8309:             if ($uri ne '') {
                   8310:                 if ($orguri =~ m{^/+res/}) {
                   8311:                     if ($uri =~ m{^lib/templates/}) {
                   8312:                         if ($env{'request.course.id'}) {
                   8313:                             $crsonly = 1;
                   8314:                             $needlockcheck = 1;
                   8315:                         }
                   8316:                     } else {
                   8317:                         $needlockcheck = 1;
                   8318:                     }
                   8319:                 } elsif ($env{'request.course.id'}) {
                   8320:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8321:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8322:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8323:                         $crsonly = 1;
                   8324:                     }
                   8325:                     $needlockcheck = 1;
                   8326:                 }
                   8327:             }
                   8328:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8329:             $needlockcheck = 1;
                   8330:         }
                   8331:     }
                   8332:     if ($needlockcheck) {
                   8333:         foreach my $envkey (keys(%env)) {
1.54      www      8334:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8335:                my $courseid=$2;
                   8336:                my $roleid=$1.'.'.$2;
1.92      www      8337:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8338:                unless ($env{'request.role'} eq $roleid) {
                   8339:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8340:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8341:                }
1.54      www      8342:                my $expiretime=600;
1.620     albertel 8343:                if ($env{'request.role'} eq $roleid) {
1.54      www      8344: 		  $expiretime=120;
                   8345:                }
                   8346: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8347:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8348:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8349: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8350:                }
1.620     albertel 8351:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8352:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8353: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8354:                        &log($env{'user.domain'},$env{'user.name'},
                   8355:                             $env{'user.home'},
1.57      www      8356:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8357:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8358:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8359: 		       return '';
                   8360:                    }
                   8361:                }
1.620     albertel 8362:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8363:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8364: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8365:                        &log($env{'user.domain'},$env{'user.name'},
                   8366:                             $env{'user.home'},
1.57      www      8367:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8368:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8369:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8370: 		       return '';
                   8371:                    }
                   8372:                }
                   8373: 	   }
1.29      www      8374:        }
1.52      www      8375:     }
1.1172.2.126  raeburn  8376: 
1.52      www      8377: #
                   8378: # Rest of the restrictions depend on selected course
                   8379: #
                   8380: 
1.620     albertel 8381:     unless ($env{'request.course.id'}) {
1.766     albertel 8382: 	if ($thisallowed eq 'A') {
                   8383: 	    return 'A';
1.814     raeburn  8384:         } elsif ($thisallowed eq 'B') {
                   8385:             return 'B';
1.766     albertel 8386: 	} else {
                   8387: 	    return '1';
                   8388: 	}
1.52      www      8389:     }
1.29      www      8390: 
1.52      www      8391: #
                   8392: # Now user is definitely in a course
                   8393: #
1.53      www      8394: 
                   8395: 
                   8396: # Course preferences
                   8397: 
                   8398:    if ($thisallowed=~/C/) {
1.620     albertel 8399:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8400:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8401:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8402: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8403: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8404: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8405: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8406: 			$env{'request.course.id'});
                   8407: 	   }
1.237     www      8408:            return '';
                   8409:        }
                   8410: 
1.620     albertel 8411:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8412: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8413: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8414: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8415: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8416: 			$env{'request.course.id'});
                   8417: 	   }
1.54      www      8418:            return '';
                   8419:        }
1.53      www      8420:    }
                   8421: 
                   8422: # Resource preferences
                   8423: 
                   8424:    if ($thisallowed=~/R/) {
1.620     albertel 8425:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8426:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8427: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8428: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8429: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8430: 	   }
                   8431: 	   return '';
1.54      www      8432:        }
1.53      www      8433:    }
1.30      www      8434: 
1.246     www      8435: # Restricted by state or randomout?
1.30      www      8436: 
1.52      www      8437:    if ($thisallowed=~/X/) {
1.620     albertel 8438:       if ($env{'acc.randomout'}) {
1.579     albertel 8439: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8440:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8441:             return ''; 
                   8442:          }
1.247     www      8443:       }
                   8444:       if (&condval($statecond)) {
1.52      www      8445: 	 return '2';
                   8446:       } else {
                   8447:          return '';
                   8448:       }
                   8449:    }
1.30      www      8450: 
1.766     albertel 8451:     if ($thisallowed eq 'A') {
                   8452: 	return 'A';
1.814     raeburn  8453:     } elsif ($thisallowed eq 'B') {
                   8454:         return 'B';
1.766     albertel 8455:     }
1.52      www      8456:    return 'F';
1.232     www      8457: }
1.1162    raeburn  8458: 
1.1172.2.13  raeburn  8459: # ------------------------------------------- Check construction space access
                   8460: 
                   8461: sub constructaccess {
                   8462:     my ($url,$setpriv)=@_;
                   8463: 
                   8464: # We do not allow editing of previous versions of files
                   8465:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8466: 
                   8467: # Get username and domain from URL
                   8468:     my ($ownername,$ownerdomain,$ownerhome);
                   8469: 
                   8470:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8471:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8472: 
                   8473: # The URL does not really point to any authorspace, forget it
                   8474:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8475: 
                   8476: # Now we need to see if the user has access to the authorspace of
                   8477: # $ownername at $ownerdomain
                   8478: 
                   8479:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8480: # Real author for this?
                   8481:        $ownerhome = $env{'user.home'};
                   8482:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8483:           return ($ownername,$ownerdomain,$ownerhome);
                   8484:        }
                   8485:     } else {
                   8486: # Co-author for this?
                   8487:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8488:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8489:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8490:             return ($ownername,$ownerdomain,$ownerhome);
                   8491:         }
                   8492:     }
                   8493: 
                   8494: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8495: # we might as well leave
                   8496:    unless ($setpriv) { return ''; }
                   8497: 
                   8498: # Backdoor access?
                   8499:     my $allowed=&allowed('eco',$ownerdomain);
                   8500: # Nope
                   8501:     unless ($allowed) { return ''; }
                   8502: # Looks like we may have access, but could be locked by the owner of the construction space
                   8503:     if ($allowed eq 'U') {
                   8504:         my %blocked=&get('environment',['domcoord.author'],
                   8505:                          $ownerdomain,$ownername);
                   8506: # Is blocked by owner
                   8507:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8508:     }
                   8509:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8510: # Grant temporary access
                   8511:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8512:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8513:         if (!$update) { $update = $then; }
                   8514:         my $refresh=$env{'user.refresh.time'};
                   8515:         if (!$refresh) { $refresh = $update; }
                   8516:         my $now = time;
                   8517:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8518:                            $now,'ca','constructaccess');
                   8519:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8520:         return($ownername,$ownerdomain,$ownerhome);
                   8521:     }
                   8522: # No business here
                   8523:     return '';
                   8524: }
                   8525: 
1.1172.2.66  raeburn  8526: # ----------------------------------------------------------- Content Blocking
                   8527: 
                   8528: {
                   8529: # Caches for faster Course Contents display where content blocking
                   8530: # is in operation (i.e., interval param set) for timed quiz.
                   8531: #
                   8532: # User for whom data are being temporarily cached.
                   8533: my $cacheduser='';
1.1172.2.126  raeburn  8534: # Course for which data are being temporarily cached.
                   8535: my $cachedcid='';
1.1172.2.66  raeburn  8536: # Cached blockers for this user (a hash of blocking items).
                   8537: my %cachedblockers=();
                   8538: # When the data were last cached.
                   8539: my $cachedlast='';
                   8540: 
                   8541: sub load_all_blockers {
1.1172.2.128  raeburn  8542:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8543:     if (($uname ne '') && ($udom ne '')) {
                   8544:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8545:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8546:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8547:             return;
                   8548:         }
                   8549:     }
                   8550:     $cachedlast=time;
                   8551:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8552:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8553:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8554:     return;
1.1172.2.66  raeburn  8555: }
                   8556: 
1.1162    raeburn  8557: sub get_comm_blocks {
                   8558:     my ($cdom,$cnum) = @_;
                   8559:     if ($cdom eq '' || $cnum eq '') {
                   8560:         return unless ($env{'request.course.id'});
                   8561:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8562:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8563:     }
                   8564:     my %commblocks;
                   8565:     my $hashid=$cdom.'_'.$cnum;
                   8566:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8567:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8568:         %commblocks = %{$blocksref};
                   8569:     } else {
                   8570:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8571:         my $cachetime = 600;
                   8572:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8573:     }
                   8574:     return %commblocks;
                   8575: }
                   8576: 
1.1172.2.66  raeburn  8577: sub get_commblock_resources {
                   8578:     my ($blocks) = @_;
                   8579:     my %blockers = ();
                   8580:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8581:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8582:     if ($env{'request.course.sec'}) {
                   8583:         $courseurl .= '/'.$env{'request.course.sec'};
                   8584:     }
                   8585:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8586:     my %commblocks;
                   8587:     if (ref($blocks) eq 'HASH') {
                   8588:         %commblocks = %{$blocks};
                   8589:     } else {
                   8590:         %commblocks = &get_comm_blocks();
                   8591:     }
1.1172.2.66  raeburn  8592:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8593:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8594:     return %blockers unless (ref($navmap));
                   8595:     my $now = time;
1.1162    raeburn  8596:     foreach my $block (keys(%commblocks)) {
                   8597:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8598:             my ($start,$end) = ($1,$2);
                   8599:             if ($start <= $now && $end >= $now) {
                   8600:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8601:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8602:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8603:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8604:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8605:                             }
                   8606:                         }
                   8607:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8608:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8609:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8610:                             }
                   8611:                         }
                   8612:                     }
                   8613:                 }
                   8614:             }
                   8615:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8616:             my $item = $1;
                   8617:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8618:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8619:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8620:                     my $type = 'map';
                   8621:                     if ($item eq 'course') {
                   8622:                         $type = 'course';
                   8623:                         @interval=&EXT("resource.0.interval");
                   8624:                     } else {
                   8625:                         if ($item =~ /___\d+___/) {
                   8626:                             $type = 'resource';
                   8627:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8628:                         } else {
1.1172.2.142  raeburn  8629:                             $mapname = &deversion($item);
                   8630:                             if (ref($navmap)) {
                   8631:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8632:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8633:                             }
                   8634:                         }
1.1172.2.66  raeburn  8635:                     }
                   8636:                     if ($interval[0] =~ /^\d+$/) {
                   8637:                         my $first_access;
                   8638:                         if ($type eq 'resource') {
                   8639:                             $first_access=&get_first_access($interval[1],$item);
                   8640:                         } elsif ($type eq 'map') {
                   8641:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8642:                         } else {
                   8643:                             $first_access=&get_first_access($interval[1]);
                   8644:                         }
                   8645:                         if ($first_access) {
                   8646:                             my $timesup = $first_access+$interval[0];
                   8647:                             if ($timesup > $now) {
                   8648:                                 my $activeblock;
1.1172.2.142  raeburn  8649:                                 if ($type eq 'resource') {
                   8650:                                     if (ref($navmap)) {
                   8651:                                         my $res = $navmap->getBySymb($item);
                   8652:                                         if ($res->answerable()) {
                   8653:                                             $activeblock = 1;
                   8654:                                         }
                   8655:                                     }
                   8656:                                 } elsif ($type eq 'map') {
                   8657:                                     my $mapsymb = &symbread($mapname,1);
                   8658:                                     if (($mapsymb) && (ref($navmap))) {
                   8659:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8660:                                         if (ref($mapres)) {
                   8661:                                             my $first = $mapres->map_start();
                   8662:                                             my $finish = $mapres->map_finish();
                   8663:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8664:                                             if (ref($it)) {
                   8665:                                                 my $res;
                   8666:                                                 while ($res = $it->next(undef,1)) {
                   8667:                                                     next unless (ref($res));
                   8668:                                                     my $symb = $res->symb();
                   8669:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8670:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8671:                                                     if ($interval[1] eq 'map') {
                   8672:                                                         if ($res->answerable()) {
                   8673:                                                             $activeblock = 1;
                   8674:                                                             last;
                   8675:                                                         }
                   8676:                                                     }
                   8677:                                                 }
                   8678:                                             }
                   8679:                                         }
1.1172.2.66  raeburn  8680:                                     }
                   8681:                                 }
                   8682:                                 if ($activeblock) {
                   8683:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8684:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8685:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8686:                                          }
                   8687:                                     }
                   8688:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8689:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8690:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8691:                                         }
1.1162    raeburn  8692:                                     }
                   8693:                                 }
                   8694:                             }
                   8695:                         }
                   8696:                     }
                   8697:                 }
                   8698:             }
                   8699:         }
                   8700:     }
1.1172.2.66  raeburn  8701:     return %blockers;
1.1162    raeburn  8702: }
                   8703: 
1.1172.2.66  raeburn  8704: sub has_comm_blocking {
1.1172.2.128  raeburn  8705:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8706:     my @blockers;
                   8707:     return unless ($env{'request.course.id'});
                   8708:     return unless ($priv eq 'bre');
                   8709:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8710:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8711:     if ($env{'request.course.sec'}) {
                   8712:         $courseurl .= '/'.$env{'request.course.sec'};
                   8713:     }
                   8714:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8715:     my %blockinfo;
                   8716:     if (ref($blocks) eq 'HASH') {
                   8717:         %blockinfo = &get_commblock_resources($blocks);
                   8718:     } else {
                   8719:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8720:         %blockinfo = %cachedblockers;
                   8721:     }
                   8722:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8723:     my (%possibles,@symbs);
                   8724:     if (!$symb) {
1.1172.2.128  raeburn  8725:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8726:     }
1.1172.2.66  raeburn  8727:     if ($symb) {
                   8728:         @symbs = ($symb);
                   8729:     } elsif (keys(%possibles)) {
                   8730:         @symbs = keys(%possibles);
                   8731:     }
                   8732:     my $noblock;
                   8733:     foreach my $symb (@symbs) {
                   8734:         last if ($noblock);
                   8735:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8736:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8737:             if ($block =~ /^firstaccess____(.+)$/) {
                   8738:                 my $item = $1;
1.1172.2.126  raeburn  8739:                 unless ($blocked) {
                   8740:                     if (($item eq $map) || ($item eq $symb)) {
                   8741:                         $noblock = 1;
                   8742:                         last;
                   8743:                     }
1.1172.2.66  raeburn  8744:                 }
1.1162    raeburn  8745:             }
1.1172.2.128  raeburn  8746:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8747:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8748:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8749:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8750:                             push(@blockers,$block);
                   8751:                         }
                   8752:                     }
                   8753:                 }
1.1172.2.128  raeburn  8754:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8755:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8756:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8757:                             push(@blockers,$block);
                   8758:                         }
1.1172.2.66  raeburn  8759:                     }
                   8760:                 }
1.1162    raeburn  8761:             }
                   8762:         }
                   8763:     }
1.1172.2.126  raeburn  8764:     unless ($noblock) {
                   8765:         return @blockers;
                   8766:     }
                   8767:     return;
1.1172.2.66  raeburn  8768: }
1.1162    raeburn  8769: }
                   8770: 
1.1172.2.66  raeburn  8771: # -------------------------------- Deversion and split uri into path an filename
                   8772: 
1.1133    foxr     8773: #
1.1172.2.66  raeburn  8774: #   Removes the version from a URI and
1.1133    foxr     8775: #   splits it in to its filename and path to the filename.
                   8776: #   Seems like File::Basename could have done this more clearly.
                   8777: #   Parameters:
                   8778: #      $uri   - input URI
                   8779: #   Returns:
                   8780: #     Two element list consisting of 
                   8781: #     $pathname  - the URI up to and excluding the trailing /
                   8782: #     $filename  - The part of the URI following the last /
                   8783: #  NOTE:
                   8784: #    Another realization of this is simply:
                   8785: #    use File::Basename;
                   8786: #    ...
                   8787: #    $uri = shift;
                   8788: #    $filename = basename($uri);
                   8789: #    $path     = dirname($uri);
                   8790: #    return ($filename, $path);
                   8791: #
                   8792: #     The implementation below is probably faster however.
                   8793: #
1.710     albertel 8794: sub split_uri_for_cond {
                   8795:     my $uri=&deversion(&declutter(shift));
                   8796:     my @uriparts=split(/\//,$uri);
                   8797:     my $filename=pop(@uriparts);
                   8798:     my $pathname=join('/',@uriparts);
                   8799:     return ($pathname,$filename);
                   8800: }
1.232     www      8801: # --------------------------------------------------- Is a resource on the map?
                   8802: 
                   8803: sub is_on_map {
1.710     albertel 8804:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8805:     #Trying to find the conditional for the file
1.620     albertel 8806:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8807: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8808:     if ($match) {
1.289     bowersj2 8809: 	return (1,$1);
                   8810:     } else {
1.434     www      8811: 	return (0,0);
1.289     bowersj2 8812:     }
1.12      www      8813: }
                   8814: 
1.427     www      8815: # --------------------------------------------------------- Get symb from alias
                   8816: 
                   8817: sub get_symb_from_alias {
                   8818:     my $symb=shift;
                   8819:     my ($map,$resid,$url)=&decode_symb($symb);
                   8820: # Already is a symb
                   8821:     if ($url) { return $symb; }
                   8822: # Must be an alias
                   8823:     my $aliassymb='';
                   8824:     my %bighash;
1.620     albertel 8825:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8826:                             &GDBM_READER(),0640)) {
                   8827:         my $rid=$bighash{'mapalias_'.$symb};
                   8828: 	if ($rid) {
                   8829: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8830: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8831: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8832: 	}
                   8833:         untie %bighash;
                   8834:     }
                   8835:     return $aliassymb;
                   8836: }
                   8837: 
1.12      www      8838: # ----------------------------------------------------------------- Define Role
                   8839: 
                   8840: sub definerole {
                   8841:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8842:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8843:     foreach my $role (split(':',$sysrole)) {
                   8844: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8845:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8846:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8847: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8848:                return "refused:s:$crole&$cqual"; 
                   8849:             }
                   8850:         }
1.191     harris41 8851:     }
1.800     albertel 8852:     foreach my $role (split(':',$domrole)) {
                   8853: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8854:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8855:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8856: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8857:                return "refused:d:$crole&$cqual"; 
                   8858:             }
                   8859:         }
1.191     harris41 8860:     }
1.800     albertel 8861:     foreach my $role (split(':',$courole)) {
                   8862: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8863:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8864:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8865: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8866:                return "refused:c:$crole&$cqual"; 
                   8867:             }
                   8868:         }
1.191     harris41 8869:     }
1.1172.2.84  raeburn  8870:     my $uhome;
                   8871:     if (($uname ne '') && ($udom ne '')) {
                   8872:         $uhome = &homeserver($uname,$udom);
                   8873:         return $uhome if ($uhome eq 'no_host');
                   8874:     } else {
                   8875:         $uname = $env{'user.name'};
                   8876:         $udom = $env{'user.domain'};
                   8877:         $uhome = $env{'user.home'};
                   8878:     }
1.620     albertel 8879:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8880:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8881:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8882:     return reply($command,$uhome);
1.12      www      8883:   } else {
                   8884:     return 'refused';
                   8885:   }
1.105     harris41 8886: }
                   8887: 
                   8888: # ---------------- Make a metadata query against the network of library servers
                   8889: 
                   8890: sub metadata_query {
1.1172.2.33  raeburn  8891:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8892:     my %rhash;
1.845     albertel 8893:     my %libserv = &all_library();
1.244     matthew  8894:     my @server_list = (defined($server_array) ? @$server_array
                   8895:                                               : keys(%libserv) );
                   8896:     for my $server (@server_list) {
1.1172.2.33  raeburn  8897:         my $domains = '';
                   8898:         if (ref($domains_hash) eq 'HASH') {
                   8899:             $domains = $domains_hash->{$server};    
                   8900:         }
1.118     harris41 8901: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8902: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8903: 	    $rhash{$server}=$reply;
                   8904: 	}
                   8905: 	else {
                   8906: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8907: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8908: 			     $server);
                   8909: 	    $rhash{$server}=$reply;
                   8910: 	}
1.112     harris41 8911:     }
1.118     harris41 8912:     return \%rhash;
1.240     www      8913: }
                   8914: 
                   8915: # ----------------------------------------- Send log queries and wait for reply
                   8916: 
                   8917: sub log_query {
                   8918:     my ($uname,$udom,$query,%filters)=@_;
                   8919:     my $uhome=&homeserver($uname,$udom);
                   8920:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8921:     my $uhost=&hostname($uhome);
1.800     albertel 8922:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8923:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8924:                        $uhome);
1.479     albertel 8925:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8926:     return get_query_reply($queryid);
                   8927: }
                   8928: 
1.818     raeburn  8929: # -------------------------- Update MySQL table for portfolio file
                   8930: 
                   8931: sub update_portfolio_table {
1.821     raeburn  8932:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8933:     if ($group ne '') {
                   8934:         $file_name =~s /^\Q$group\E//;
                   8935:     }
1.818     raeburn  8936:     my $homeserver = &homeserver($uname,$udom);
                   8937:     my $queryid=
1.821     raeburn  8938:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8939:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8940:     my $reply = &get_query_reply($queryid);
                   8941:     return $reply;
                   8942: }
                   8943: 
1.899     raeburn  8944: # -------------------------- Update MySQL allusers table
                   8945: 
                   8946: sub update_allusers_table {
                   8947:     my ($uname,$udom,$names) = @_;
                   8948:     my $homeserver = &homeserver($uname,$udom);
                   8949:     my $queryid=
                   8950:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8951:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8952:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8953:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8954:                'generation='.&escape($names->{'generation'}).'%%'.
                   8955:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8956:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8957:     return;
1.899     raeburn  8958: }
                   8959: 
1.508     raeburn  8960: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8961: 
                   8962: sub fetch_enrollment_query {
1.511     raeburn  8963:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8964:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8965:     my $maxtries = 1;
1.508     raeburn  8966:     if ($context eq 'automated') {
                   8967:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8968:         $sleep = 2;
                   8969:         $loopmax = 100;
1.547     raeburn  8970:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8971:     } else {
                   8972:         $homeserver = &homeserver($cnum,$dom);
                   8973:     }
1.838     albertel 8974:     my $host=&hostname($homeserver);
1.506     raeburn  8975:     my $cmd = '';
1.1000    raeburn  8976:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8977:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8978:     }
                   8979:     $cmd =~ s/%%$//;
                   8980:     $cmd = &escape($cmd);
                   8981:     my $query = 'fetchenrollment';
1.620     albertel 8982:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8983:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8984:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8985:         return 'error: '.$queryid;
                   8986:     }
1.1172.2.93  raeburn  8987:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8988:     my $tries = 1;
                   8989:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8990:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8991:         $tries ++;
                   8992:     }
1.526     raeburn  8993:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8994:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8995:     } else {
1.901     albertel 8996:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8997:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8998:             foreach my $line (@responses) {
                   8999:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9000:                 $$replyref{$key} = $value;
                   9001:             }
                   9002:         } else {
1.1117    foxr     9003:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9004:             foreach my $line (@responses) {
                   9005:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9006:                 $$replyref{$key} = $value;
                   9007:                 if ($value > 0) {
1.800     albertel 9008:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9009:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9010:                         my $destname = $pathname.'/'.$filename;
                   9011:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9012:                         if ($xml_classlist =~ /^error/) {
                   9013:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9014:                         } else {
1.1172.2.96  raeburn  9015:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9016:                                 print FILE &unescape($xml_classlist);
                   9017:                                 close(FILE);
1.526     raeburn  9018:                             } else {
                   9019:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9020:                             }
                   9021:                         }
                   9022:                     }
                   9023:                 }
                   9024:             }
                   9025:         }
                   9026:         return 'ok';
                   9027:     }
                   9028:     return 'error';
                   9029: }
                   9030: 
1.242     www      9031: sub get_query_reply {
1.1172.2.79  raeburn  9032:     my ($queryid,$sleep,$loopmax) = @_;
                   9033:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9034:         $sleep = 0.2;
                   9035:     }
                   9036:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9037:         $loopmax = 100;
                   9038:     }
1.1117    foxr     9039:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9040:     my $reply='';
1.1172.2.79  raeburn  9041:     for (1..$loopmax) {
                   9042: 	sleep($sleep);
1.240     www      9043:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9044: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9045: 		$reply = join('',<$fh>);
                   9046: 		close($fh);
1.240     www      9047: 	   } else { return 'error: reply_file_error'; }
1.242     www      9048:            return &unescape($reply);
                   9049: 	}
1.240     www      9050:     }
1.242     www      9051:     return 'timeout:'.$queryid;
1.240     www      9052: }
                   9053: 
                   9054: sub courselog_query {
1.241     www      9055: #
                   9056: # possible filters:
                   9057: # url: url or symb
                   9058: # username
                   9059: # domain
                   9060: # action: view, submit, grade
                   9061: # start: timestamp
                   9062: # end: timestamp
                   9063: #
1.240     www      9064:     my (%filters)=@_;
1.620     albertel 9065:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9066:     if ($filters{'url'}) {
                   9067: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9068:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9069:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9070:     }
1.620     albertel 9071:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9072:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9073:     return &log_query($cname,$cdom,'courselog',%filters);
                   9074: }
                   9075: 
                   9076: sub userlog_query {
1.858     raeburn  9077: #
                   9078: # possible filters:
                   9079: # action: log check role
                   9080: # start: timestamp
                   9081: # end: timestamp
                   9082: #
1.240     www      9083:     my ($uname,$udom,%filters)=@_;
                   9084:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9085: }
                   9086: 
1.506     raeburn  9087: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9088: 
                   9089: sub auto_run {
1.508     raeburn  9090:     my ($cnum,$cdom) = @_;
1.876     raeburn  9091:     my $response = 0;
                   9092:     my $settings;
                   9093:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9094:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9095:         $settings = $domconfig{'autoenroll'};
                   9096:         if ($settings->{'run'} eq '1') {
                   9097:             $response = 1;
                   9098:         }
                   9099:     } else {
1.934     raeburn  9100:         my $homeserver;
                   9101:         if (&is_course($cdom,$cnum)) {
                   9102:             $homeserver = &homeserver($cnum,$cdom);
                   9103:         } else {
                   9104:             $homeserver = &domain($cdom,'primary');
                   9105:         }
                   9106:         if ($homeserver ne 'no_host') {
                   9107:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9108:         }
1.876     raeburn  9109:     }
1.506     raeburn  9110:     return $response;
                   9111: }
1.776     albertel 9112: 
1.506     raeburn  9113: sub auto_get_sections {
1.508     raeburn  9114:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9115:     my $homeserver;
                   9116:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9117:         $homeserver = &homeserver($cnum,$cdom);
                   9118:     }
                   9119:     if (!defined($homeserver)) { 
                   9120:         if ($cdom =~ /^$match_domain$/) {
                   9121:             $homeserver = &domain($cdom,'primary');
                   9122:         }
                   9123:     }
                   9124:     my @secs;
                   9125:     if (defined($homeserver)) {
                   9126:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9127:         unless ($response eq 'refused') {
                   9128:             @secs = split(/:/,$response);
                   9129:         }
1.506     raeburn  9130:     }
                   9131:     return @secs;
                   9132: }
1.776     albertel 9133: 
1.506     raeburn  9134: sub auto_new_course {
1.1099    raeburn  9135:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9136:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9137:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9138:     return $response;
                   9139: }
1.776     albertel 9140: 
1.506     raeburn  9141: sub auto_validate_courseID {
1.508     raeburn  9142:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9143:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9144:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9145:     return $response;
                   9146: }
1.776     albertel 9147: 
1.1007    raeburn  9148: sub auto_validate_instcode {
1.1020    raeburn  9149:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9150:     my ($homeserver,$response);
                   9151:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9152:         $homeserver = &homeserver($cnum,$cdom);
                   9153:     }
                   9154:     if (!defined($homeserver)) {
                   9155:         if ($cdom =~ /^$match_domain$/) {
                   9156:             $homeserver = &domain($cdom,'primary');
                   9157:         }
                   9158:     }
1.1065    raeburn  9159:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9160:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9161:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9162:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9163: }
                   9164: 
1.1172.2.141  raeburn  9165: sub auto_validate_inst_crosslist {
                   9166:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9167:     my ($homeserver,$response);
                   9168:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9169:         $homeserver = &homeserver($cnum,$cdom);
                   9170:     }
                   9171:     if (!defined($homeserver)) {
                   9172:         if ($cdom =~ /^$match_domain$/) {
                   9173:             $homeserver = &domain($cdom,'primary');
                   9174:         }
                   9175:     }
                   9176:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9177:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9178:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9179:                          &escape($coowner),$homeserver);
                   9180:     }
                   9181:     return $response;
                   9182: }
                   9183: 
1.506     raeburn  9184: sub auto_create_password {
1.873     raeburn  9185:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9186:     my ($homeserver,$response);
1.506     raeburn  9187:     my $create_passwd = 0;
                   9188:     my $authchk = '';
1.873     raeburn  9189:     if ($udom =~ /^$match_domain$/) {
                   9190:         $homeserver = &domain($udom,'primary');
                   9191:     }
                   9192:     if ($homeserver eq '') {
                   9193:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9194:             $homeserver = &homeserver($cnum,$cdom);
                   9195:         }
                   9196:     }
                   9197:     if ($homeserver eq '') {
                   9198:         $authchk = 'nodomain';
1.506     raeburn  9199:     } else {
1.873     raeburn  9200:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9201:         if ($response eq 'refused') {
                   9202:             $authchk = 'refused';
                   9203:         } else {
1.901     albertel 9204:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9205:         }
1.506     raeburn  9206:     }
                   9207:     return ($authparam,$create_passwd,$authchk);
                   9208: }
                   9209: 
1.706     raeburn  9210: sub auto_photo_permission {
                   9211:     my ($cnum,$cdom,$students) = @_;
                   9212:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9213:     my ($outcome,$perm_reqd,$conditions) = 
                   9214: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9215:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9216: 	return (undef,undef);
                   9217:     }
1.706     raeburn  9218:     return ($outcome,$perm_reqd,$conditions);
                   9219: }
                   9220: 
                   9221: sub auto_checkphotos {
                   9222:     my ($uname,$udom,$pid) = @_;
                   9223:     my $homeserver = &homeserver($uname,$udom);
                   9224:     my ($result,$resulttype);
                   9225:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9226: 				   &escape($uname).':'.&escape($pid),
                   9227: 				   $homeserver));
1.709     albertel 9228:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9229: 	return (undef,undef);
                   9230:     }
1.706     raeburn  9231:     if ($outcome) {
                   9232:         ($result,$resulttype) = split(/:/,$outcome);
                   9233:     } 
                   9234:     return ($result,$resulttype);
                   9235: }
                   9236: 
                   9237: sub auto_photochoice {
                   9238:     my ($cnum,$cdom) = @_;
                   9239:     my $homeserver = &homeserver($cnum,$cdom);
                   9240:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9241: 						       &escape($cdom),
                   9242: 						       $homeserver)));
1.709     albertel 9243:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9244: 	return (undef,undef);
                   9245:     }
1.706     raeburn  9246:     return ($update,$comment);
                   9247: }
                   9248: 
                   9249: sub auto_photoupdate {
                   9250:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9251:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9252:     my $host=&hostname($homeserver);
1.706     raeburn  9253:     my $cmd = '';
                   9254:     my $maxtries = 1;
1.800     albertel 9255:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9256:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9257:     }
                   9258:     $cmd =~ s/%%$//;
                   9259:     $cmd = &escape($cmd);
                   9260:     my $query = 'institutionalphotos';
                   9261:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9262:     unless ($queryid=~/^\Q$host\E\_/) {
                   9263:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9264:         return 'error: '.$queryid;
                   9265:     }
                   9266:     my $reply = &get_query_reply($queryid);
                   9267:     my $tries = 1;
                   9268:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9269:         $reply = &get_query_reply($queryid);
                   9270:         $tries ++;
                   9271:     }
                   9272:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9273:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9274:     } else {
                   9275:         my @responses = split(/:/,$reply);
                   9276:         my $outcome = shift(@responses); 
                   9277:         foreach my $item (@responses) {
                   9278:             my ($key,$value) = split(/=/,$item);
                   9279:             $$photo{$key} = $value;
                   9280:         }
                   9281:         return $outcome;
                   9282:     }
                   9283:     return 'error';
                   9284: }
                   9285: 
1.521     raeburn  9286: sub auto_instcode_format {
1.793     albertel 9287:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9288: 	$cat_order) = @_;
1.521     raeburn  9289:     my $courses = '';
1.772     raeburn  9290:     my @homeservers;
1.521     raeburn  9291:     if ($caller eq 'global') {
1.841     albertel 9292: 	my %servers = &get_servers($codedom,'library');
                   9293: 	foreach my $tryserver (keys(%servers)) {
                   9294: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9295: 		push(@homeservers,$tryserver);
                   9296: 	    }
1.584     raeburn  9297:         }
1.1022    raeburn  9298:     } elsif ($caller eq 'requests') {
                   9299:         if ($codedom =~ /^$match_domain$/) {
                   9300:             my $chome = &domain($codedom,'primary');
                   9301:             unless ($chome eq 'no_host') {
                   9302:                 push(@homeservers,$chome);
                   9303:             }
                   9304:         }
1.521     raeburn  9305:     } else {
1.772     raeburn  9306:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9307:     }
1.793     albertel 9308:     foreach my $code (keys(%{$instcodes})) {
                   9309:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9310:     }
                   9311:     chop($courses);
1.772     raeburn  9312:     my $ok_response = 0;
                   9313:     my $response;
                   9314:     while (@homeservers > 0 && $ok_response == 0) {
                   9315:         my $server = shift(@homeservers); 
                   9316:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9317:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9318:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9319: 		split(/:/,$response);
1.772     raeburn  9320:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9321:             push(@{$codetitles},&str2array($codetitles_str));
                   9322:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9323:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9324:             $ok_response = 1;
                   9325:         }
                   9326:     }
                   9327:     if ($ok_response) {
1.521     raeburn  9328:         return 'ok';
1.772     raeburn  9329:     } else {
                   9330:         return $response;
1.521     raeburn  9331:     }
                   9332: }
                   9333: 
1.792     raeburn  9334: sub auto_instcode_defaults {
                   9335:     my ($domain,$returnhash,$code_order) = @_;
                   9336:     my @homeservers;
1.841     albertel 9337: 
                   9338:     my %servers = &get_servers($domain,'library');
                   9339:     foreach my $tryserver (keys(%servers)) {
                   9340: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9341: 	    push(@homeservers,$tryserver);
                   9342: 	}
1.792     raeburn  9343:     }
1.841     albertel 9344: 
1.792     raeburn  9345:     my $response;
1.841     albertel 9346:     foreach my $server (@homeservers) {
1.792     raeburn  9347:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9348:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9349: 	
                   9350: 	foreach my $pair (split(/\&/,$response)) {
                   9351: 	    my ($name,$value)=split(/\=/,$pair);
                   9352: 	    if ($name eq 'code_order') {
                   9353: 		@{$code_order} = split(/\&/,&unescape($value));
                   9354: 	    } else {
                   9355: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9356: 	    }
                   9357: 	}
                   9358: 	return 'ok';
1.792     raeburn  9359:     }
1.841     albertel 9360: 
                   9361:     return $response;
1.1003    raeburn  9362: }
                   9363: 
                   9364: sub auto_possible_instcodes {
1.1007    raeburn  9365:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9366:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9367:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9368:         return;
                   9369:     }
1.1003    raeburn  9370:     my (@homeservers,$uhome);
                   9371:     if (defined(&domain($domain,'primary'))) {
                   9372:         $uhome=&domain($domain,'primary');
                   9373:         push(@homeservers,&domain($domain,'primary'));
                   9374:     } else {
                   9375:         my %servers = &get_servers($domain,'library');
                   9376:         foreach my $tryserver (keys(%servers)) {
                   9377:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9378:                 push(@homeservers,$tryserver);
                   9379:             }
                   9380:         }
                   9381:     }
                   9382:     my $response;
                   9383:     foreach my $server (@homeservers) {
                   9384:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9385:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9386:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9387:             split(':',$response);
                   9388:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9389:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9390:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9391:             my ($name,$value)=split('=',$item);
                   9392:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9393:         }
                   9394:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9395:             my ($name,$value)=split('=',$item);
                   9396:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9397:         }
                   9398:         return 'ok';
                   9399:     }
                   9400:     return $response;
                   9401: }
1.792     raeburn  9402: 
1.1010    raeburn  9403: sub auto_courserequest_checks {
                   9404:     my ($dom) = @_;
1.1020    raeburn  9405:     my ($homeserver,%validations);
                   9406:     if ($dom =~ /^$match_domain$/) {
                   9407:         $homeserver = &domain($dom,'primary');
                   9408:     }
                   9409:     unless ($homeserver eq 'no_host') {
                   9410:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9411:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9412:             my @items = split(/&/,$response);
                   9413:             foreach my $item (@items) {
                   9414:                 my ($key,$value) = split('=',$item);
                   9415:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9416:             }
                   9417:         }
                   9418:     }
1.1010    raeburn  9419:     return %validations; 
                   9420: }
                   9421: 
1.1020    raeburn  9422: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9423:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9424:     my ($homeserver,$response);
                   9425:     if ($dom =~ /^$match_domain$/) {
                   9426:         $homeserver = &domain($dom,'primary');
                   9427:     }
1.1172.2.43  raeburn  9428:     unless ($homeserver eq 'no_host') {
                   9429:         my $customdata;
                   9430:         if (ref($custominfo) eq 'HASH') {
                   9431:             $customdata = &freeze_escape($custominfo);
                   9432:         }
1.1020    raeburn  9433:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9434:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9435:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9436:                                     $customdata,$homeserver));
1.1020    raeburn  9437:     }
                   9438:     return $response;
                   9439: }
                   9440: 
1.777     albertel 9441: sub auto_validate_class_sec {
1.918     raeburn  9442:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9443:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9444:     my $ownerlist;
                   9445:     if (ref($owners) eq 'ARRAY') {
                   9446:         $ownerlist = join(',',@{$owners});
                   9447:     } else {
                   9448:         $ownerlist = $owners;
                   9449:     }
1.773     raeburn  9450:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9451:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9452:     return $response;
                   9453: }
                   9454: 
1.1172.2.141  raeburn  9455: sub auto_instsec_reformat {
                   9456:     my ($cdom,$action,$instsecref) = @_;
                   9457:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9458:     my @homeservers;
                   9459:     if (defined(&domain($cdom,'primary'))) {
                   9460:         push(@homeservers,&domain($cdom,'primary'));
                   9461:     } else {
                   9462:         my %servers = &get_servers($cdom,'library');
                   9463:         foreach my $tryserver (keys(%servers)) {
                   9464:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9465:                 push(@homeservers,$tryserver);
                   9466:             }
                   9467:         }
                   9468:     }
                   9469:     my $response;
                   9470:     my %reformatted = %{$instsecref};
                   9471:     foreach my $server (@homeservers) {
                   9472:         if (ref($instsecref) eq 'HASH') {
                   9473:             my $info = &freeze_escape($instsecref);
                   9474:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9475:                                 $action.':'.$info,$server);
                   9476:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9477:             my @items = split(/&/,$response);
                   9478:             foreach my $item (@items) {
                   9479:                 my ($key,$value) = split(/=/,$item);
                   9480:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9481:             }
                   9482:         }
                   9483:     }
                   9484:     return %reformatted;
                   9485: }
                   9486: 
1.1172.2.94  raeburn  9487: sub auto_validate_instclasses {
                   9488:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9489:     my ($homeserver,%validations);
                   9490:     $homeserver = &homeserver($cnum,$cdom);
                   9491:     unless ($homeserver eq 'no_host') {
                   9492:         my $ownerlist;
                   9493:         if (ref($owners) eq 'ARRAY') {
                   9494:             $ownerlist = join(',',@{$owners});
                   9495:         } else {
                   9496:             $ownerlist = $owners;
                   9497:         }
                   9498:         if (ref($classesref) eq 'HASH') {
                   9499:             my $classes = &freeze_escape($classesref);
                   9500:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9501:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9502:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9503:                 my @items = split(/&/,$response);
                   9504:                 foreach my $item (@items) {
                   9505:                     my ($key,$value) = split('=',$item);
                   9506:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9507:                 }
                   9508:             }
                   9509:         }
                   9510:     }
                   9511:     return %validations;
                   9512: }
                   9513: 
1.1172.2.38  raeburn  9514: sub auto_crsreq_update {
                   9515:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9516:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9517:     my ($homeserver,%crsreqresponse);
                   9518:     if ($cdom =~ /^$match_domain$/) {
                   9519:         $homeserver = &domain($cdom,'primary');
                   9520:     }
                   9521:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9522:         my $info;
                   9523:         if (ref($inbound) eq 'HASH') {
                   9524:             $info = &freeze_escape($inbound);
                   9525:         }
                   9526:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9527:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9528:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9529:                             &escape($title).':'.&escape($code).':'.
                   9530:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9531:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9532:             my @items = split(/&/,$response);
                   9533:             foreach my $item (@items) {
                   9534:                 my ($key,$value) = split('=',$item);
                   9535:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9536:             }
                   9537:         }
                   9538:     }
                   9539:     return \%crsreqresponse;
                   9540: }
                   9541: 
1.1172.2.78  raeburn  9542: sub auto_export_grades {
                   9543:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9544:     my ($homeserver,%exportresponse);
                   9545:     if ($cdom =~ /^$match_domain$/) {
                   9546:         $homeserver = &domain($cdom,'primary');
                   9547:     }
                   9548:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9549:         my $info;
                   9550:         if (ref($inforef) eq 'HASH') {
                   9551:             $info = &freeze_escape($inforef);
                   9552:         }
                   9553:         if (ref($gradesref) eq 'HASH') {
                   9554:             my $grades = &freeze_escape($gradesref);
                   9555:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9556:                                 $info.':'.$grades,$homeserver);
                   9557:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9558:                 my @items = split(/&/,$response);
                   9559:                 foreach my $item (@items) {
                   9560:                     my ($key,$value) = split('=',$item);
                   9561:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9562:                 }
                   9563:             }
                   9564:         }
                   9565:     }
                   9566:     return \%exportresponse;
                   9567: }
                   9568: 
1.1172.2.68  raeburn  9569: sub check_instcode_cloning {
                   9570:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9571:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9572:         return;
                   9573:     }
                   9574:     my $canclone;
                   9575:     if (@{$code_order} > 0) {
                   9576:         my $instcoderegexp ='^';
                   9577:         my @clonecodes = split(/\&/,$cloner);
                   9578:         foreach my $item (@{$code_order}) {
                   9579:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9580:                 foreach my $pair (@clonecodes) {
                   9581:                     my ($key,$val) = split(/\=/,$pair,2);
                   9582:                     $val = &unescape($val);
                   9583:                     if ($key eq $item) {
                   9584:                         $instcoderegexp .= '('.$val.')';
                   9585:                         last;
                   9586:                     }
                   9587:                 }
                   9588:             } else {
                   9589:                 $instcoderegexp .= $codedefaults->{$item};
                   9590:             }
                   9591:         }
                   9592:         $instcoderegexp .= '$';
                   9593:         my (@from,@to);
                   9594:         eval {
                   9595:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9596:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9597:         };
                   9598:         if ((@from > 0) && (@to > 0)) {
                   9599:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9600:             if (!@diffs) {
                   9601:                 $canclone = 1;
                   9602:             }
                   9603:         }
                   9604:     }
                   9605:     return $canclone;
                   9606: }
                   9607: 
                   9608: sub default_instcode_cloning {
                   9609:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9610:     my (%codedefaults,@code_order,$canclone);
                   9611:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9612:         %codedefaults = %{$codedefaultsref};
                   9613:         @code_order = @{$codeorderref};
                   9614:     } elsif ($clonedom) {
                   9615:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9616:     }
                   9617:     if (($domdefclone) && (@code_order)) {
                   9618:         my @clonecodes = split(/\+/,$domdefclone);
                   9619:         my $instcoderegexp ='^';
                   9620:         foreach my $item (@code_order) {
                   9621:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9622:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9623:             } else {
                   9624:                 $instcoderegexp .= $codedefaults{$item};
                   9625:             }
                   9626:         }
                   9627:         $instcoderegexp .= '$';
                   9628:         my (@from,@to);
                   9629:         eval {
                   9630:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9631:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9632:         };
                   9633:         if ((@from > 0) && (@to > 0)) {
                   9634:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9635:             if (!@diffs) {
                   9636:                 $canclone = 1;
                   9637:             }
                   9638:         }
                   9639:     }
                   9640:     return $canclone;
                   9641: }
                   9642: 
1.679     raeburn  9643: # ------------------------------------------------------- Course Group routines
                   9644: 
                   9645: sub get_coursegroups {
1.809     raeburn  9646:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9647:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9648: }
                   9649: 
1.679     raeburn  9650: sub modify_coursegroup {
                   9651:     my ($cdom,$cnum,$groupsettings) = @_;
                   9652:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9653: }
                   9654: 
1.809     raeburn  9655: sub toggle_coursegroup_status {
                   9656:     my ($cdom,$cnum,$group,$action) = @_;
                   9657:     my ($from_namespace,$to_namespace);
                   9658:     if ($action eq 'delete') {
                   9659:         $from_namespace = 'coursegroups';
                   9660:         $to_namespace = 'deleted_groups';
                   9661:     } else {
                   9662:         $from_namespace = 'deleted_groups';
                   9663:         $to_namespace = 'coursegroups';
                   9664:     }
                   9665:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9666:     if (my $tmp = &error(%curr_group)) {
                   9667:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9668:         return ('read error',$tmp);
                   9669:     } else {
                   9670:         my %savedsettings = %curr_group; 
1.809     raeburn  9671:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9672:         my $deloutcome;
                   9673:         if ($result eq 'ok') {
1.809     raeburn  9674:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9675:         } else {
                   9676:             return ('write error',$result);
                   9677:         }
                   9678:         if ($deloutcome eq 'ok') {
                   9679:             return 'ok';
                   9680:         } else {
                   9681:             return ('delete error',$deloutcome);
                   9682:         }
                   9683:     }
                   9684: }
                   9685: 
1.679     raeburn  9686: sub modify_group_roles {
1.957     raeburn  9687:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9688:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9689:     my $role = 'gr/'.&escape($userprivs);
                   9690:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9691:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9692:     if ($result eq 'ok') {
                   9693:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9694:     }
1.679     raeburn  9695:     return $result;
                   9696: }
                   9697: 
                   9698: sub modify_coursegroup_membership {
                   9699:     my ($cdom,$cnum,$membership) = @_;
                   9700:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9701:     return $result;
                   9702: }
                   9703: 
1.682     raeburn  9704: sub get_active_groups {
                   9705:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9706:     my $now = time;
                   9707:     my %groups = ();
                   9708:     foreach my $key (keys(%env)) {
1.811     albertel 9709:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9710:             my ($start,$end) = split(/\./,$env{$key});
                   9711:             if (($end!=0) && ($end<$now)) { next; }
                   9712:             if (($start!=0) && ($start>$now)) { next; }
                   9713:             if ($1 eq $cdom && $2 eq $cnum) {
                   9714:                 $groups{$3} = $env{$key} ;
                   9715:             }
                   9716:         }
                   9717:     }
                   9718:     return %groups;
                   9719: }
                   9720: 
1.683     raeburn  9721: sub get_group_membership {
                   9722:     my ($cdom,$cnum,$group) = @_;
                   9723:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9724: }
                   9725: 
                   9726: sub get_users_groups {
                   9727:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9728:     my @usersgroups;
1.683     raeburn  9729:     my $cachetime=1800;
                   9730: 
                   9731:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9732:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9733:     if (defined($cached)) {
1.734     albertel 9734:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9735:     } else {  
                   9736:         $grouplist = '';
1.816     raeburn  9737:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9738:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9739:         my $access_end = $env{'course.'.$courseid.
                   9740:                               '.default_enrollment_end_date'};
                   9741:         my $now = time;
                   9742:         foreach my $key (keys(%roleshash)) {
                   9743:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9744:                 my $group = $1;
                   9745:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9746:                     my $start = $2;
                   9747:                     my $end = $1;
                   9748:                     if ($start == -1) { next; } # deleted from group
                   9749:                     if (($start!=0) && ($start>$now)) { next; }
                   9750:                     if (($end!=0) && ($end<$now)) {
                   9751:                         if ($access_end && $access_end < $now) {
                   9752:                             if ($access_end - $end < 86400) {
                   9753:                                 push(@usersgroups,$group);
1.733     raeburn  9754:                             }
                   9755:                         }
1.817     raeburn  9756:                         next;
1.733     raeburn  9757:                     }
1.817     raeburn  9758:                     push(@usersgroups,$group);
1.683     raeburn  9759:                 }
                   9760:             }
                   9761:         }
1.817     raeburn  9762:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9763:         $grouplist = join(':',@usersgroups);
                   9764:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9765:     }
1.733     raeburn  9766:     return @usersgroups;
1.683     raeburn  9767: }
                   9768: 
                   9769: sub devalidate_getgroups_cache {
                   9770:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9771:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9772: 
1.683     raeburn  9773:     my $hashid="$udom:$uname:$courseid";
                   9774:     &devalidate_cache_new('getgroups',$hashid);
                   9775: }
                   9776: 
1.12      www      9777: # ------------------------------------------------------------------ Plain Text
                   9778: 
                   9779: sub plaintext {
1.988     raeburn  9780:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9781:     if ($short =~ m{^cr/}) {
1.758     albertel 9782: 	return (split('/',$short))[-1];
                   9783:     }
1.742     raeburn  9784:     if (!defined($cid)) {
                   9785:         $cid = $env{'request.course.id'};
                   9786:     }
                   9787:     my %rolenames = (
1.1008    raeburn  9788:                       Course    => 'std',
                   9789:                       Community => 'alt1',
1.742     raeburn  9790:                     );
1.1037    raeburn  9791:     if ($cid ne '') {
                   9792:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9793:             unless ($forcedefault) {
                   9794:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9795:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9796:                 return &Apache::lonlocal::mt($roletext);
                   9797:             }
                   9798:         }
                   9799:     }
                   9800:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9801:         (defined($rolenames{$type})) && 
                   9802:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9803:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9804:     } elsif ($cid ne '') {
                   9805:         my $crstype = $env{'course.'.$cid.'.type'};
                   9806:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9807:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9808:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9809:         }
1.742     raeburn  9810:     }
1.1037    raeburn  9811:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9812: }
                   9813: 
                   9814: # ----------------------------------------------------------------- Assign Role
                   9815: 
                   9816: sub assignrole {
1.957     raeburn  9817:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9818:         $context)=@_;
1.21      www      9819:     my $mrole;
                   9820:     if ($role =~ /^cr\//) {
1.393     www      9821:         my $cwosec=$url;
1.811     albertel 9822:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9823: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9824:            my $refused = 1;
                   9825:            if ($context eq 'requestcourses') {
                   9826:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9827:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9828:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9829:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9830:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9831:                            if ($crsenv{'internal.courseowner'} eq
                   9832:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9833:                                $refused = '';
                   9834:                            }
                   9835:                        }
                   9836:                    }
                   9837:                }
                   9838:            }
                   9839:            if ($refused) {
                   9840:                &logthis('Refused custom assignrole: '.
                   9841:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9842:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9843:                return 'refused';
                   9844:            }
1.104     www      9845:         }
1.21      www      9846:         $mrole='cr';
1.678     raeburn  9847:     } elsif ($role =~ /^gr\//) {
                   9848:         my $cwogrp=$url;
1.811     albertel 9849:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9850:         unless (&allowed('mdg',$cwogrp)) {
                   9851:             &logthis('Refused group assignrole: '.
                   9852:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9853:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9854:             return 'refused';
                   9855:         }
                   9856:         $mrole='gr';
1.21      www      9857:     } else {
1.82      www      9858:         my $cwosec=$url;
1.811     albertel 9859:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9860:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9861:             my $refused;
                   9862:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9863:                 if (!(&allowed('c'.$role,$url))) {
                   9864:                     $refused = 1;
                   9865:                 }
                   9866:             } else {
                   9867:                 $refused = 1;
                   9868:             }
1.947     raeburn  9869:             if ($refused) {
1.1045    raeburn  9870:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9871:                 if (!$selfenroll && $context eq 'course') {
                   9872:                     my %crsenv;
                   9873:                     if ($role eq 'cc' || $role eq 'co') {
                   9874:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9875:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9876:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9877:                                 if ($crsenv{'internal.courseowner'} eq 
                   9878:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9879:                                     $refused = '';
                   9880:                                 }
                   9881:                             }
                   9882:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9883:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9884:                                 if ($crsenv{'internal.courseowner'} eq 
                   9885:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9886:                                     $refused = '';
                   9887:                                 }
                   9888:                             }
                   9889:                         }
                   9890:                     }
                   9891:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9892:                     $refused = '';
1.1017    raeburn  9893:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9894:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9895:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9896:                         my $wrongcc;
                   9897:                         if ($cnum =~ /^$match_community$/) {
                   9898:                             $wrongcc = 1 if ($role eq 'cc');
                   9899:                         } else {
                   9900:                             $wrongcc = 1 if ($role eq 'co');
                   9901:                         }
                   9902:                         unless ($wrongcc) {
                   9903:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9904:                             if ($crsenv{'internal.courseowner'} eq 
                   9905:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9906:                                 $refused = '';
                   9907:                             }
1.1017    raeburn  9908:                         }
                   9909:                     }
1.1172.2.9  raeburn  9910:                 } elsif ($context eq 'requestauthor') {
                   9911:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9912:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9913:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9914:                             $refused = '';
                   9915:                         } else {
                   9916:                             my %domdefaults = &get_domain_defaults($udom);
                   9917:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9918:                                 my $checkbystatus;
                   9919:                                 if ($env{'user.adv'}) {
                   9920:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9921:                                     if ($disposition eq 'automatic') {
                   9922:                                         $refused = '';
                   9923:                                     } elsif ($disposition eq '') {
                   9924:                                         $checkbystatus = 1;
                   9925:                                     }
                   9926:                                 } else {
                   9927:                                     $checkbystatus = 1;
                   9928:                                 }
                   9929:                                 if ($checkbystatus) {
                   9930:                                     if ($env{'environment.inststatus'}) {
                   9931:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9932:                                         foreach my $type (@inststatuses) {
                   9933:                                             if (($type ne '') &&
                   9934:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9935:                                                 $refused = '';
                   9936:                                             }
                   9937:                                         }
                   9938:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9939:                                         $refused = '';
                   9940:                                     }
                   9941:                                 }
                   9942:                             }
                   9943:                         }
                   9944:                     }
1.1017    raeburn  9945:                 }
                   9946:                 if ($refused) {
1.947     raeburn  9947:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9948:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9949: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9950:                     return 'refused';
                   9951:                 }
1.932     raeburn  9952:             }
1.1131    raeburn  9953:         } elsif ($role eq 'au') {
                   9954:             if ($url ne '/'.$udom.'/') {
                   9955:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9956:                          ' to assign author role for '.$uname.':'.$udom.
                   9957:                          ' in domain: '.$url.' refused (wrong domain).');
                   9958:                 return 'refused';
                   9959:             }
1.104     www      9960:         }
1.21      www      9961:         $mrole=$role;
                   9962:     }
1.620     albertel 9963:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9964:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9965:     if ($end) { $command.='_'.$end; }
1.21      www      9966:     if ($start) {
                   9967: 	if ($end) { 
1.81      www      9968:            $command.='_'.$start; 
1.21      www      9969:         } else {
1.81      www      9970:            $command.='_0_'.$start;
1.21      www      9971:         }
                   9972:     }
1.739     raeburn  9973:     my $origstart = $start;
                   9974:     my $origend = $end;
1.957     raeburn  9975:     my $delflag;
1.357     www      9976: # actually delete
                   9977:     if ($deleteflag) {
1.373     www      9978: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9979: # modify command to delete the role
1.620     albertel 9980:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9981:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9982: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9983: # set start and finish to negative values for userrolelog
                   9984:            $start=-1;
                   9985:            $end=-1;
1.957     raeburn  9986:            $delflag = 1;
1.357     www      9987:         }
                   9988:     }
                   9989: # send command
1.349     www      9990:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9991: # log new user role if status is ok
1.349     www      9992:     if ($answer eq 'ok') {
1.663     raeburn  9993: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9994:         if (($role eq 'cc') || ($role eq 'in') ||
                   9995:             ($role eq 'ep') || ($role eq 'ad') ||
                   9996:             ($role eq 'ta') || ($role eq 'st') ||
                   9997:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9998:             ($role eq 'co')) {
1.1172.2.13  raeburn  9999: # for course roles, perform group memberships changes triggered by role change.
                   10000:             unless ($role =~ /^gr/) {
                   10001:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10002:                                                  $origstart,$selfenroll,$context);
                   10003:             }
1.1172.2.9  raeburn  10004:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10005:                            $selfenroll,$context);
                   10006:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10007:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10008:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10009:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10010:                            $context);
                   10011:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10012:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10013:                              $context);
                   10014:         }
1.1053    raeburn  10015:         if ($role eq 'cc') {
                   10016:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10017:         }
1.349     www      10018:     }
                   10019:     return $answer;
1.169     harris41 10020: }
                   10021: 
1.1053    raeburn  10022: sub autoupdate_coowners {
                   10023:     my ($url,$end,$start,$uname,$udom) = @_;
                   10024:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10025:     if (($cdom ne '') && ($cnum ne '')) {
                   10026:         my $now = time;
                   10027:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10028:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10029:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10030:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10031:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10032:             if ($instcode ne '') {
1.1056    raeburn  10033:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10034:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10035:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10036:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10037:                         unless ($result eq 'valid') {
                   10038:                             if ($xlists ne '') {
                   10039:                                 foreach my $xlist (split(',',$xlists)) {
                   10040:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10041:                                     $result =
                   10042:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10043:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10044:                                     last if ($result eq 'valid');
                   10045:                                 }
                   10046:                             }
                   10047:                         }
1.1056    raeburn  10048:                         if ($result eq 'valid') {
                   10049:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10050:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10051:                                     push(@newcoowners,$coowner);
                   10052:                                 }
                   10053:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10054:                                     push(@newcoowners,$uname.':'.$udom);
                   10055:                                 }
                   10056:                                 @newcoowners = sort(@newcoowners);
                   10057:                             } else {
                   10058:                                 push(@newcoowners,$uname.':'.$udom);
                   10059:                             }
1.1172.2.141  raeburn  10060:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10061:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10062:                                 unless ($coowner eq $uname.':'.$udom) {
                   10063:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10064:                                 }
                   10065:                             }
1.1172.2.141  raeburn  10066:                             unless (@newcoowners > 0) {
                   10067:                                 $delcoowners = 1;
                   10068:                                 $coowners = '';
                   10069:                             }
1.1053    raeburn  10070:                         }
                   10071:                         if (@newcoowners || $delcoowners) {
                   10072:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10073:                                             $delcoowners,@newcoowners);
                   10074:                         }
                   10075:                     }
                   10076:                 }
                   10077:             }
                   10078:         }
                   10079:     }
                   10080: }
                   10081: 
                   10082: sub store_coowners {
                   10083:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10084:     my $cid = $cdom.'_'.$cnum;
                   10085:     my ($coowners,$delresult,$putresult);
                   10086:     if (@newcoowners) {
                   10087:         $coowners = join(',',@newcoowners);
                   10088:         my %coownershash = (
                   10089:                             'internal.co-owners' => $coowners,
                   10090:                            );
                   10091:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10092:         if ($putresult eq 'ok') {
                   10093:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10094:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10095:             }
                   10096:         }
                   10097:     }
                   10098:     if ($delcoowners) {
                   10099:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10100:         if ($delresult eq 'ok') {
                   10101:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10102:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10103:             }
                   10104:         }
                   10105:     }
                   10106:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10107:         my %crsinfo =
                   10108:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10109:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10110:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10111:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10112:         }
                   10113:     }
                   10114: }
                   10115: 
1.169     harris41 10116: # -------------------------------------------------- Modify user authentication
1.197     www      10117: # Overrides without validation
                   10118: 
1.169     harris41 10119: sub modifyuserauth {
                   10120:     my ($udom,$uname,$umode,$upass)=@_;
                   10121:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10122:     my $allowed;
                   10123:     if (&allowed('mau',$udom)) {
                   10124:         $allowed = 1;
                   10125:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10126:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10127:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10128:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10129:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10130:         if (($cdom ne '') && ($cnum ne '')) {
                   10131:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10132:             if ($is_owner) {
                   10133:                 $allowed = 1;
                   10134:             }
                   10135:         }
                   10136:     }
                   10137:     unless ($allowed) { return 'refused'; }
1.197     www      10138:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10139:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10140:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10141:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10142: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10143:     my $ip = &get_requestor_ip();
1.620     albertel 10144:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10145:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10146:          '(Remote '.$ip.'): '.$reply);
1.197     www      10147:     &log($udom,,$uname,$uhome,
1.620     albertel 10148:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10149:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10150:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10151:     unless ($reply eq 'ok') {
1.197     www      10152:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10153: 	return 'error: '.$reply;
                   10154:     }   
1.170     harris41 10155:     return 'ok';
1.80      www      10156: }
                   10157: 
1.81      www      10158: # --------------------------------------------------------------- Modify a user
1.80      www      10159: 
1.81      www      10160: sub modifyuser {
1.206     matthew  10161:     my ($udom,    $uname, $uid,
                   10162:         $umode,   $upass, $first,
                   10163:         $middle,  $last,  $gene,
1.1058    raeburn  10164:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10165:     $udom= &LONCAPA::clean_domain($udom);
                   10166:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10167:     my $showcandelete = 'none';
                   10168:     if (ref($candelete) eq 'ARRAY') {
                   10169:         if (@{$candelete} > 0) {
                   10170:             $showcandelete = join(', ',@{$candelete});
                   10171:         }
                   10172:     }
1.81      www      10173:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10174:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10175: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10176:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10177:                                      ' desiredhome not specified'). 
1.620     albertel 10178:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10179:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10180:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10181:     my $newuser;
                   10182:     if ($uhome eq 'no_host') {
                   10183:         $newuser = 1;
                   10184:     }
1.80      www      10185: # ----------------------------------------------------------------- Create User
1.406     albertel 10186:     if (($uhome eq 'no_host') && 
                   10187: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10188:         my $unhome='';
1.844     albertel 10189:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10190:             $unhome = $desiredhome;
1.620     albertel 10191: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10192: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10193:         } else { # load balancing routine for determining $unhome
1.81      www      10194:             my $loadm=10000000;
1.841     albertel 10195: 	    my %servers = &get_servers($udom,'library');
                   10196: 	    foreach my $tryserver (keys(%servers)) {
                   10197: 		my $answer=reply('load',$tryserver);
                   10198: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10199: 		    $loadm=$answer;
                   10200: 		    $unhome=$tryserver;
                   10201: 		}
1.80      www      10202: 	    }
                   10203:         }
                   10204:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10205: 	    return 'error: unable to find a home server for '.$uname.
                   10206:                    ' in domain '.$udom;
1.80      www      10207:         }
                   10208:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10209:                          &escape($upass),$unhome);
                   10210: 	unless ($reply eq 'ok') {
                   10211:             return 'error: '.$reply;
                   10212:         }   
1.230     stredwic 10213:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10214:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10215: 	    return 'error: unable verify users home machine.';
1.80      www      10216:         }
1.209     matthew  10217:     }   # End of creation of new user
1.80      www      10218: # ---------------------------------------------------------------------- Add ID
                   10219:     if ($uid) {
                   10220:        $uid=~tr/A-Z/a-z/;
                   10221:        my %uidhash=&idrget($udom,$uname);
1.196     www      10222:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10223:          && (!$forceid)) {
1.80      www      10224: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10225: 	      return 'error: user id "'.$uid.'" does not match '.
                   10226:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10227:           }
                   10228:        } else {
                   10229: 	  &idput($udom,($uname => $uid));
                   10230:        }
                   10231:     }
                   10232: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10233:     my @tmp=&get('environment',
1.899     raeburn  10234: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10235:                     'permanentemail','inststatus'],
1.134     albertel 10236: 		   $udom,$uname);
1.1075    raeburn  10237:     my (%names,%oldnames);
1.313     matthew  10238:     if ($tmp[0] =~ m/^error:.*/) { 
                   10239:         %names=(); 
                   10240:     } else {
                   10241:         %names = @tmp;
1.1075    raeburn  10242:         %oldnames = %names;
1.313     matthew  10243:     }
1.388     www      10244: #
1.1058    raeburn  10245: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10246: # of users did not contain them), do not overwrite existing values
                   10247: # unless field is in $candelete array ref.  
                   10248: #
                   10249: 
                   10250:     my @fields = ('firstname','middlename','lastname','generation',
                   10251:                   'permanentemail','id');
                   10252:     my %newvalues;
                   10253:     if (ref($candelete) eq 'ARRAY') {
                   10254:         foreach my $field (@fields) {
                   10255:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10256:                 if ($field eq 'firstname') {
                   10257:                     $names{$field} = $first;
                   10258:                 } elsif ($field eq 'middlename') {
                   10259:                     $names{$field} = $middle;
                   10260:                 } elsif ($field eq 'lastname') {
                   10261:                     $names{$field} = $last;
                   10262:                 } elsif ($field eq 'generation') { 
                   10263:                     $names{$field} = $gene;
                   10264:                 } elsif ($field eq 'permanentemail') {
                   10265:                     $names{$field} = $email;
                   10266:                 } elsif ($field eq 'id') {
                   10267:                     $names{$field}  = $uid;
                   10268:                 }
                   10269:             }
                   10270:         }
                   10271:     }
1.388     www      10272:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10273:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10274:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10275:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10276:     if ($email) {
                   10277:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10278:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10279:     }
1.899     raeburn  10280:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10281:     if (defined($inststatus)) {
                   10282:         $names{'inststatus'} = '';
                   10283:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10284:         if (ref($usertypes) eq 'HASH') {
                   10285:             my @okstatuses; 
                   10286:             foreach my $item (split(/:/,$inststatus)) {
                   10287:                 if (defined($usertypes->{$item})) {
                   10288:                     push(@okstatuses,$item);  
                   10289:                 }
                   10290:             }
                   10291:             if (@okstatuses) {
                   10292:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10293:             }
                   10294:         }
                   10295:     }
1.1075    raeburn  10296:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10297:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10298:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10299:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10300:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10301:     } else {
                   10302:         $logmsg .= ' during self creation';
                   10303:     }
1.1075    raeburn  10304:     my $changed;
                   10305:     if ($newuser) {
                   10306:         $changed = 1;
                   10307:     } else {
                   10308:         foreach my $field (@fields) {
                   10309:             if ($names{$field} ne $oldnames{$field}) {
                   10310:                 $changed = 1;
                   10311:                 last;
                   10312:             }
                   10313:         }
                   10314:     }
                   10315:     unless ($changed) {
                   10316:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10317:         &logthis($logmsg);
                   10318:         return 'ok';
                   10319:     }
                   10320:     my $reply = &put('environment', \%names, $udom,$uname);
                   10321:     if ($reply ne 'ok') { 
                   10322:         return 'error: '.$reply;
                   10323:     }
1.1087    raeburn  10324:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10325:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10326:     }
1.1075    raeburn  10327:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10328:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10329:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10330:     &logthis($logmsg);
1.134     albertel 10331:     return 'ok';
1.80      www      10332: }
                   10333: 
1.81      www      10334: # -------------------------------------------------------------- Modify student
1.80      www      10335: 
1.81      www      10336: sub modifystudent {
                   10337:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10338:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10339:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10340:     if (!$cid) {
1.620     albertel 10341: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10342: 	    return 'not_in_class';
                   10343: 	}
1.80      www      10344:     }
                   10345: # --------------------------------------------------------------- Make the user
1.81      www      10346:     my $reply=&modifyuser
1.209     matthew  10347: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10348:          $desiredhome,$email,$inststatus);
1.80      www      10349:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10350:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10351:     # student's environment
1.297     matthew  10352:     $uid = undef if (!$forceid);
1.455     albertel 10353:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10354: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10355:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10356:     return $reply;
                   10357: }
                   10358: 
                   10359: sub modify_student_enrollment {
1.1172.2.23  raeburn  10360:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10361:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10362:     my ($cdom,$cnum,$chome);
                   10363:     if (!$cid) {
1.620     albertel 10364: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10365: 	    return 'not_in_class';
                   10366: 	}
1.620     albertel 10367: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10368: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10369:     } else {
                   10370: 	($cdom,$cnum)=split(/_/,$cid);
                   10371:     }
1.620     albertel 10372:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10373:     if (!$chome) {
1.457     raeburn  10374: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10375:     }
1.455     albertel 10376:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10377:     # Make sure the user exists
1.81      www      10378:     my $uhome=&homeserver($uname,$udom);
                   10379:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10380: 	return 'error: no such user';
                   10381:     }
1.297     matthew  10382:     # Get student data if we were not given enough information
                   10383:     if (!defined($first)  || $first  eq '' || 
                   10384:         !defined($last)   || $last   eq '' || 
                   10385:         !defined($uid)    || $uid    eq '' || 
                   10386:         !defined($middle) || $middle eq '' || 
                   10387:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10388:         # They did not supply us with enough data to enroll the student, so
                   10389:         # we need to pick up more information.
1.297     matthew  10390:         my %tmp = &get('environment',
1.294     matthew  10391:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10392:                        ,$udom,$uname);
                   10393: 
1.800     albertel 10394:         #foreach my $key (keys(%tmp)) {
                   10395:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10396:         #}
1.294     matthew  10397:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10398:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10399:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10400:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10401:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10402:     }
1.556     albertel 10403:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10404:     my $user = "$uname:$udom";
                   10405:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10406:     my $reply=cput('classlist',
1.1148    raeburn  10407: 		   {$user => 
1.1172.2.76  raeburn  10408: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10409: 		   $cdom,$cnum);
1.1148    raeburn  10410:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10411:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10412:     } else { 
1.81      www      10413: 	return 'error: '.$reply;
                   10414:     }
1.297     matthew  10415:     # Add student role to user
1.83      www      10416:     my $uurl='/'.$cid;
1.81      www      10417:     $uurl=~s/\_/\//g;
                   10418:     if ($usec) {
                   10419: 	$uurl.='/'.$usec;
                   10420:     }
1.1148    raeburn  10421:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10422:                              $selfenroll,$context);
                   10423:     if ($result ne 'ok') {
                   10424:         if ($old_entry{$user} ne '') {
                   10425:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10426:         } else {
                   10427:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10428:         }
                   10429:     }
                   10430:     return $result; 
1.21      www      10431: }
                   10432: 
1.556     albertel 10433: sub format_name {
                   10434:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10435:     my $name;
                   10436:     if ($first ne 'lastname') {
                   10437: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10438:     } else {
                   10439: 	if ($lastname=~/\S/) {
                   10440: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10441: 	    $name=~s/\s+,/,/;
                   10442: 	} else {
                   10443: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10444: 	}
                   10445:     }
                   10446:     $name=~s/^\s+//;
                   10447:     $name=~s/\s+$//;
                   10448:     $name=~s/\s+/ /g;
                   10449:     return $name;
                   10450: }
                   10451: 
1.84      www      10452: # ------------------------------------------------- Write to course preferences
                   10453: 
                   10454: sub writecoursepref {
                   10455:     my ($courseid,%prefs)=@_;
                   10456:     $courseid=~s/^\///;
                   10457:     $courseid=~s/\_/\//g;
                   10458:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10459:     my $chome=homeserver($cnum,$cdomain);
                   10460:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10461: 	return 'error: no such course';
                   10462:     }
                   10463:     my $cstring='';
1.800     albertel 10464:     foreach my $pref (keys(%prefs)) {
                   10465: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10466:     }
1.84      www      10467:     $cstring=~s/\&$//;
                   10468:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10469: }
                   10470: 
                   10471: # ---------------------------------------------------------- Make/modify course
                   10472: 
                   10473: sub createcourse {
1.741     raeburn  10474:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10475:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10476:     $url=&declutter($url);
                   10477:     my $cid='';
1.1028    raeburn  10478:     if ($context eq 'requestcourses') {
                   10479:         my $can_create = 0;
                   10480:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10481:         if ($udom eq $ownerdom) {
                   10482:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10483:                                   $context)) {
                   10484:                 $can_create = 1;
                   10485:             }
                   10486:         } else {
                   10487:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10488:                                            $category);
                   10489:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10490:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10491:                 if (@curr > 0) {
                   10492:                     my @options = qw(approval validate autolimit);
                   10493:                     my $optregex = join('|',@options);
                   10494:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10495:                         $can_create = 1;
                   10496:                     }
                   10497:                 }
                   10498:             }
                   10499:         }
                   10500:         if ($can_create) {
                   10501:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10502:                 unless (&allowed('ccc',$udom)) {
                   10503:                     return 'refused'; 
                   10504:                 }
1.1017    raeburn  10505:             }
                   10506:         } else {
                   10507:             return 'refused';
                   10508:         }
1.1028    raeburn  10509:     } elsif (!&allowed('ccc',$udom)) {
                   10510:         return 'refused';
1.84      www      10511:     }
1.1011    raeburn  10512: # --------------------------------------------------------------- Get Unique ID
                   10513:     my $uname;
                   10514:     if ($cnum =~ /^$match_courseid$/) {
                   10515:         my $chome=&homeserver($cnum,$udom,'true');
                   10516:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10517:             $uname = $cnum;
                   10518:         } else {
1.1038    raeburn  10519:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10520:         }
                   10521:     } else {
1.1038    raeburn  10522:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10523:     }
                   10524:     return $uname if ($uname =~ /^error/);
                   10525: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10526:     if (!defined($course_server)) {
                   10527:         if (defined(&domain($udom,'primary'))) {
                   10528:             $course_server = &domain($udom,'primary');
                   10529:         } else {
                   10530:             $course_server = $env{'user.home'}; 
                   10531:         }
                   10532:     }
                   10533:     my %host_servers =
                   10534:         &Apache::lonnet::get_servers($udom,'library');
                   10535:     unless ($host_servers{$course_server}) {
                   10536:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10537:     }
1.84      www      10538: # ------------------------------------------------------------- Make the course
                   10539:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10540:                       $course_server);
1.84      www      10541:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10542:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10543:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10544: 	return 'error: no such course';
                   10545:     }
1.271     www      10546: # ----------------------------------------------------------------- Course made
1.516     raeburn  10547: # log existence
1.1029    raeburn  10548:     my $now = time;
1.918     raeburn  10549:     my $newcourse = {
                   10550:                     $udom.'_'.$uname => {
1.921     raeburn  10551:                                      description => $description,
                   10552:                                      inst_code   => $inst_code,
                   10553:                                      owner       => $course_owner,
                   10554:                                      type        => $crstype,
1.1029    raeburn  10555:                                      creator     => $env{'user.name'}.':'.
                   10556:                                                     $env{'user.domain'},
                   10557:                                      created     => $now,
                   10558:                                      context     => $context,
1.918     raeburn  10559:                                                 },
                   10560:                     };
1.921     raeburn  10561:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10562: # set toplevel url
1.271     www      10563:     my $topurl=$url;
                   10564:     unless ($nonstandard) {
                   10565: # ------------------------------------------ For standard courses, make top url
                   10566:         my $mapurl=&clutter($url);
1.278     www      10567:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10568:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10569: <map>
                   10570: <resource id="1" type="start"></resource>
                   10571: <resource id="2" src="$mapurl"></resource>
                   10572: <resource id="3" type="finish"></resource>
                   10573: <link index="1" from="1" to="2"></link>
                   10574: <link index="2" from="2" to="3"></link>
                   10575: </map>
                   10576: ENDINITMAP
                   10577:         $topurl=&declutter(
1.638     albertel 10578:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10579:                           );
                   10580:     }
                   10581: # ----------------------------------------------------------- Write preferences
1.84      www      10582:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10583:                      ('description'              => $description,
                   10584:                       'url'                      => $topurl,
                   10585:                       'internal.creator'         => $env{'user.name'}.':'.
                   10586:                                                     $env{'user.domain'},
                   10587:                       'internal.created'         => $now,
                   10588:                       'internal.creationcontext' => $context)
                   10589:                     );
1.84      www      10590:     return '/'.$udom.'/'.$uname;
                   10591: }
                   10592: 
1.1011    raeburn  10593: # ------------------------------------------------------------------- Create ID
                   10594: sub generate_coursenum {
1.1038    raeburn  10595:     my ($udom,$crstype) = @_;
1.1011    raeburn  10596:     my $domdesc = &domain($udom);
                   10597:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10598:     my $first;
                   10599:     if ($crstype eq 'Community') {
                   10600:         $first = '0';
                   10601:     } else {
                   10602:         $first = int(1+rand(9)); 
                   10603:     } 
                   10604:     my $uname=$first.
1.1011    raeburn  10605:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10606:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10607:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10608: # ----------------------------------------------- Make sure that does not exist
                   10609:     my $uhome=&homeserver($uname,$udom,'true');
                   10610:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10611:         if ($crstype eq 'Community') {
                   10612:             $first = '0';
                   10613:         } else {
                   10614:             $first = int(1+rand(9));
                   10615:         }
                   10616:         $uname=$first.
1.1011    raeburn  10617:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10618:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10619:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10620:         $uhome=&homeserver($uname,$udom,'true');
                   10621:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10622:             return 'error: unable to generate unique course-ID';
                   10623:         }
                   10624:     }
                   10625:     return $uname;
                   10626: }
                   10627: 
1.813     albertel 10628: sub is_course {
1.1167    droeschl 10629:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10630:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10631:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10632:     my $uhome=&homeserver($cnum,$cdom);
                   10633:     my $iscourse;
                   10634:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10635:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10636:     } else {
                   10637:         my $hashid = $cdom.':'.$cnum;
                   10638:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10639:         unless (defined($cached)) {
                   10640:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10641:                                         $cnum,undef,undef,'.');
                   10642:             $iscourse = 0;
                   10643:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10644:                 $iscourse = 1;
                   10645:             }
                   10646:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10647:         }
                   10648:     }
                   10649:     return unless($iscourse);
1.1167    droeschl 10650:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10651: }
                   10652: 
1.1015    raeburn  10653: sub store_userdata {
                   10654:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10655:     my $result;
1.1016    raeburn  10656:     if ($datakey ne '') {
1.1013    raeburn  10657:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10658:             if ($udom eq '' || $uname eq '') {
                   10659:                 $udom = $env{'user.domain'};
                   10660:                 $uname = $env{'user.name'};
                   10661:             }
                   10662:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10663:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10664:                 $result = 'error: no_host';
                   10665:             } else {
1.1172.2.138  raeburn  10666:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10667:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10668: 
                   10669:                 my $namevalue='';
                   10670:                 foreach my $key (keys(%{$storehash})) {
                   10671:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10672:                 }
                   10673:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10674:                 unless ($namespace eq 'courserequests') {
                   10675:                     $datakey = &escape($datakey);
                   10676:                 }
1.1105    raeburn  10677:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10678:                                   $namevalue,$uhome);
1.1013    raeburn  10679:             }
                   10680:         } else {
                   10681:             $result = 'error: data to store was not a hash reference'; 
                   10682:         }
                   10683:     } else {
                   10684:         $result= 'error: invalid requestkey'; 
                   10685:     }
                   10686:     return $result;
                   10687: }
                   10688: 
1.21      www      10689: # ---------------------------------------------------------- Assign Custom Role
                   10690: 
                   10691: sub assigncustomrole {
1.957     raeburn  10692:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10693:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10694:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10695: }
                   10696: 
                   10697: # ----------------------------------------------------------------- Revoke Role
                   10698: 
                   10699: sub revokerole {
1.957     raeburn  10700:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10701:     my $now=time;
1.965     raeburn  10702:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10703: }
                   10704: 
                   10705: # ---------------------------------------------------------- Revoke Custom Role
                   10706: 
                   10707: sub revokecustomrole {
1.957     raeburn  10708:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10709:     my $now=time;
1.357     www      10710:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10711:            $deleteflag,$selfenroll,$context);
1.17      www      10712: }
                   10713: 
1.533     banghart 10714: # ------------------------------------------------------------ Disk usage
1.535     albertel 10715: sub diskusage {
1.955     raeburn  10716:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10717:     $directorypath =~ s/\/$//;
                   10718:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10719:                        .&escape($getpropath).':'.&escape($uname).':'
                   10720:                        .&escape($udom),homeserver($uname,$udom));
                   10721:     if ($listing eq 'unknown_cmd') {
                   10722:         if ($getpropath) {
                   10723:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10724:         }
                   10725:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10726:     }
1.514     albertel 10727:     return $listing;
1.512     banghart 10728: }
                   10729: 
1.566     banghart 10730: sub is_locked {
1.1096    raeburn  10731:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10732:     my @check;
                   10733:     my $is_locked;
1.1093    raeburn  10734:     push (@check,$file_name);
1.613     albertel 10735:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10736: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10737:     my ($tmp)=keys(%locked);
                   10738:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10739:     
1.566     banghart 10740:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10741:         $is_locked = 'false';
                   10742:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10743:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10744:                $is_locked = 'true';
1.1096    raeburn  10745:                if (ref($which) eq 'ARRAY') {
                   10746:                    push(@{$which},$entry);
                   10747:                } else {
                   10748:                    last;
                   10749:                }
1.745     raeburn  10750:            }
                   10751:        }
1.566     banghart 10752:     } else {
                   10753:         $is_locked = 'false';
                   10754:     }
1.1093    raeburn  10755:     return $is_locked;
1.566     banghart 10756: }
                   10757: 
1.759     albertel 10758: sub declutter_portfile {
                   10759:     my ($file) = @_;
1.833     albertel 10760:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10761:     return $file;
                   10762: }
                   10763: 
1.559     banghart 10764: # ------------------------------------------------------------- Mark as Read Only
                   10765: 
                   10766: sub mark_as_readonly {
                   10767:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10768:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10769:     my ($tmp)=keys(%current_permissions);
                   10770:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10771:     foreach my $file (@{$files}) {
1.759     albertel 10772: 	$file = &declutter_portfile($file);
1.561     banghart 10773:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10774:     }
1.613     albertel 10775:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10776:     return;
                   10777: }
                   10778: 
1.572     banghart 10779: # ------------------------------------------------------------Save Selected Files
                   10780: 
                   10781: sub save_selected_files {
                   10782:     my ($user, $path, @files) = @_;
                   10783:     my $filename = $user."savedfiles";
1.573     banghart 10784:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10785:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10786:     foreach my $file (@files) {
1.620     albertel 10787:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10788:     }
                   10789:     foreach my $file (@other_files) {
1.574     banghart 10790:         print (OUT $file."\n");
1.572     banghart 10791:     }
1.574     banghart 10792:     close (OUT);
1.572     banghart 10793:     return 'ok';
                   10794: }
                   10795: 
1.574     banghart 10796: sub clear_selected_files {
                   10797:     my ($user) = @_;
                   10798:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10799:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10800:     print (OUT undef);
                   10801:     close (OUT);
                   10802:     return ("ok");    
                   10803: }
                   10804: 
1.572     banghart 10805: sub files_in_path {
                   10806:     my ($user, $path) = @_;
                   10807:     my $filename = $user."savedfiles";
                   10808:     my %return_files;
1.1172.2.96  raeburn  10809:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10810:     while (my $line_in = <IN>) {
1.574     banghart 10811:         chomp ($line_in);
                   10812:         my @paths_and_file = split (m!/!, $line_in);
                   10813:         my $file_part = pop (@paths_and_file);
                   10814:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10815:         $path_part.='/';
                   10816:         my $path_and_file = $path_part.$file_part;
                   10817:         if ($path_part eq $path) {
                   10818:             $return_files{$file_part}= 'selected';
                   10819:         }
                   10820:     }
1.574     banghart 10821:     close (IN);
                   10822:     return (\%return_files);
1.572     banghart 10823: }
                   10824: 
                   10825: # called in portfolio select mode, to show files selected NOT in current directory
                   10826: sub files_not_in_path {
                   10827:     my ($user, $path) = @_;
                   10828:     my $filename = $user."savedfiles";
                   10829:     my @return_files;
                   10830:     my $path_part;
1.1172.2.96  raeburn  10831:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10832:     while (my $line = <IN>) {
1.572     banghart 10833:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10834:         my @paths_and_file = split(m|/|, $line);
                   10835:         my $file_part = pop(@paths_and_file);
                   10836:         chomp($file_part);
                   10837:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10838:         $path_part .= '/';
                   10839:         my $path_and_file = $path_part.$file_part;
                   10840:         if ($path_part ne $path) {
1.800     albertel 10841:             push(@return_files, ($path_and_file));
1.572     banghart 10842:         }
                   10843:     }
1.800     albertel 10844:     close(OUT);
1.574     banghart 10845:     return (@return_files);
1.572     banghart 10846: }
                   10847: 
1.745     raeburn  10848: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10849: 
1.745     raeburn  10850: sub get_portfile_permissions {
                   10851:     my ($domain,$user) = @_;
1.613     albertel 10852:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10853:     my ($tmp)=keys(%current_permissions);
                   10854:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10855:     return \%current_permissions;
                   10856: }
                   10857: 
                   10858: #---------------------------------------------Get portfolio file access controls
                   10859: 
1.749     raeburn  10860: sub get_access_controls {
1.745     raeburn  10861:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10862:     my %access;
                   10863:     my $real_file = $file;
                   10864:     $file =~ s/\.meta$//;
1.745     raeburn  10865:     if (defined($file)) {
1.749     raeburn  10866:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10867:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10868:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10869:             }
                   10870:         }
1.745     raeburn  10871:     } else {
1.749     raeburn  10872:         foreach my $key (keys(%{$current_permissions})) {
                   10873:             if ($key =~ /\0accesscontrol$/) {
                   10874:                 if (defined($group)) {
                   10875:                     if ($key !~ m-^\Q$group\E/-) {
                   10876:                         next;
                   10877:                     }
                   10878:                 }
                   10879:                 my ($fullpath) = split(/\0/,$key);
                   10880:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10881:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10882:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10883:                     }
                   10884:                 }
                   10885:             }
                   10886:         }
                   10887:     }
                   10888:     return %access;
                   10889: }
                   10890: 
                   10891: sub modify_access_controls {
                   10892:     my ($file_name,$changes,$domain,$user)=@_;
                   10893:     my ($outcome,$deloutcome);
                   10894:     my %store_permissions;
                   10895:     my %new_values;
                   10896:     my %new_control;
                   10897:     my %translation;
                   10898:     my @deletions = ();
                   10899:     my $now = time;
                   10900:     if (exists($$changes{'activate'})) {
                   10901:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10902:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10903:             my $numnew = scalar(@newitems);
                   10904:             for (my $i=0; $i<$numnew; $i++) {
                   10905:                 my $newkey = $newitems[$i];
                   10906:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10907:                 if ($newkey =~ /^\d+:/) { 
                   10908:                     $newkey =~ s/^(\d+)/$newid/;
                   10909:                     $translation{$1} = $newid;
                   10910:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10911:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10912:                     $translation{$1} = $newid;
                   10913:                 }
1.749     raeburn  10914:                 $new_values{$file_name."\0".$newkey} = 
                   10915:                                           $$changes{'activate'}{$newitems[$i]};
                   10916:                 $new_control{$newkey} = $now;
                   10917:             }
                   10918:         }
                   10919:     }
                   10920:     my %todelete;
                   10921:     my %changed_items;
                   10922:     foreach my $action ('delete','update') {
                   10923:         if (exists($$changes{$action})) {
                   10924:             if (ref($$changes{$action}) eq 'HASH') {
                   10925:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10926:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10927:                     if ($action eq 'delete') { 
                   10928:                         $todelete{$itemnum} = 1;
                   10929:                     } else {
                   10930:                         $changed_items{$itemnum} = $key;
                   10931:                     }
                   10932:                 }
1.745     raeburn  10933:             }
                   10934:         }
1.749     raeburn  10935:     }
                   10936:     # get lock on access controls for file.
                   10937:     my $lockhash = {
                   10938:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10939:                                                        ':'.$env{'user.domain'},
                   10940:                    }; 
                   10941:     my $tries = 0;
                   10942:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10943:    
1.1172.2.79  raeburn  10944:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10945:         $tries ++;
1.1172.2.79  raeburn  10946:         sleep(0.1);
1.749     raeburn  10947:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10948:     }
                   10949:     if ($gotlock eq 'ok') {
                   10950:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10951:         my ($tmp)=keys(%curr_permissions);
                   10952:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10953:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10954:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10955:             if (ref($curr_controls) eq 'HASH') {
                   10956:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10957:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10958:                     if (defined($todelete{$itemnum})) {
                   10959:                         push(@deletions,$file_name."\0".$control_item);
                   10960:                     } else {
                   10961:                         if (defined($changed_items{$itemnum})) {
                   10962:                             $new_control{$changed_items{$itemnum}} = $now;
                   10963:                             push(@deletions,$file_name."\0".$control_item);
                   10964:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10965:                         } else {
                   10966:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10967:                         }
                   10968:                     }
1.745     raeburn  10969:                 }
                   10970:             }
                   10971:         }
1.970     raeburn  10972:         my ($group);
                   10973:         if (&is_course($domain,$user)) {
                   10974:             ($group,my $file) = split(/\//,$file_name,2);
                   10975:         }
1.749     raeburn  10976:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10977:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10978:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10979:         #  remove lock
                   10980:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10981:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10982:         my $sqlresult =
1.970     raeburn  10983:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10984:                                     $group);
1.749     raeburn  10985:     } else {
                   10986:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10987:     }
1.749     raeburn  10988:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10989: }
                   10990: 
1.827     raeburn  10991: sub make_public_indefinitely {
                   10992:     my ($requrl) = @_;
                   10993:     my $now = time;
                   10994:     my $action = 'activate';
                   10995:     my $aclnum = 0;
                   10996:     if (&is_portfolio_url($requrl)) {
                   10997:         my (undef,$udom,$unum,$file_name,$group) =
                   10998:             &parse_portfolio_url($requrl);
                   10999:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11000:         my %access_controls = &get_access_controls($current_perms,
                   11001:                                                    $group,$file_name);
                   11002:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11003:             my ($num,$scope,$end,$start) = 
                   11004:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11005:             if ($scope eq 'public') {
                   11006:                 if ($start <= $now && $end == 0) {
                   11007:                     $action = 'none';
                   11008:                 } else {
                   11009:                     $action = 'update';
                   11010:                     $aclnum = $num;
                   11011:                 }
                   11012:                 last;
                   11013:             }
                   11014:         }
                   11015:         if ($action eq 'none') {
                   11016:              return 'ok';
                   11017:         } else {
                   11018:             my %changes;
                   11019:             my $newend = 0;
                   11020:             my $newstart = $now;
                   11021:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11022:             $changes{$action}{$newkey} = {
                   11023:                 type => 'public',
                   11024:                 time => {
                   11025:                     start => $newstart,
                   11026:                     end   => $newend,
                   11027:                 },
                   11028:             };
                   11029:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11030:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11031:             return $outcome;
                   11032:         }
                   11033:     } else {
                   11034:         return 'invalid';
                   11035:     }
                   11036: }
                   11037: 
1.745     raeburn  11038: #------------------------------------------------------Get Marked as Read Only
                   11039: 
                   11040: sub get_marked_as_readonly {
                   11041:     my ($domain,$user,$what,$group) = @_;
                   11042:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11043:     my @readonly_files;
1.629     banghart 11044:     my $cmp1=$what;
                   11045:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11046:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11047:         if (defined($group)) {
                   11048:             if ($file_name !~ m-^\Q$group\E/-) {
                   11049:                 next;
                   11050:             }
                   11051:         }
1.561     banghart 11052:         if (ref($value) eq "ARRAY"){
                   11053:             foreach my $stored_what (@{$value}) {
1.629     banghart 11054:                 my $cmp2=$stored_what;
1.759     albertel 11055:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11056:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11057:                 }
1.629     banghart 11058:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11059:                     push(@readonly_files, $file_name);
1.745     raeburn  11060:                     last;
1.563     banghart 11061:                 } elsif (!defined($what)) {
                   11062:                     push(@readonly_files, $file_name);
1.745     raeburn  11063:                     last;
1.561     banghart 11064:                 }
                   11065:             }
1.745     raeburn  11066:         }
1.561     banghart 11067:     }
                   11068:     return @readonly_files;
                   11069: }
1.577     banghart 11070: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11071: 
1.577     banghart 11072: sub get_marked_as_readonly_hash {
1.745     raeburn  11073:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11074:     my %readonly_files;
1.745     raeburn  11075:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11076:         if (defined($group)) {
                   11077:             if ($file_name !~ m-^\Q$group\E/-) {
                   11078:                 next;
                   11079:             }
                   11080:         }
1.577     banghart 11081:         if (ref($value) eq "ARRAY"){
                   11082:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11083:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11084:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11085:                         if ($lock_descriptor eq 'graded') {
                   11086:                             $readonly_files{$file_name} = 'graded';
                   11087:                         } elsif ($lock_descriptor eq 'handback') {
                   11088:                             $readonly_files{$file_name} = 'handback';
                   11089:                         } else {
                   11090:                             if (!exists($readonly_files{$file_name})) {
                   11091:                                 $readonly_files{$file_name} = 'locked';
                   11092:                             }
                   11093:                         }
1.745     raeburn  11094:                     }
1.750     banghart 11095:                 } 
1.577     banghart 11096:             }
                   11097:         } 
                   11098:     }
                   11099:     return %readonly_files;
                   11100: }
1.559     banghart 11101: # ------------------------------------------------------------ Unmark as Read Only
                   11102: 
                   11103: sub unmark_as_readonly {
1.629     banghart 11104:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11105:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11106:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11107:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11108:     my $symb_crs = $what;
                   11109:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11110:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11111:     my ($tmp)=keys(%current_permissions);
                   11112:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11113:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11114:     foreach my $file (@readonly_files) {
1.759     albertel 11115: 	my $clean_file = &declutter_portfile($file);
                   11116: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11117: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11118:         my @new_locks;
                   11119:         my @del_keys;
                   11120:         if (ref($current_locks) eq "ARRAY"){
                   11121:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11122:                 my $compare=$locker;
1.749     raeburn  11123:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11124:                     $compare=join('',@{$locker});
1.746     raeburn  11125:                     if ($compare ne $symb_crs) {
                   11126:                         push(@new_locks, $locker);
                   11127:                     }
1.563     banghart 11128:                 }
                   11129:             }
1.650     albertel 11130:             if (scalar(@new_locks) > 0) {
1.563     banghart 11131:                 $current_permissions{$file} = \@new_locks;
                   11132:             } else {
                   11133:                 push(@del_keys, $file);
1.613     albertel 11134:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11135:                 delete($current_permissions{$file});
1.563     banghart 11136:             }
                   11137:         }
1.561     banghart 11138:     }
1.613     albertel 11139:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11140:     return;
                   11141: }
1.512     banghart 11142: 
1.17      www      11143: # ------------------------------------------------------------ Directory lister
                   11144: 
                   11145: sub dirlist {
1.955     raeburn  11146:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11147:     $uri=~s/^\///;
                   11148:     $uri=~s/\/$//;
1.253     stredwic 11149:     my ($udom, $uname);
1.955     raeburn  11150:     if ($getuserdir) {
1.253     stredwic 11151:         $udom = $userdomain;
                   11152:         $uname = $username;
1.955     raeburn  11153:     } else {
                   11154:         (undef,$udom,$uname)=split(/\//,$uri);
                   11155:         if(defined($userdomain)) {
                   11156:             $udom = $userdomain;
                   11157:         }
                   11158:         if(defined($username)) {
                   11159:             $uname = $username;
                   11160:         }
1.253     stredwic 11161:     }
1.955     raeburn  11162:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11163: 
1.955     raeburn  11164:     $dirRoot = $perlvar{'lonDocRoot'};
                   11165:     if (defined($getpropath)) {
                   11166:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11167:         $dirRoot =~ s/\/$//;
1.955     raeburn  11168:     } elsif (defined($getuserdir)) {
                   11169:         my $subdir=$uname.'__';
                   11170:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11171:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11172:                    ."/$udom/$subdir/$uname";
                   11173:     } elsif (defined($alternateRoot)) {
                   11174:         $dirRoot = $alternateRoot;
1.751     banghart 11175:     }
1.253     stredwic 11176: 
                   11177:     if($udom) {
                   11178:         if($uname) {
1.1135    raeburn  11179:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11180:             if ($uhome eq 'no_host') {
                   11181:                 return ([],'no_host');
                   11182:             }
1.955     raeburn  11183:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11184:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11185:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11186:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11187:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11188:             } else {
                   11189:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11190:             }
1.605     matthew  11191:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11192:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11193:                 @listing_results = split(/:/,$listing);
                   11194:             } else {
                   11195:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11196:             }
1.1135    raeburn  11197:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11198:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11199:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11200:                 return ([],$listing);
                   11201:             } else {
                   11202:                 return (\@listing_results);
1.1135    raeburn  11203:             }
1.955     raeburn  11204:         } elsif(!$alternateRoot) {
1.1136    raeburn  11205:             my (%allusers,%listerror);
1.841     albertel 11206: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11207:  	    foreach my $tryserver (keys(%servers)) {
                   11208:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11209:                                   &escape($udom),$tryserver);
                   11210:                 if ($listing eq 'unknown_cmd') {
                   11211: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11212: 				      $udom, $tryserver);
                   11213:                 } else {
                   11214:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11215:                 }
1.841     albertel 11216: 		if ($listing eq 'unknown_cmd') {
                   11217: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11218: 				      $udom, $tryserver);
                   11219: 		    @listing_results = split(/:/,$listing);
                   11220: 		} else {
                   11221: 		    @listing_results =
                   11222: 			map { &unescape($_); } split(/:/,$listing);
                   11223: 		}
1.1136    raeburn  11224:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11225:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11226:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11227:                     $listerror{$tryserver} = $listing;
                   11228:                 } else {
1.841     albertel 11229: 		    foreach my $line (@listing_results) {
                   11230: 			my ($entry) = split(/&/,$line,2);
                   11231: 			$allusers{$entry} = 1;
                   11232: 		    }
                   11233: 		}
1.253     stredwic 11234:             }
1.1136    raeburn  11235:             my @alluserslist=();
1.800     albertel 11236:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11237:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11238:             }
1.1172.2.80  raeburn  11239:             if (!%listerror) {
                   11240:                 # no errors
                   11241:                 return (\@alluserslist);
                   11242:             } elsif (scalar(keys(%servers)) == 1) {
                   11243:                 # one library server, one error
                   11244:                 my ($key) = keys(%listerror);
                   11245:                 return (\@alluserslist, $listerror{$key});
                   11246:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11247:                 # con_lost indicates that we might miss data from at least one
                   11248:                 # library server
                   11249:                 return (\@alluserslist, 'con_lost');
                   11250:             } else {
                   11251:                 # multiple library servers and no con_lost -> data should be
                   11252:                 # complete.
                   11253:                 return (\@alluserslist);
                   11254:             }
                   11255: 
1.253     stredwic 11256:         } else {
1.1136    raeburn  11257:             return ([],'missing username');
1.253     stredwic 11258:         }
1.955     raeburn  11259:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11260:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11261:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11262:         return (\@all_domains);
1.955     raeburn  11263:     } else {
1.1136    raeburn  11264:         return ([],'missing domain');
1.275     stredwic 11265:     }
                   11266: }
                   11267: 
                   11268: # --------------------------------------------- GetFileTimestamp
                   11269: # This function utilizes dirlist and returns the date stamp for
                   11270: # when it was last modified.  It will also return an error of -1
                   11271: # if an error occurs
                   11272: 
                   11273: sub GetFileTimestamp {
1.955     raeburn  11274:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11275:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11276:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11277:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11278:                                     undef,$getuserdir);
                   11279:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11280:         return -1;
                   11281:     }
                   11282:     if (ref($fileref) eq 'ARRAY') {
                   11283:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11284:         # @stats contains first the filename, then the stat output
                   11285:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11286:     } else {
                   11287:         return -1;
1.253     stredwic 11288:     }
1.26      www      11289: }
                   11290: 
1.712     albertel 11291: sub stat_file {
                   11292:     my ($uri) = @_;
1.787     albertel 11293:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11294: 
1.955     raeburn  11295:     my ($udom,$uname,$file);
1.712     albertel 11296:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11297: 	($udom,$uname,$file) =
1.811     albertel 11298: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11299: 	$file = 'userfiles/'.$file;
                   11300:     }
                   11301:     if ($uri =~ m-^/res/-) {
                   11302: 	($udom,$uname) = 
1.807     albertel 11303: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11304: 	$file = $uri;
                   11305:     }
                   11306: 
                   11307:     if (!$udom || !$uname || !$file) {
                   11308: 	# unable to handle the uri
                   11309: 	return ();
                   11310:     }
1.956     raeburn  11311:     my $getpropath;
                   11312:     if ($file =~ /^userfiles\//) {
                   11313:         $getpropath = 1;
                   11314:     }
1.1136    raeburn  11315:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11316:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11317:         return ();
                   11318:     } else {
                   11319:         if (ref($listref) eq 'ARRAY') {
                   11320:             my @stats = split('&',$listref->[0]);
                   11321: 	    shift(@stats); #filename is first
                   11322: 	    return @stats;
                   11323:         }
1.712     albertel 11324:     }
                   11325:     return ();
                   11326: }
                   11327: 
1.26      www      11328: # -------------------------------------------------------- Value of a Condition
                   11329: 
1.713     albertel 11330: # gets the value of a specific preevaluated condition
                   11331: #    stored in the string  $env{user.state.<cid>}
                   11332: # or looks up a condition reference in the bighash and if if hasn't
                   11333: # already been evaluated recurses into docondval to get the value of
                   11334: # the condition, then memoizing it to 
                   11335: #   $env{user.state.<cid>.<condition>}
1.40      www      11336: sub directcondval {
                   11337:     my $number=shift;
1.620     albertel 11338:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11339: 	&Apache::lonuserstate::evalstate();
                   11340:     }
1.713     albertel 11341:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11342: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11343:     } elsif ($number =~ /^_/) {
                   11344: 	my $sub_condition;
                   11345: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11346: 		&GDBM_READER(),0640)) {
                   11347: 	    $sub_condition=$bighash{'conditions'.$number};
                   11348: 	    untie(%bighash);
                   11349: 	}
                   11350: 	my $value = &docondval($sub_condition);
1.949     raeburn  11351: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11352: 	return $value;
                   11353:     }
1.620     albertel 11354:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11355:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11356:     } else {
                   11357:        return 2;
                   11358:     }
                   11359: }
                   11360: 
1.713     albertel 11361: # get the collection of conditions for this resource
1.26      www      11362: sub condval {
                   11363:     my $condidx=shift;
1.54      www      11364:     my $allpathcond='';
1.713     albertel 11365:     foreach my $cond (split(/\|/,$condidx)) {
                   11366: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11367: 	    $allpathcond.=
                   11368: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11369: 	}
1.191     harris41 11370:     }
1.54      www      11371:     $allpathcond=~s/\|$//;
1.713     albertel 11372:     return &docondval($allpathcond);
                   11373: }
                   11374: 
                   11375: #evaluates an expression of conditions
                   11376: sub docondval {
                   11377:     my ($allpathcond) = @_;
                   11378:     my $result=0;
                   11379:     if ($env{'request.course.id'}
                   11380: 	&& defined($allpathcond)) {
                   11381: 	my $operand='|';
                   11382: 	my @stack;
                   11383: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11384: 	    if ($chunk eq '(') {
                   11385: 		push @stack,($operand,$result);
                   11386: 	    } elsif ($chunk eq ')') {
                   11387: 		my $before=pop @stack;
                   11388: 		if (pop @stack eq '&') {
                   11389: 		    $result=$result>$before?$before:$result;
                   11390: 		} else {
                   11391: 		    $result=$result>$before?$result:$before;
                   11392: 		}
                   11393: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11394: 		$operand=$chunk;
                   11395: 	    } else {
                   11396: 		my $new=directcondval($chunk);
                   11397: 		if ($operand eq '&') {
                   11398: 		    $result=$result>$new?$new:$result;
                   11399: 		} else {
                   11400: 		    $result=$result>$new?$result:$new;
                   11401: 		}
                   11402: 	    }
                   11403: 	}
1.26      www      11404:     }
                   11405:     return $result;
1.421     albertel 11406: }
                   11407: 
                   11408: # ---------------------------------------------------- Devalidate courseresdata
                   11409: 
                   11410: sub devalidatecourseresdata {
                   11411:     my ($coursenum,$coursedomain)=@_;
                   11412:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11413:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11414: }
                   11415: 
1.763     www      11416: 
1.200     www      11417: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11418: #
                   11419: #  Parameters:
                   11420: #      $coursenum    - Number of the course.
                   11421: #      $coursedomain - Domain at which the course was created.
                   11422: #  Returns:
                   11423: #     A hash of the course parameters along (I think) with timestamps
                   11424: #     and version info.
1.877     foxr     11425: 
1.624     albertel 11426: sub get_courseresdata {
                   11427:     my ($coursenum,$coursedomain)=@_;
1.200     www      11428:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11429:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11430:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11431:     my %dumpreply;
1.417     albertel 11432:     unless (defined($cached)) {
1.624     albertel 11433: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11434: 	$result=\%dumpreply;
1.251     albertel 11435: 	my ($tmp) = keys(%dumpreply);
                   11436: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11437: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11438: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11439: 	    return $tmp;
1.416     albertel 11440: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11441: 	    $result=undef;
1.599     albertel 11442: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11443: 	}
                   11444:     }
1.624     albertel 11445:     return $result;
                   11446: }
                   11447: 
1.633     albertel 11448: sub devalidateuserresdata {
                   11449:     my ($uname,$udom)=@_;
                   11450:     my $hashid="$udom:$uname";
                   11451:     &devalidate_cache_new('userres',$hashid);
                   11452: }
                   11453: 
1.624     albertel 11454: sub get_userresdata {
                   11455:     my ($uname,$udom)=@_;
                   11456:     #most student don\'t have any data set, check if there is some data
                   11457:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11458: 
                   11459:     my $hashid="$udom:$uname";
                   11460:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11461:     if (!defined($cached)) {
                   11462: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11463: 	$result=\%resourcedata;
                   11464: 	&do_cache_new('userres',$hashid,$result,600);
                   11465:     }
                   11466:     my ($tmp)=keys(%$result);
                   11467:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11468: 	return $result;
                   11469:     }
                   11470:     #error 2 occurs when the .db doesn't exist
                   11471:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11472:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11473: 	    &logthis("<font color=\"blue\">WARNING:".
                   11474: 		     " Trying to get resource data for ".
                   11475: 		     $uname." at ".$udom.": ".
                   11476: 		     $tmp."</font>");
                   11477:         }
1.624     albertel 11478:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11479: 	#&EXT_cache_set($udom,$uname);
                   11480: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11481: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11482:     }
                   11483:     return $tmp;
                   11484: }
1.879     foxr     11485: #----------------------------------------------- resdata - return resource data
                   11486: #  Purpose:
                   11487: #    Return resource data for either users or for a course.
                   11488: #  Parameters:
                   11489: #     $name      - Course/user name.
                   11490: #     $domain    - Name of the domain the user/course is registered on.
                   11491: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11492: #     @which     - Array of names of resources desired.
                   11493: #  Returns:
                   11494: #     The value of the first reasource in @which that is found in the
                   11495: #     resource hash.
                   11496: #  Exceptional Conditions:
                   11497: #     If the $type passed in is not valid (not the string 'course' or 
                   11498: #     'user', an undefined  reference is returned.
                   11499: #     If none of the resources are found, an undef is returned
1.624     albertel 11500: sub resdata {
                   11501:     my ($name,$domain,$type,@which)=@_;
                   11502:     my $result;
                   11503:     if ($type eq 'course') {
                   11504: 	$result=&get_courseresdata($name,$domain);
                   11505:     } elsif ($type eq 'user') {
                   11506: 	$result=&get_userresdata($name,$domain);
                   11507:     }
                   11508:     if (!ref($result)) { return $result; }    
1.251     albertel 11509:     foreach my $item (@which) {
1.927     albertel 11510: 	if (defined($result->{$item->[0]})) {
                   11511: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11512: 	}
1.250     albertel 11513:     }
1.291     albertel 11514:     return undef;
1.200     www      11515: }
                   11516: 
1.1172.2.31  raeburn  11517: sub get_numsuppfiles {
                   11518:     my ($cnum,$cdom,$ignorecache)=@_;
                   11519:     my $hashid=$cnum.':'.$cdom;
                   11520:     my ($suppcount,$cached);
                   11521:     unless ($ignorecache) {
                   11522:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11523:     }
                   11524:     unless (defined($cached)) {
                   11525:         my $chome=&homeserver($cnum,$cdom);
                   11526:         unless ($chome eq 'no_host') {
                   11527:             ($suppcount,my $errors) = (0,0);
                   11528:             my $suppmap = 'supplemental.sequence';
                   11529:             ($suppcount,$errors) =
                   11530:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11531:         }
                   11532:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11533:     }
                   11534:     return $suppcount;
                   11535: }
                   11536: 
1.379     matthew  11537: #
                   11538: # EXT resource caching routines
                   11539: #
                   11540: 
                   11541: sub clear_EXT_cache_status {
1.383     albertel 11542:     &delenv('cache.EXT.');
1.379     matthew  11543: }
                   11544: 
                   11545: sub EXT_cache_status {
                   11546:     my ($target_domain,$target_user) = @_;
1.383     albertel 11547:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11548:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11549:         # We know already the user has no data
                   11550:         return 1;
                   11551:     } else {
                   11552:         return 0;
                   11553:     }
                   11554: }
                   11555: 
                   11556: sub EXT_cache_set {
                   11557:     my ($target_domain,$target_user) = @_;
1.383     albertel 11558:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11559:     #&appenv({$cachename => time});
1.379     matthew  11560: }
                   11561: 
1.28      www      11562: # --------------------------------------------------------- Value of a Variable
1.58      www      11563: sub EXT {
1.715     albertel 11564: 
1.1172.2.28  raeburn  11565:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11566:     unless ($varname) { return ''; }
1.218     albertel 11567:     #get real user name/domain, courseid and symb
                   11568:     my $courseid;
1.359     albertel 11569:     my $publicuser;
1.427     www      11570:     if ($symbparm) {
                   11571: 	$symbparm=&get_symb_from_alias($symbparm);
                   11572:     }
1.218     albertel 11573:     if (!($uname && $udom)) {
1.790     albertel 11574:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11575:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11576:     } else {
1.620     albertel 11577: 	$courseid=$env{'request.course.id'};
1.218     albertel 11578:     }
1.48      www      11579:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11580:     my $rest;
1.320     albertel 11581:     if (defined($therest[0])) {
1.48      www      11582:        $rest=join('.',@therest);
                   11583:     } else {
                   11584:        $rest='';
                   11585:     }
1.320     albertel 11586: 
1.57      www      11587:     my $qualifierrest=$qualifier;
                   11588:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11589:     my $spacequalifierrest=$space;
                   11590:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11591:     if ($realm eq 'user') {
1.48      www      11592: # --------------------------------------------------------------- user.resource
                   11593: 	if ($space eq 'resource') {
1.651     albertel 11594: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11595: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11596: 		 &&
1.1172.2.142  raeburn  11597: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11598: 		# if we are in the middle of processing the resource the
                   11599: 		# get the value we are planning on committing
                   11600:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11601:                     return $Apache::lonhomework::results{$qualifierrest};
                   11602:                 } else {
                   11603:                     return $Apache::lonhomework::history{$qualifierrest};
                   11604:                 }
1.335     albertel 11605: 	    } else {
1.359     albertel 11606: 		my %restored;
1.620     albertel 11607: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11608: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11609: 		} else {
                   11610: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11611: 		}
1.335     albertel 11612: 		return $restored{$qualifierrest};
                   11613: 	    }
1.48      www      11614: # ----------------------------------------------------------------- user.access
                   11615:         } elsif ($space eq 'access') {
1.218     albertel 11616: 	    # FIXME - not supporting calls for a specific user
1.48      www      11617:             return &allowed($qualifier,$rest);
                   11618: # ------------------------------------------ user.preferences, user.environment
                   11619:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11620: 	    if (($uname eq $env{'user.name'}) &&
                   11621: 		($udom eq $env{'user.domain'})) {
                   11622: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11623: 	    } else {
1.359     albertel 11624: 		my %returnhash;
                   11625: 		if (!$publicuser) {
                   11626: 		    %returnhash=&userenvironment($udom,$uname,
                   11627: 						 $qualifierrest);
                   11628: 		}
1.218     albertel 11629: 		return $returnhash{$qualifierrest};
                   11630: 	    }
1.48      www      11631: # ----------------------------------------------------------------- user.course
                   11632:         } elsif ($space eq 'course') {
1.218     albertel 11633: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11634:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11635: # ------------------------------------------------------------------- user.role
                   11636:         } elsif ($space eq 'role') {
1.218     albertel 11637: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11638:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11639:             if ($qualifier eq 'value') {
                   11640: 		return $role;
                   11641:             } elsif ($qualifier eq 'extent') {
                   11642:                 return $where;
                   11643:             }
                   11644: # ----------------------------------------------------------------- user.domain
                   11645:         } elsif ($space eq 'domain') {
1.218     albertel 11646:             return $udom;
1.48      www      11647: # ------------------------------------------------------------------- user.name
                   11648:         } elsif ($space eq 'name') {
1.218     albertel 11649:             return $uname;
1.48      www      11650: # ---------------------------------------------------- Any other user namespace
1.29      www      11651:         } else {
1.359     albertel 11652: 	    my %reply;
                   11653: 	    if (!$publicuser) {
                   11654: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11655: 	    }
                   11656: 	    return $reply{$qualifierrest};
1.48      www      11657:         }
1.236     www      11658:     } elsif ($realm eq 'query') {
                   11659: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11660:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11661: 						[$spacequalifierrest]);
1.620     albertel 11662: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11663:    } elsif ($realm eq 'request') {
1.48      www      11664: # ------------------------------------------------------------- request.browser
                   11665:         if ($space eq 'browser') {
1.1145    bisitz   11666:             return $env{'browser.'.$qualifier};
1.57      www      11667: # ------------------------------------------------------------ request.filename
                   11668:         } else {
1.620     albertel 11669:             return $env{'request.'.$spacequalifierrest};
1.29      www      11670:         }
1.28      www      11671:     } elsif ($realm eq 'course') {
1.48      www      11672: # ---------------------------------------------------------- course.description
1.620     albertel 11673:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11674:     } elsif ($realm eq 'resource') {
1.165     www      11675: 
1.620     albertel 11676: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11677: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11678: 	}
1.693     albertel 11679: 
1.1172.2.30  raeburn  11680:         if ($qualifier eq '') {
                   11681: 	    if ($space eq 'title') {
                   11682: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11683: 	        return &gettitle($symbparm);
                   11684: 	    }
1.693     albertel 11685: 	
1.1172.2.30  raeburn  11686: 	    if ($space eq 'map') {
                   11687: 	        my ($map) = &decode_symb($symbparm);
                   11688: 	        return &symbread($map);
                   11689: 	    }
                   11690:             if ($space eq 'maptitle') {
                   11691:                 my ($map) = &decode_symb($symbparm);
                   11692:                 return &gettitle($map);
                   11693:             }
                   11694: 	    if ($space eq 'filename') {
                   11695: 	        if ($symbparm) {
                   11696: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11697: 	        }
                   11698: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11699: 	    }
1.1172.2.30  raeburn  11700: 
                   11701:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11702:                 if ($space eq 'visibleparts') {
                   11703:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11704:                     my $item;
                   11705:                     if (ref($navmap)) {
                   11706:                         my $res = $navmap->getBySymb($symbparm);
                   11707:                         my $parts = $res->parts();
                   11708:                         if (ref($parts) eq 'ARRAY') {
                   11709:                             $item = join(',',@{$parts});
                   11710:                         }
                   11711:                         undef($navmap);
                   11712:                     }
                   11713:                     return $item;
                   11714:                 }
                   11715:             }
                   11716:         }
1.693     albertel 11717: 
                   11718: 	my ($section, $group, @groups);
1.593     albertel 11719: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11720:         if (($courseid eq '') && ($cid)) {
                   11721:             $courseid = $cid;
                   11722:         }
                   11723: 	if (($symbparm && $courseid) && 
                   11724: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11725: 
1.218     albertel 11726: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11727: 
1.60      www      11728: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11729: 	    my $symbp=$symbparm;
1.735     albertel 11730: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11731: 
                   11732: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11733: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11734: 
1.620     albertel 11735: 	    if (($env{'user.name'} eq $uname) &&
                   11736: 		($env{'user.domain'} eq $udom)) {
                   11737: 		$section=$env{'request.course.sec'};
1.733     raeburn  11738:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11739:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11740: 	    } else {
1.539     albertel 11741: 		if (! defined($usection)) {
1.551     albertel 11742: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11743: 		} else {
                   11744: 		    $section = $usection;
                   11745: 		}
1.733     raeburn  11746:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11747: 	    }
                   11748: 
                   11749: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11750: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11751: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11752: 
1.593     albertel 11753: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11754: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11755: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11756: 
1.60      www      11757: # ----------------------------------------------------------- first, check user
1.624     albertel 11758: 
                   11759: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11760: 				       ([$courselevelr,'resource'],
                   11761: 					[$courselevelm,'map'     ],
                   11762: 					[$courselevel, 'course'  ]));
1.931     albertel 11763: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11764: 
1.594     albertel 11765: # ------------------------------------------------ second, check some of course
1.684     raeburn  11766:             my $coursereply;
1.691     raeburn  11767:             if (@groups > 0) {
                   11768:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11769:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11770:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11771:             }
1.96      www      11772: 
1.684     raeburn  11773: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11774: 				  $env{'course.'.$courseid.'.domain'},
                   11775: 				  'course',
                   11776: 				  ([$seclevelr,   'resource'],
                   11777: 				   [$seclevelm,   'map'     ],
                   11778: 				   [$seclevel,    'course'  ],
                   11779: 				   [$courselevelr,'resource']));
                   11780: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11781: 
1.60      www      11782: # ------------------------------------------------------ third, check map parms
1.218     albertel 11783: 	    my %parmhash=();
                   11784: 	    my $thisparm='';
                   11785: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11786: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11787: 		    &GDBM_READER(),0640)) {
1.218     albertel 11788: 		$thisparm=$parmhash{$symbparm};
                   11789: 		untie(%parmhash);
                   11790: 	    }
1.927     albertel 11791: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11792: 	}
1.594     albertel 11793: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11794: 
1.218     albertel 11795: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11796: 	my $filename;
                   11797: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11798: 	if ($symbparm) {
1.409     www      11799: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11800: 	} else {
1.620     albertel 11801: 	    $filename=$env{'request.filename'};
1.282     albertel 11802: 	}
                   11803: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11804: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11805: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11806: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11807: 
1.927     albertel 11808: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11809: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11810: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11811: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11812: 				     $env{'course.'.$courseid.'.domain'},
                   11813: 				     'course',
1.927     albertel 11814: 				     ([$courselevelm,'map'   ],
                   11815: 				      [$courselevel, 'course']));
                   11816: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11817: 	}
1.145     www      11818: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11819: 	unless ($space eq '0') {
1.336     albertel 11820: 	    my @parts=split(/_/,$space);
                   11821: 	    my $id=pop(@parts);
                   11822: 	    my $part=join('_',@parts);
                   11823: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11824: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11825: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11826: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11827: 	}
1.395     albertel 11828: 	if ($recurse) { return undef; }
                   11829: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11830: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11831: # ---------------------------------------------------- Any other user namespace
                   11832:     } elsif ($realm eq 'environment') {
                   11833: # ----------------------------------------------------------------- environment
1.620     albertel 11834: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11835: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11836: 	} else {
1.770     albertel 11837: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11838: 		return '';
                   11839: 	    }
1.219     albertel 11840: 	    my %returnhash=&userenvironment($udom,$uname,
                   11841: 					    $spacequalifierrest);
                   11842: 	    return $returnhash{$spacequalifierrest};
                   11843: 	}
1.28      www      11844:     } elsif ($realm eq 'system') {
1.48      www      11845: # ----------------------------------------------------------------- system.time
                   11846: 	if ($space eq 'time') {
                   11847: 	    return time;
                   11848:         }
1.696     albertel 11849:     } elsif ($realm eq 'server') {
                   11850: # ----------------------------------------------------------------- system.time
                   11851: 	if ($space eq 'name') {
                   11852: 	    return $ENV{'SERVER_NAME'};
                   11853:         }
1.28      www      11854:     }
1.48      www      11855:     return '';
1.61      www      11856: }
                   11857: 
1.927     albertel 11858: sub get_reply {
                   11859:     my ($reply_value) = @_;
1.940     raeburn  11860:     if (ref($reply_value) eq 'ARRAY') {
                   11861:         if (wantarray) {
                   11862: 	    return @$reply_value;
                   11863:         }
                   11864:         return $reply_value->[0];
                   11865:     } else {
                   11866:         return $reply_value;
1.927     albertel 11867:     }
                   11868: }
                   11869: 
1.691     raeburn  11870: sub check_group_parms {
                   11871:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11872:     my @groupitems = ();
                   11873:     my $resultitem;
1.927     albertel 11874:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11875:     foreach my $group (@{$groups}) {
                   11876:         foreach my $level (@levels) {
1.927     albertel 11877:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11878:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11879:         }
                   11880:     }
                   11881:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11882:                             $env{'course.'.$courseid.'.domain'},
                   11883:                                      'course',@groupitems);
                   11884:     return $coursereply;
                   11885: }
                   11886: 
                   11887: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11888:     my ($courseid,@groups) = @_;
                   11889:     @groups = sort(@groups);
1.691     raeburn  11890:     return @groups;
                   11891: }
                   11892: 
1.395     albertel 11893: sub packages_tab_default {
                   11894:     my ($uri,$varname)=@_;
                   11895:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11896: 
                   11897:     my (@extension,@specifics,$do_default);
                   11898:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11899: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11900: 	if ($pack_type eq 'default') {
                   11901: 	    $do_default=1;
                   11902: 	} elsif ($pack_type eq 'extension') {
                   11903: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11904: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11905: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11906: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11907: 	}
                   11908:     }
                   11909:     # first look for a package that matches the requested part id
                   11910:     foreach my $package (@specifics) {
                   11911: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11912: 	next if ($pack_part ne $part);
                   11913: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11914: 	    return $packagetab{"$pack_type&$name&default"};
                   11915: 	}
                   11916:     }
                   11917:     # look for any possible matching non extension_ package
                   11918:     foreach my $package (@specifics) {
                   11919: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11920: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11921: 	    return $packagetab{"$pack_type&$name&default"};
                   11922: 	}
1.585     albertel 11923: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11924: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11925: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11926: 	}
                   11927:     }
1.738     albertel 11928:     # look for any posible extension_ match
                   11929:     foreach my $package (@extension) {
                   11930: 	my ($package,$pack_type)=@{$package};
                   11931: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11932: 	    return $packagetab{"$pack_type&$name&default"};
                   11933: 	}
                   11934: 	if (defined($packagetab{$package."&$name&default"})) {
                   11935: 	    return $packagetab{$package."&$name&default"};
                   11936: 	}
                   11937:     }
                   11938:     # look for a global default setting
                   11939:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11940: 	return $packagetab{"default&$name&default"};
                   11941:     }
1.395     albertel 11942:     return undef;
                   11943: }
                   11944: 
1.334     albertel 11945: sub add_prefix_and_part {
                   11946:     my ($prefix,$part)=@_;
                   11947:     my $keyroot;
                   11948:     if (defined($prefix) && $prefix !~ /^__/) {
                   11949: 	# prefix that has a part already
                   11950: 	$keyroot=$prefix;
                   11951:     } elsif (defined($prefix)) {
                   11952: 	# prefix that is missing a part
                   11953: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11954:     } else {
                   11955: 	# no prefix at all
                   11956: 	if (defined($part)) { $keyroot='_'.$part; }
                   11957:     }
                   11958:     return $keyroot;
                   11959: }
                   11960: 
1.71      www      11961: # ---------------------------------------------------------------- Get metadata
                   11962: 
1.599     albertel 11963: my %metaentry;
1.1070    www      11964: my %importedpartids;
1.1172.2.99  raeburn  11965: my %importedrespids;
1.71      www      11966: sub metadata {
1.176     www      11967:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11968:     $uri=&declutter($uri);
1.288     albertel 11969:     # if it is a non metadata possible uri return quickly
1.529     albertel 11970:     if (($uri eq '') || 
                   11971: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11972: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11973:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11974: 	return undef;
                   11975:     }
1.1172.2.49  raeburn  11976:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11977: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11978: 	return undef;
1.288     albertel 11979:     }
1.73      www      11980:     my $filename=$uri;
                   11981:     $uri=~s/\.meta$//;
1.172     www      11982: #
                   11983: # Is the metadata already cached?
1.177     www      11984: # Look at timestamp of caching
1.172     www      11985: # Everything is cached by the main uri, libraries are never directly cached
                   11986: #
1.428     albertel 11987:     if (!defined($liburi)) {
1.599     albertel 11988: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11989: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11990:     }
                   11991:     {
1.1069    www      11992: # Imported parts would go here
1.1172.2.99  raeburn  11993:         my @origfiletagids=();
1.1069    www      11994:         my $importedparts=0;
1.1172.2.99  raeburn  11995: 
                   11996: # Imported responseids would go here
                   11997:         my $importedresponses=0;
1.172     www      11998: #
                   11999: # Is this a recursive call for a library?
                   12000: #
1.599     albertel 12001: #	if (! exists($metacache{$uri})) {
                   12002: #	    $metacache{$uri}={};
                   12003: #	}
1.924     albertel 12004: 	my $cachetime = 60*60;
1.171     www      12005:         if ($liburi) {
                   12006: 	    $liburi=&declutter($liburi);
                   12007:             $filename=$liburi;
1.401     bowersj2 12008:         } else {
1.599     albertel 12009: 	    &devalidate_cache_new('meta',$uri);
                   12010: 	    undef(%metaentry);
1.401     bowersj2 12011: 	}
1.140     www      12012:         my %metathesekeys=();
1.73      www      12013:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12014: 	my $metastring;
1.1140    www      12015: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12016: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12017: 	    $metastring = 
1.929     albertel 12018: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12019: 					  ('grade_target' => 'meta'));
                   12020: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12021: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12022:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12023: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12024: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12025: 	    $metastring=&getfile($file);
1.489     albertel 12026: 	}
1.208     albertel 12027:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12028:         my $token;
1.140     www      12029:         undef %metathesekeys;
1.71      www      12030:         while ($token=$parser->get_token) {
1.339     albertel 12031: 	    if ($token->[0] eq 'S') {
                   12032: 		if (defined($token->[2]->{'package'})) {
1.172     www      12033: #
                   12034: # This is a package - get package info
                   12035: #
1.339     albertel 12036: 		    my $package=$token->[2]->{'package'};
                   12037: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12038: 		    if (defined($token->[2]->{'id'})) { 
                   12039: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12040: 		    }
1.599     albertel 12041: 		    if ($metaentry{':packages'}) {
                   12042: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12043: 		    } else {
1.599     albertel 12044: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12045: 		    }
1.736     albertel 12046: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12047: 			my $part=$keyroot;
                   12048: 			$part=~s/^\_//;
1.736     albertel 12049: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12050: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12051: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12052: 			    # ignore package.tab specified default values
                   12053:                             # here &package_tab_default() will fetch those
                   12054: 			    if ($subp eq 'default') { next; }
1.736     albertel 12055: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12056: 			    my $unikey;
                   12057: 			    if ($pack =~ /_0$/) {
                   12058: 				$unikey='parameter_0_'.$name;
                   12059: 				$part=0;
                   12060: 			    } else {
                   12061: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12062: 			    }
1.339     albertel 12063: 			    if ($subp eq 'display') {
                   12064: 				$value.=' [Part: '.$part.']';
                   12065: 			    }
1.599     albertel 12066: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12067: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12068: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12069: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12070: 			    }
1.599     albertel 12071: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12072: 				$metaentry{':'.$unikey}=
                   12073: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12074: 			    }
1.339     albertel 12075: 			}
                   12076: 		    }
                   12077: 		} else {
1.172     www      12078: #
                   12079: # This is not a package - some other kind of start tag
1.339     albertel 12080: #
                   12081: 		    my $entry=$token->[1];
1.1068    www      12082: 		    my $unikey='';
1.175     www      12083: 
1.339     albertel 12084: 		    if ($entry eq 'import') {
1.175     www      12085: #
                   12086: # Importing a library here
1.339     albertel 12087: #
1.1067    www      12088:                         my $location=$parser->get_text('/import');
                   12089:                         my $dir=$filename;
                   12090:                         $dir=~s|[^/]*$||;
                   12091:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12092: 
                   12093:                         my $importid=$token->[2]->{'id'};
1.1068    www      12094:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12095: #
                   12096: # Check metadata for imported file to
                   12097: # see if it contained response items
                   12098: #
                   12099:                         my %currmetaentry = %metaentry;
                   12100:                         my $libresponseorder = &metadata($location,'responseorder');
                   12101:                         my $origfile;
                   12102:                         if ($libresponseorder ne '') {
                   12103:                             if ($#origfiletagids<0) {
                   12104:                                 undef(%importedrespids);
                   12105:                                 undef(%importedpartids);
                   12106:                             }
                   12107:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12108:                             if (@{$importedrespids{$importid}} > 0) {
                   12109:                                 $importedresponses = 1;
                   12110: # We need to get the original file and the imported file to get the response order correct
                   12111: # Load and inspect original file
                   12112:                                 if ($#origfiletagids<0) {
                   12113:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12114:                                     $origfile=&getfile($origfilelocation);
                   12115:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12116:                                 }
                   12117:                             }
                   12118:                         }
                   12119: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12120: # hash populated for imported library file
                   12121:                         %metaentry = %currmetaentry;
                   12122:                         undef(%currmetaentry);
1.1068    www      12123:                         if ($importmode eq 'problem') {
1.1069    www      12124: # Import as problem/response
1.1068    www      12125:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12126:                         } elsif ($importmode eq 'part') {
                   12127: # Import as part(s)
1.1069    www      12128:                            $importedparts=1;
                   12129: # We need to get the original file and the imported file to get the part order correct
                   12130: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12131: # Load and inspect original file if we didn't do that already
                   12132:                            if ($#origfiletagids<0) {
                   12133:                                undef(%importedrespids);
                   12134:                                undef(%importedpartids);
                   12135:                                if ($origfile eq '') {
                   12136:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12137:                                    $origfile=&getfile($origfilelocation);
                   12138:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12139:                                }
1.1070    www      12140:                            }
                   12141: 
1.1069    www      12142: # Load and inspect imported file
                   12143:                            my $impfile=&getfile($location);
                   12144:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12145:                            if ($#impfilepartids>=0) {
                   12146: # This problem had parts
1.1070    www      12147:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12148:                            } else {
                   12149: # Importing by turning a single problem into a problem part
                   12150: # It gets the import-tags ID as part-ID
                   12151:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12152:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12153:                            }
1.1068    www      12154:                         } else {
                   12155: # Normal import
                   12156:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12157:                            if (defined($token->[2]->{'id'})) {
                   12158:                               $unikey.='_'.$token->[2]->{'id'};
                   12159:                            }
1.1067    www      12160:                         }
                   12161: 
1.339     albertel 12162: 			if ($depthcount<20) {
1.736     albertel 12163: 			    my $metadata = 
                   12164: 				&metadata($uri,'keys', $location,$unikey,
                   12165: 					  $depthcount+1);
                   12166: 			    foreach my $meta (split(',',$metadata)) {
                   12167: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12168: 				$metathesekeys{$meta}=1;
1.339     albertel 12169: 			    }
1.1068    www      12170: 			
                   12171:                         }
1.1067    www      12172: 		    } else {
                   12173: #
                   12174: # Not importing, some other kind of non-package, non-library start tag
                   12175: # 
                   12176:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12177:                         if (defined($token->[2]->{'id'})) {
                   12178:                             $unikey.='_'.$token->[2]->{'id'};
                   12179:                         }
1.339     albertel 12180: 			if (defined($token->[2]->{'name'})) { 
                   12181: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12182: 			}
                   12183: 			$metathesekeys{$unikey}=1;
1.736     albertel 12184: 			foreach my $param (@{$token->[3]}) {
                   12185: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12186: 				$token->[2]->{$param};
1.339     albertel 12187: 			}
                   12188: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12189: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12190: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12191: 		 # only ws inside the tag, and not in default, so use default
                   12192: 		 # as value
1.599     albertel 12193: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12194: 			} elsif ( $internaltext =~ /\S/ ) {
                   12195: 		  # something interesting inside the tag
                   12196: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12197: 			} else {
1.908     albertel 12198: 		  # no interesting values, don't set a default
1.339     albertel 12199: 			}
1.172     www      12200: # end of not-a-package not-a-library import
1.339     albertel 12201: 		    }
1.172     www      12202: # end of not-a-package start tag
1.339     albertel 12203: 		}
1.172     www      12204: # the next is the end of "start tag"
1.339     albertel 12205: 	    }
                   12206: 	}
1.483     albertel 12207: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12208: 	$extension = lc($extension);
                   12209: 	if ($extension eq 'htm') { $extension='html'; }
                   12210: 
1.737     albertel 12211: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12212: 	    #no specific packages #how's our extension
                   12213: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12214: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12215: 					 \%metathesekeys);
                   12216: 	}
1.883     albertel 12217: 
                   12218: 	if (!exists($metaentry{':packages'})
                   12219: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12220: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12221: 		#no specific packages well let's get default then
                   12222: 		if ($key!~/^default&/) { next; }
1.488     albertel 12223: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12224: 					     \%metathesekeys);
                   12225: 	    }
                   12226: 	}
1.338     www      12227: # are there custom rights to evaluate
1.599     albertel 12228: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12229: 
1.338     www      12230:     #
                   12231:     # Importing a rights file here
1.339     albertel 12232:     #
                   12233: 	    unless ($depthcount) {
1.599     albertel 12234: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12235: 		my $dir=$filename;
                   12236: 		$dir=~s|[^/]*$||;
                   12237: 		$location=&filelocation($dir,$location);
1.736     albertel 12238: 		my $rights_metadata =
                   12239: 		    &metadata($uri,'keys',$location,'_rights',
                   12240: 			      $depthcount+1);
                   12241: 		foreach my $rights (split(',',$rights_metadata)) {
                   12242: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12243: 		    $metathesekeys{$rights}=1;
1.339     albertel 12244: 		}
                   12245: 	    }
                   12246: 	}
1.737     albertel 12247: 	# uniqifiy package listing
                   12248: 	my %seen;
                   12249: 	my @uniq_packages =
                   12250: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12251: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12252: 
1.1172.2.99  raeburn  12253:         if (($importedresponses) || ($importedparts)) {
                   12254:             if ($importedparts) {
1.1070    www      12255: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12256:                 $metaentry{':partorder'}='';
                   12257:                 $metathesekeys{'partorder'}=1;
                   12258:             }
                   12259:             if ($importedresponses) {
                   12260: # We had imported responses and need to rebuild responseorder
                   12261:                 $metaentry{':responseorder'}='';
                   12262:                 $metathesekeys{'responseorder'}=1;
                   12263:             }
                   12264:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12265:                 my $origid = $origfiletagids[$index+1];
                   12266:                 if ($origfiletagids[$index] eq 'part') {
                   12267: # Original part, part of the problem
                   12268:                     if ($importedparts) {
                   12269:                         $metaentry{':partorder'}.=','.$origid;
                   12270:                     }
                   12271:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12272:                     if ($importedparts) {
                   12273: # We have imported parts at this position
                   12274:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12275:                     }
                   12276:                     if ($importedresponses) {
                   12277: # We have imported responses at this position
                   12278:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12279:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12280:                         }
                   12281:                     }
                   12282:                 } else {
                   12283: # Original response item, part of the problem
                   12284:                     if ($importedresponses) {
                   12285:                         $metaentry{':responseorder'}.=','.$origid;
                   12286:                     }
                   12287:                 }
                   12288:             }
                   12289:             if ($importedparts) {
                   12290:                 $metaentry{':partorder'}=~s/^\,//;
                   12291:             }
                   12292:             if ($importedresponses) {
                   12293:                 $metaentry{':responseorder'}=~s/^\,//;
                   12294:             }
1.1070    www      12295:         }
                   12296: 
1.737     albertel 12297: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12298: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12299: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12300: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12301: # this is the end of "was not already recently cached
1.71      www      12302:     }
1.599     albertel 12303:     return $metaentry{':'.$what};
1.261     albertel 12304: }
                   12305: 
1.488     albertel 12306: sub metadata_create_package_def {
1.483     albertel 12307:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12308:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12309:     if ($subp eq 'default') { next; }
                   12310:     
1.599     albertel 12311:     if (defined($metaentry{':packages'})) {
                   12312: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12313:     } else {
1.599     albertel 12314: 	$metaentry{':packages'}=$package;
1.483     albertel 12315:     }
                   12316:     my $value=$packagetab{$key};
                   12317:     my $unikey;
                   12318:     $unikey='parameter_0_'.$name;
1.599     albertel 12319:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12320:     $$metathesekeys{$unikey}=1;
1.599     albertel 12321:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12322: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12323:     }
1.599     albertel 12324:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12325: 	$metaentry{':'.$unikey}=
                   12326: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12327:     }
                   12328: }
                   12329: 
1.261     albertel 12330: sub metadata_generate_part0 {
                   12331:     my ($metadata,$metacache,$uri) = @_;
                   12332:     my %allnames;
1.737     albertel 12333:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12334: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12335: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12336: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12337: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12338: 	    $allnames{$name}=$part;
                   12339: 	  }
                   12340: 	}
                   12341:     }
                   12342:     foreach my $name (keys(%allnames)) {
                   12343:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12344:       my $key=":parameter_0_$name";
1.261     albertel 12345:       $$metacache{"$key.part"}='0';
                   12346:       $$metacache{"$key.name"}=$name;
1.428     albertel 12347:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12348: 					   $allnames{$name}.'_'.$name.
                   12349: 					   '.type'};
1.428     albertel 12350:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12351: 			     '.display'};
1.644     www      12352:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12353:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12354:       $$metacache{"$key.display"}=$olddis;
                   12355:     }
1.71      www      12356: }
                   12357: 
1.764     albertel 12358: # ------------------------------------------------------ Devalidate title cache
                   12359: 
                   12360: sub devalidate_title_cache {
                   12361:     my ($url)=@_;
                   12362:     if (!$env{'request.course.id'}) { return; }
                   12363:     my $symb=&symbread($url);
                   12364:     if (!$symb) { return; }
                   12365:     my $key=$env{'request.course.id'}."\0".$symb;
                   12366:     &devalidate_cache_new('title',$key);
                   12367: }
                   12368: 
1.1014    droeschl 12369: # ------------------------------------------------- Get the title of a course
                   12370: 
                   12371: sub current_course_title {
                   12372:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12373: }
1.301     www      12374: # ------------------------------------------------- Get the title of a resource
                   12375: 
                   12376: sub gettitle {
                   12377:     my $urlsymb=shift;
                   12378:     my $symb=&symbread($urlsymb);
1.534     albertel 12379:     if ($symb) {
1.620     albertel 12380: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12381: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12382: 	if (defined($cached)) { 
                   12383: 	    return $result;
                   12384: 	}
1.534     albertel 12385: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12386: 	my $title='';
1.907     albertel 12387: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12388: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12389: 	} else {
                   12390: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12391: 		    &GDBM_READER(),0640)) {
                   12392: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12393: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12394: 		untie(%bighash);
                   12395: 	    }
1.534     albertel 12396: 	}
                   12397: 	$title=~s/\&colon\;/\:/gs;
                   12398: 	if ($title) {
1.1159    www      12399: # Remember both $symb and $title for dynamic metadata
                   12400:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12401:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12402: # Cache this title and then return it
1.599     albertel 12403: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12404: 	}
                   12405: 	$urlsymb=$url;
                   12406:     }
                   12407:     my $title=&metadata($urlsymb,'title');
                   12408:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12409:     return $title;
1.301     www      12410: }
1.613     albertel 12411: 
1.614     albertel 12412: sub get_slot {
                   12413:     my ($which,$cnum,$cdom)=@_;
                   12414:     if (!$cnum || !$cdom) {
1.790     albertel 12415: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12416: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12417: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12418:     }
1.703     albertel 12419:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12420:     my %slotinfo;
                   12421:     if (exists($remembered{$key})) {
                   12422: 	$slotinfo{$which} = $remembered{$key};
                   12423:     } else {
                   12424: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12425: 	&Apache::lonhomework::showhash(%slotinfo);
                   12426: 	my ($tmp)=keys(%slotinfo);
                   12427: 	if ($tmp=~/^error:/) { return (); }
                   12428: 	$remembered{$key} = $slotinfo{$which};
                   12429:     }
1.616     albertel 12430:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12431: 	return %{$slotinfo{$which}};
                   12432:     }
                   12433:     return $slotinfo{$which};
1.614     albertel 12434: }
1.1150    raeburn  12435: 
                   12436: sub get_reservable_slots {
                   12437:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12438:     my $now = time;
                   12439:     my $reservable_info;
                   12440:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12441:     if (exists($remembered{$key})) {
                   12442:         $reservable_info = $remembered{$key};
                   12443:     } else {
                   12444:         my %resv;
                   12445:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12446:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12447:         $reservable_info = \%resv;
                   12448:         $remembered{$key} = $reservable_info;
                   12449:     }
                   12450:     return $reservable_info;
                   12451: }
                   12452: 
                   12453: sub get_course_slots {
                   12454:     my ($cnum,$cdom) = @_;
                   12455:     my $hashid=$cnum.':'.$cdom;
                   12456:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12457:     if (defined($cached)) {
                   12458:         if (ref($result) eq 'HASH') {
                   12459:             return %{$result};
                   12460:         }
                   12461:     } else {
                   12462:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12463:         my ($tmp) = keys(%slots);
                   12464:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12465:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12466:             return %slots;
                   12467:         }
                   12468:     }
                   12469:     return;
                   12470: }
                   12471: 
                   12472: sub devalidate_slots_cache {
                   12473:     my ($cnum,$cdom)=@_;
                   12474:     my $hashid=$cnum.':'.$cdom;
                   12475:     &devalidate_cache_new('allslots',$hashid);
                   12476: }
                   12477: 
1.1172.2.8  raeburn  12478: sub get_coursechange {
                   12479:     my ($cdom,$cnum) = @_;
                   12480:     if ($cdom eq '' || $cnum eq '') {
                   12481:         return unless ($env{'request.course.id'});
                   12482:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12483:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12484:     }
                   12485:     my $hashid=$cdom.'_'.$cnum;
                   12486:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12487:     if ((defined($cached)) && ($change ne '')) {
                   12488:         return $change;
                   12489:     } else {
                   12490:         my %crshash;
                   12491:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12492:         if ($crshash{'internal.contentchange'} eq '') {
                   12493:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12494:             if ($change eq '') {
                   12495:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12496:                 $change = $crshash{'internal.created'};
                   12497:             }
                   12498:         } else {
                   12499:             $change = $crshash{'internal.contentchange'};
                   12500:         }
                   12501:         my $cachetime = 600;
                   12502:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12503:     }
                   12504:     return $change;
                   12505: }
                   12506: 
                   12507: sub devalidate_coursechange_cache {
                   12508:     my ($cnum,$cdom)=@_;
                   12509:     my $hashid=$cnum.':'.$cdom;
                   12510:     &devalidate_cache_new('crschange',$hashid);
                   12511: }
                   12512: 
1.31      www      12513: # ------------------------------------------------- Update symbolic store links
                   12514: 
                   12515: sub symblist {
                   12516:     my ($mapname,%newhash)=@_;
1.438     www      12517:     $mapname=&deversion(&declutter($mapname));
1.31      www      12518:     my %hash;
1.620     albertel 12519:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12520:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12521:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12522: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12523: 		next if ($url eq 'last_known'
                   12524: 			 && $env{'form.no_update_last_known'});
                   12525: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12526: 						    $newhash{$url}->[1],
                   12527: 						    $newhash{$url}->[0]);
1.191     harris41 12528:             }
1.31      www      12529:             if (untie(%hash)) {
                   12530: 		return 'ok';
                   12531:             }
                   12532:         }
                   12533:     }
                   12534:     return 'error';
1.212     www      12535: }
                   12536: 
                   12537: # --------------------------------------------------------------- Verify a symb
                   12538: 
                   12539: sub symbverify {
1.1172.2.11  raeburn  12540:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12541:     my $thisfn=$thisurl;
1.439     www      12542:     $thisfn=&declutter($thisfn);
1.215     www      12543: # direct jump to resource in page or to a sequence - will construct own symbs
                   12544:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12545: # check URL part
1.409     www      12546:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12547: 
1.431     www      12548:     unless ($url eq $thisfn) { return 0; }
1.213     www      12549: 
1.216     www      12550:     $symb=&symbclean($symb);
1.510     www      12551:     $thisurl=&deversion($thisurl);
1.439     www      12552:     $thisfn=&deversion($thisfn);
1.213     www      12553: 
                   12554:     my %bighash;
                   12555:     my $okay=0;
1.431     www      12556: 
1.620     albertel 12557:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12558:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12559:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12560:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12561:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12562:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12563:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12564:             }
                   12565:         }
                   12566:         my $ids;
1.1172.2.122  raeburn  12567:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12568:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12569:         } else {
                   12570:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12571:         }
1.1102    raeburn  12572:         unless ($ids) {
1.1172.2.13  raeburn  12573:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12574:             $ids=$bighash{$idkey};
1.216     www      12575:         }
                   12576:         if ($ids) {
                   12577: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12578:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12579:                 $symb =~ s/\?.+$//;
                   12580:             }
1.800     albertel 12581: 	    foreach my $id (split(/\,/,$ids)) {
                   12582: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12583:                if (
                   12584:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12585:    eq $symb) {
1.1172.2.11  raeburn  12586:                    if (ref($encstate)) {
                   12587:                        $$encstate = $bighash{'encrypted_'.$id};
                   12588:                    }
1.1172.2.13  raeburn  12589:                    if (($env{'request.role.adv'}) ||
                   12590:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12591:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12592:                        $okay=1;
                   12593:                        last;
                   12594:                    }
                   12595:                }
                   12596:            }
1.216     www      12597:         }
1.213     www      12598: 	untie(%bighash);
                   12599:     }
                   12600:     return $okay;
1.31      www      12601: }
                   12602: 
1.210     www      12603: # --------------------------------------------------------------- Clean-up symb
                   12604: 
                   12605: sub symbclean {
                   12606:     my $symb=shift;
1.568     albertel 12607:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12608: # remove version from map
                   12609:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12610: 
1.210     www      12611: # remove version from URL
                   12612:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12613: 
1.507     www      12614: # remove wrapper
                   12615: 
1.510     www      12616:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12617:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12618:     return $symb;
1.409     www      12619: }
                   12620: 
                   12621: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12622: 
                   12623: sub encode_symb {
                   12624:     my ($map,$resid,$url)=@_;
                   12625:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12626: }
1.409     www      12627: 
                   12628: sub decode_symb {
1.568     albertel 12629:     my $symb=shift;
                   12630:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12631:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12632:     return (&fixversion($map),$resid,&fixversion($url));
                   12633: }
                   12634: 
                   12635: sub fixversion {
                   12636:     my $fn=shift;
1.609     banghart 12637:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12638:     my %bighash;
                   12639:     my $uri=&clutter($fn);
1.620     albertel 12640:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12641: # is this cached?
1.599     albertel 12642:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12643:     if (defined($cached)) { return $result; }
                   12644: # unfortunately not cached, or expired
1.620     albertel 12645:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12646: 	    &GDBM_READER(),0640)) {
                   12647:  	if ($bighash{'version_'.$uri}) {
                   12648:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12649:  	    unless (($version eq 'mostrecent') || 
                   12650: 		    ($version==&getversion($uri))) {
1.440     www      12651:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12652:  	    }
                   12653:  	}
                   12654:  	untie %bighash;
1.413     www      12655:     }
1.599     albertel 12656:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12657: }
                   12658: 
                   12659: sub deversion {
                   12660:     my $url=shift;
                   12661:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12662:     return $url;
1.210     www      12663: }
                   12664: 
1.31      www      12665: # ------------------------------------------------------ Return symb list entry
                   12666: 
                   12667: sub symbread {
1.1172.2.126  raeburn  12668:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12669:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12670:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12671:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12672:         unless (ref($possibles) eq 'HASH') {
                   12673:             if ($ignorecachednull) {
                   12674:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12675:             } else {
                   12676:                 return $env{$cache_str};
                   12677:             }
1.1172.2.66  raeburn  12678:         }
                   12679:     }
1.242     www      12680: # no filename provided? try from environment
1.1172.2.54  raeburn  12681:     unless ($thisfn) {
1.620     albertel 12682:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12683:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12684:         }
                   12685:         $thisfn=$env{'request.filename'};
1.44      www      12686:     }
1.569     albertel 12687:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12688: # is that filename actually a symb? Verify, clean, and return
                   12689:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12690: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12691: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12692: 	}
1.242     www      12693:     }
1.44      www      12694:     $thisfn=declutter($thisfn);
1.31      www      12695:     my %hash;
1.37      www      12696:     my %bighash;
                   12697:     my $syval='';
1.620     albertel 12698:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12699:         my $targetfn = $thisfn;
1.609     banghart 12700:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12701:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12702:         }
1.687     albertel 12703: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12704: 	    $targetfn=$1;
                   12705: 	}
1.1172.2.128  raeburn  12706:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12707:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12708:                           &GDBM_READER(),0640)) {
                   12709: 	        $syval=$hash{$targetfn};
                   12710:                 untie(%hash);
                   12711:             }
1.1172.2.128  raeburn  12712:             if ($syval && $checkforblock) {
                   12713:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12714:                 if (@blockers) {
                   12715:                     $syval='';
                   12716:                 }
                   12717:             }
1.37      www      12718:         }
                   12719: # ---------------------------------------------------------- There was an entry
                   12720:         if ($syval) {
1.601     albertel 12721: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12722: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12723: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12724: 		    #return $env{$cache_str}='';
1.601     albertel 12725: 		#}    
                   12726: 		#$syval.=$1;
                   12727: 	    #}
1.37      www      12728:         } else {
                   12729: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12730:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12731:                             &GDBM_READER(),0640)) {
1.37      www      12732: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12733:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12734:               unless ($ids) { 
                   12735:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12736:               }
                   12737:               unless ($ids) {
                   12738: # alias?
                   12739: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12740:               }
1.37      www      12741:               if ($ids) {
                   12742: # ------------------------------------------------------------------- Has ID(s)
                   12743:                  my @possibilities=split(/\,/,$ids);
1.39      www      12744:                  if ($#possibilities==0) {
                   12745: # ----------------------------------------------- There is only one possibility
1.37      www      12746: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12747: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12748: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12749:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12750:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12751:                              $possibles->{$syval} = 1;
                   12752:                          }
1.1172.2.66  raeburn  12753:                      }
                   12754:                      if ($checkforblock) {
1.1172.2.126  raeburn  12755:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12756:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12757:                              if (@blockers) {
                   12758:                                  $syval = '';
                   12759:                                  untie(%bighash);
                   12760:                                  return $env{$cache_str}='';
                   12761:                              }
1.1172.2.66  raeburn  12762:                          }
                   12763:                      }
                   12764:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12765: # ------------------------------------------ There is more than one possibility
                   12766:                      my $realpossible=0;
1.800     albertel 12767:                      foreach my $id (@possibilities) {
                   12768: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12769:                          my $canaccess;
                   12770:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12771:                              $canaccess = 1;
                   12772:                          } else {
                   12773:                              $canaccess = &allowed('bre',$file);
                   12774:                          }
                   12775:                          if ($canaccess) {
                   12776:          		     my ($mapid,$resid)=split(/\./,$id);
                   12777:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12778:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12779:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12780:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12781:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12782:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12783:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12784:                                      if (@blockers > 0) {
                   12785:                                          $syval = '';
                   12786:                                      } else {
1.1172.2.66  raeburn  12787:                                          $syval = $poss_syval;
                   12788:                                          $realpossible++;
                   12789:                                      }
                   12790:                                  } else {
                   12791:                                      $syval = $poss_syval;
                   12792:                                      $realpossible++;
                   12793:                                  }
1.1172.2.126  raeburn  12794:                                  if ($syval) {
                   12795:                                      if (ref($possibles) eq 'HASH') {
                   12796:                                          $possibles->{$syval} = 1;
                   12797:                                      }
                   12798:                                  }
1.1172.2.66  raeburn  12799:                              }
1.39      www      12800: 			 }
1.191     harris41 12801:                      }
1.39      www      12802: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12803:                  } else {
                   12804:                      $syval='';
1.37      www      12805:                  }
                   12806: 	      }
1.1172.2.66  raeburn  12807:               untie(%bighash);
1.481     raeburn  12808:            }
1.31      www      12809:         }
1.62      www      12810:         if ($syval) {
1.1172.2.128  raeburn  12811: 	    return $env{$cache_str}=$syval;
1.62      www      12812:         }
1.31      www      12813:     }
1.949     raeburn  12814:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12815:     return $env{$cache_str}='';
1.31      www      12816: }
                   12817: 
                   12818: # ---------------------------------------------------------- Return random seed
                   12819: 
1.32      www      12820: sub numval {
                   12821:     my $txt=shift;
                   12822:     $txt=~tr/A-J/0-9/;
                   12823:     $txt=~tr/a-j/0-9/;
                   12824:     $txt=~tr/K-T/0-9/;
                   12825:     $txt=~tr/k-t/0-9/;
                   12826:     $txt=~tr/U-Z/0-5/;
                   12827:     $txt=~tr/u-z/0-5/;
                   12828:     $txt=~s/\D//g;
1.564     albertel 12829:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12830:     return int($txt);
1.368     albertel 12831: }
                   12832: 
1.484     albertel 12833: sub numval2 {
                   12834:     my $txt=shift;
                   12835:     $txt=~tr/A-J/0-9/;
                   12836:     $txt=~tr/a-j/0-9/;
                   12837:     $txt=~tr/K-T/0-9/;
                   12838:     $txt=~tr/k-t/0-9/;
                   12839:     $txt=~tr/U-Z/0-5/;
                   12840:     $txt=~tr/u-z/0-5/;
                   12841:     $txt=~s/\D//g;
                   12842:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12843:     my $total;
                   12844:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12845:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12846:     return int($total);
                   12847: }
                   12848: 
1.575     albertel 12849: sub numval3 {
                   12850:     use integer;
                   12851:     my $txt=shift;
                   12852:     $txt=~tr/A-J/0-9/;
                   12853:     $txt=~tr/a-j/0-9/;
                   12854:     $txt=~tr/K-T/0-9/;
                   12855:     $txt=~tr/k-t/0-9/;
                   12856:     $txt=~tr/U-Z/0-5/;
                   12857:     $txt=~tr/u-z/0-5/;
                   12858:     $txt=~s/\D//g;
                   12859:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12860:     my $total;
                   12861:     foreach my $val (@txts) { $total+=$val; }
                   12862:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12863:     return $total;
                   12864: }
                   12865: 
1.675     albertel 12866: sub digest {
                   12867:     my ($data)=@_;
                   12868:     my $digest=&Digest::MD5::md5($data);
                   12869:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12870:     my ($e,$f);
                   12871:     {
                   12872:         use integer;
                   12873:         $e=($a+$b);
                   12874:         $f=($c+$d);
                   12875:         if ($_64bit) {
                   12876:             $e=(($e<<32)>>32);
                   12877:             $f=(($f<<32)>>32);
                   12878:         }
                   12879:     }
                   12880:     if (wantarray) {
                   12881: 	return ($e,$f);
                   12882:     } else {
                   12883: 	my $g;
                   12884: 	{
                   12885: 	    use integer;
                   12886: 	    $g=($e+$f);
                   12887: 	    if ($_64bit) {
                   12888: 		$g=(($g<<32)>>32);
                   12889: 	    }
                   12890: 	}
                   12891: 	return $g;
                   12892:     }
                   12893: }
                   12894: 
1.368     albertel 12895: sub latest_rnd_algorithm_id {
1.675     albertel 12896:     return '64bit5';
1.366     albertel 12897: }
1.32      www      12898: 
1.503     albertel 12899: sub get_rand_alg {
                   12900:     my ($courseid)=@_;
1.790     albertel 12901:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12902:     if ($courseid) {
1.620     albertel 12903: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12904:     }
                   12905:     return &latest_rnd_algorithm_id();
                   12906: }
                   12907: 
1.562     albertel 12908: sub validCODE {
                   12909:     my ($CODE)=@_;
                   12910:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12911:     return 0;
                   12912: }
                   12913: 
1.491     albertel 12914: sub getCODE {
1.620     albertel 12915:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12916:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12917: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12918: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12919: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12920:     }
                   12921:     return undef;
                   12922: }
1.1133    foxr     12923: #
                   12924: #  Determines the random seed for a specific context:
                   12925: #
                   12926: # parameters:
                   12927: #   symb      - in course context the symb for the seed.
                   12928: #   course_id - The course id of the form domain_coursenum.
                   12929: #   domain    - Domain for the user.
                   12930: #   course    - Course for the user.
                   12931: #   cenv      - environment of the course.
                   12932: #
                   12933: # NOTE:
                   12934: #   All parameters are picked out of the environment if missing
                   12935: #   or not defined.
                   12936: #   If a symb cannot be determined the current time is used instead.
                   12937: #
                   12938: #  For a given well defined symb, courside, domain, username,
                   12939: #  and course environment, the seed is reproducible.
                   12940: #
1.31      www      12941: sub rndseed {
1.1133    foxr     12942:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12943:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12944:     if (!defined($symb)) {
1.366     albertel 12945: 	unless ($symb=$wsymb) { return time; }
                   12946:     }
1.1146    foxr     12947:     if (!defined $courseid) { 
                   12948: 	$courseid=$wcourseid; 
                   12949:     }
                   12950:     if (!defined $domain) { $domain=$wdomain; }
                   12951:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12952: 
                   12953:     my $which;
                   12954:     if (defined($cenv->{'rndseed'})) {
                   12955: 	$which = $cenv->{'rndseed'};
                   12956:     } else {
                   12957: 	$which =&get_rand_alg($courseid);
                   12958:     }
1.491     albertel 12959:     if (defined(&getCODE())) {
1.675     albertel 12960: 	if ($which eq '64bit5') {
                   12961: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12962: 	} elsif ($which eq '64bit4') {
1.575     albertel 12963: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12964: 	} else {
                   12965: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12966: 	}
1.675     albertel 12967:     } elsif ($which eq '64bit5') {
                   12968: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12969:     } elsif ($which eq '64bit4') {
                   12970: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12971:     } elsif ($which eq '64bit3') {
                   12972: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12973:     } elsif ($which eq '64bit2') {
                   12974: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12975:     } elsif ($which eq '64bit') {
                   12976: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12977:     }
                   12978:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12979: }
                   12980: 
                   12981: sub rndseed_32bit {
                   12982:     my ($symb,$courseid,$domain,$username)=@_;
                   12983:     {
                   12984: 	use integer;
                   12985: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12986: 	my $symbseed=numval($symb) << 22;
                   12987: 	my $namechck=unpack("%32C*",$username) << 17;
                   12988: 	my $nameseed=numval($username) << 12;
                   12989: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12990: 	my $courseseed=unpack("%32C*",$courseid);
                   12991: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12992: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12993: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12994: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12995: 	return $num;
                   12996:     }
                   12997: }
                   12998: 
                   12999: sub rndseed_64bit {
                   13000:     my ($symb,$courseid,$domain,$username)=@_;
                   13001:     {
                   13002: 	use integer;
                   13003: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13004: 	my $symbseed=numval($symb) << 10;
                   13005: 	my $namechck=unpack("%32S*",$username);
                   13006: 	
                   13007: 	my $nameseed=numval($username) << 21;
                   13008: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13009: 	my $courseseed=unpack("%32S*",$courseid);
                   13010: 	
                   13011: 	my $num1=$symbchck+$symbseed+$namechck;
                   13012: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13013: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13014: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13015: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13016: 	return "$num1,$num2";
1.155     albertel 13017:     }
1.366     albertel 13018: }
                   13019: 
1.443     albertel 13020: sub rndseed_64bit2 {
                   13021:     my ($symb,$courseid,$domain,$username)=@_;
                   13022:     {
                   13023: 	use integer;
                   13024: 	# strings need to be an even # of cahracters long, it it is odd the
                   13025:         # last characters gets thrown away
                   13026: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13027: 	my $symbseed=numval($symb) << 10;
                   13028: 	my $namechck=unpack("%32S*",$username.' ');
                   13029: 	
                   13030: 	my $nameseed=numval($username) << 21;
1.501     albertel 13031: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13032: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13033: 	
                   13034: 	my $num1=$symbchck+$symbseed+$namechck;
                   13035: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13036: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13037: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13038: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13039: 	return "$num1,$num2";
                   13040:     }
                   13041: }
                   13042: 
                   13043: sub rndseed_64bit3 {
                   13044:     my ($symb,$courseid,$domain,$username)=@_;
                   13045:     {
                   13046: 	use integer;
                   13047: 	# strings need to be an even # of cahracters long, it it is odd the
                   13048:         # last characters gets thrown away
                   13049: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13050: 	my $symbseed=numval2($symb) << 10;
                   13051: 	my $namechck=unpack("%32S*",$username.' ');
                   13052: 	
                   13053: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13054: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13055: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13056: 	
                   13057: 	my $num1=$symbchck+$symbseed+$namechck;
                   13058: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13059: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13060: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13061: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13062: 	
1.503     albertel 13063: 	return "$num1:$num2";
1.443     albertel 13064:     }
                   13065: }
                   13066: 
1.575     albertel 13067: sub rndseed_64bit4 {
                   13068:     my ($symb,$courseid,$domain,$username)=@_;
                   13069:     {
                   13070: 	use integer;
                   13071: 	# strings need to be an even # of cahracters long, it it is odd the
                   13072:         # last characters gets thrown away
                   13073: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13074: 	my $symbseed=numval3($symb) << 10;
                   13075: 	my $namechck=unpack("%32S*",$username.' ');
                   13076: 	
                   13077: 	my $nameseed=numval3($username) << 21;
                   13078: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13079: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13080: 	
                   13081: 	my $num1=$symbchck+$symbseed+$namechck;
                   13082: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13083: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13084: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13085: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13086: 	
1.575     albertel 13087: 	return "$num1:$num2";
                   13088:     }
                   13089: }
                   13090: 
1.675     albertel 13091: sub rndseed_64bit5 {
                   13092:     my ($symb,$courseid,$domain,$username)=@_;
                   13093:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13094:     return "$num1:$num2";
                   13095: }
                   13096: 
1.366     albertel 13097: sub rndseed_CODE_64bit {
                   13098:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13099:     {
1.366     albertel 13100: 	use integer;
1.443     albertel 13101: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13102: 	my $symbseed=numval2($symb);
1.491     albertel 13103: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13104: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13105: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13106: 	my $num1=$symbseed+$CODEchck;
                   13107: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13108: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13109: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13110: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13111: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13112: 	return "$num1:$num2";
1.366     albertel 13113:     }
                   13114: }
                   13115: 
1.575     albertel 13116: sub rndseed_CODE_64bit4 {
                   13117:     my ($symb,$courseid,$domain,$username)=@_;
                   13118:     {
                   13119: 	use integer;
                   13120: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13121: 	my $symbseed=numval3($symb);
                   13122: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13123: 	my $CODEseed=numval3(&getCODE());
                   13124: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13125: 	my $num1=$symbseed+$CODEchck;
                   13126: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13127: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13128: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13129: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13130: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13131: 	return "$num1:$num2";
                   13132:     }
                   13133: }
                   13134: 
1.675     albertel 13135: sub rndseed_CODE_64bit5 {
                   13136:     my ($symb,$courseid,$domain,$username)=@_;
                   13137:     my $code = &getCODE();
                   13138:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13139:     return "$num1:$num2";
                   13140: }
                   13141: 
1.366     albertel 13142: sub setup_random_from_rndseed {
                   13143:     my ($rndseed)=@_;
1.503     albertel 13144:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13145: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13146:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13147:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13148:         } else {
                   13149:             &Math::Random::random_set_seed($num1,$num2);
                   13150:         }
1.366     albertel 13151:     } else {
                   13152: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13153:     }
1.36      albertel 13154: }
                   13155: 
1.474     albertel 13156: sub latest_receipt_algorithm_id {
1.835     albertel 13157:     return 'receipt3';
1.474     albertel 13158: }
                   13159: 
1.480     www      13160: sub recunique {
                   13161:     my $fucourseid=shift;
                   13162:     my $unique;
1.835     albertel 13163:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13164: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13165: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13166:     } else {
                   13167: 	$unique=$perlvar{'lonReceipt'};
                   13168:     }
                   13169:     return unpack("%32C*",$unique);
                   13170: }
                   13171: 
                   13172: sub recprefix {
                   13173:     my $fucourseid=shift;
                   13174:     my $prefix;
1.835     albertel 13175:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13176: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13177: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13178:     } else {
                   13179: 	$prefix=$perlvar{'lonHostID'};
                   13180:     }
                   13181:     return unpack("%32C*",$prefix);
                   13182: }
                   13183: 
1.76      www      13184: sub ireceipt {
1.474     albertel 13185:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13186: 
                   13187:     my $return =&recprefix($fucourseid).'-';
                   13188: 
                   13189:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13190: 	$env{'request.state'} eq 'construct') {
                   13191: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13192: 	return $return;
                   13193:     }
                   13194: 
1.76      www      13195:     my $cuname=unpack("%32C*",$funame);
                   13196:     my $cudom=unpack("%32C*",$fudom);
                   13197:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13198:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13199:     my $cunique=&recunique($fucourseid);
1.474     albertel 13200:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13201:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13202: 
1.790     albertel 13203: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13204: 			       
                   13205: 	$return.= ($cunique%$cuname+
                   13206: 		   $cunique%$cudom+
                   13207: 		   $cusymb%$cuname+
                   13208: 		   $cusymb%$cudom+
                   13209: 		   $cucourseid%$cuname+
                   13210: 		   $cucourseid%$cudom+
                   13211: 		   $cpart%$cuname+
                   13212: 		   $cpart%$cudom);
                   13213:     } else {
                   13214: 	$return.= ($cunique%$cuname+
                   13215: 		   $cunique%$cudom+
                   13216: 		   $cusymb%$cuname+
                   13217: 		   $cusymb%$cudom+
                   13218: 		   $cucourseid%$cuname+
                   13219: 		   $cucourseid%$cudom);
                   13220:     }
                   13221:     return $return;
1.76      www      13222: }
                   13223: 
                   13224: sub receipt {
1.474     albertel 13225:     my ($part)=@_;
1.790     albertel 13226:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13227:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13228: }
1.260     ng       13229: 
1.790     albertel 13230: sub whichuser {
                   13231:     my ($passedsymb)=@_;
                   13232:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13233:     if (defined($env{'form.grade_symb'})) {
                   13234: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13235: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13236: 	if (!$allowed &&
                   13237: 	    exists($env{'request.course.sec'}) &&
                   13238: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13239: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13240: 			      '/'.$env{'request.course.sec'});
                   13241: 	}
                   13242: 	if ($allowed) {
                   13243: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13244: 	    $courseid=$tmp_courseid;
                   13245: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13246: 	    ($name)=&get_env_multiple('form.grade_username');
                   13247: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13248: 	}
                   13249:     }
                   13250:     if (!$passedsymb) {
                   13251: 	$symb=&symbread();
                   13252:     } else {
                   13253: 	$symb=$passedsymb;
                   13254:     }
                   13255:     $courseid=$env{'request.course.id'};
                   13256:     $domain=$env{'user.domain'};
                   13257:     $name=$env{'user.name'};
                   13258:     if ($name eq 'public' && $domain eq 'public') {
                   13259: 	if (!defined($env{'form.username'})) {
                   13260: 	    $env{'form.username'}.=time.rand(10000000);
                   13261: 	}
                   13262: 	$name.=$env{'form.username'};
                   13263:     }
                   13264:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13265: 
                   13266: }
                   13267: 
1.36      albertel 13268: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13269: # returns either the contents of the file or 
                   13270: # -1 if the file doesn't exist
1.481     raeburn  13271: #
                   13272: # if the target is a file that was uploaded via DOCS, 
                   13273: # a check will be made to see if a current copy exists on the local server,
                   13274: # if it does this will be served, otherwise a copy will be retrieved from
                   13275: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13276: # the local server.   
1.472     albertel 13277: 
1.36      albertel 13278: sub getfile {
1.538     albertel 13279:     my ($file) = @_;
1.609     banghart 13280:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13281:     &repcopy($file);
                   13282:     return &readfile($file);
                   13283: }
                   13284: 
                   13285: sub repcopy_userfile {
                   13286:     my ($file)=@_;
1.1142    raeburn  13287:     my $londocroot = $perlvar{'lonDocRoot'};
                   13288:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13289:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13290:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13291: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13292:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13293:     if (-e "$file") {
1.828     www      13294: # we already have a local copy, check it out
1.538     albertel 13295: 	my @fileinfo = stat($file);
1.828     www      13296: 	my $rtncode;
                   13297: 	my $info;
1.538     albertel 13298: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13299: 	if ($lwpresp ne 'ok') {
1.828     www      13300: # there is no such file anymore, even though we had a local copy
1.482     albertel 13301: 	    if ($rtncode eq '404') {
1.538     albertel 13302: 		unlink($file);
1.482     albertel 13303: 	    }
                   13304: 	    return -1;
                   13305: 	}
                   13306: 	if ($info < $fileinfo[9]) {
1.828     www      13307: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13308: 	    return 'ok';
1.828     www      13309: 	} else {
                   13310: # the file is outdated, get rid of it
                   13311: 	    unlink($file);
1.482     albertel 13312: 	}
1.828     www      13313:     }
                   13314: # one way or the other, at this point, we don't have the file
                   13315: # construct the correct path for the file
                   13316:     my @parts = ($cdom,$cnum); 
                   13317:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13318: 	push @parts, split(/\//,$1);
                   13319:     }
                   13320:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13321:     foreach my $part (@parts) {
                   13322: 	$path .= '/'.$part;
                   13323: 	if (!-e $path) {
                   13324: 	    mkdir($path,0770);
1.482     albertel 13325: 	}
                   13326:     }
1.828     www      13327: # now the path exists for sure
                   13328: # get a user agent
                   13329:     my $ua=new LWP::UserAgent;
                   13330:     my $transferfile=$file.'.in.transfer';
                   13331: # FIXME: this should flock
                   13332:     if (-e $transferfile) { return 'ok'; }
                   13333:     my $request;
                   13334:     $uri=~s/^\///;
1.980     raeburn  13335:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13336:     my $hostname = &hostname($homeserver);
1.980     raeburn  13337:     my $protocol = $protocol{$homeserver};
                   13338:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13339:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13340:     my $response=$ua->request($request,$transferfile);
                   13341: # did it work?
                   13342:     if ($response->is_error()) {
                   13343: 	unlink($transferfile);
                   13344: 	&logthis("Userfile repcopy failed for $uri");
                   13345: 	return -1;
                   13346:     }
                   13347: # worked, rename the transfer file
                   13348:     rename($transferfile,$file);
1.607     raeburn  13349:     return 'ok';
1.481     raeburn  13350: }
                   13351: 
1.517     albertel 13352: sub tokenwrapper {
                   13353:     my $uri=shift;
1.980     raeburn  13354:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13355:     $uri=~s|^/||;
1.620     albertel 13356:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13357:     my $token=$1;
1.552     albertel 13358:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13359:     if ($udom && $uname && $file) {
                   13360: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13361:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13362:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13363:         my $hostname = &hostname($homeserver);
1.980     raeburn  13364:         my $protocol = $protocol{$homeserver};
                   13365:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13366:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13367:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13368:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13369:     } else {
                   13370:         return '/adm/notfound.html';
                   13371:     }
                   13372: }
                   13373: 
1.828     www      13374: # call with reqtype HEAD: get last modification time
                   13375: # call with reqtype GET: get the file contents
                   13376: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13377: #
1.481     raeburn  13378: sub getuploaded {
                   13379:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13380:     $uri=~s/^\///;
1.980     raeburn  13381:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13382:     my $hostname = &hostname($homeserver);
1.980     raeburn  13383:     my $protocol = $protocol{$homeserver};
                   13384:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13385:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13386:     my $ua=new LWP::UserAgent;
                   13387:     my $request=new HTTP::Request($reqtype,$uri);
                   13388:     my $response=$ua->request($request);
                   13389:     $$rtncode = $response->code;
1.482     albertel 13390:     if (! $response->is_success()) {
                   13391: 	return 'failed';
                   13392:     }      
                   13393:     if ($reqtype eq 'HEAD') {
1.486     www      13394: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13395:     } elsif ($reqtype eq 'GET') {
                   13396: 	$$info = $response->content;
1.472     albertel 13397:     }
1.482     albertel 13398:     return 'ok';
1.36      albertel 13399: }
                   13400: 
1.481     raeburn  13401: sub readfile {
                   13402:     my $file = shift;
                   13403:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13404:     my $fh;
1.1172.2.96  raeburn  13405:     open($fh,"<",$file);
1.481     raeburn  13406:     my $a='';
1.800     albertel 13407:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13408:     return $a;
                   13409: }
                   13410: 
1.36      albertel 13411: sub filelocation {
1.590     banghart 13412:     my ($dir,$file) = @_;
                   13413:     my $location;
                   13414:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13415: 
                   13416:     if ($file =~ m-^/adm/-) {
                   13417: 	$file=~s-^/adm/wrapper/-/-;
                   13418: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13419:     }
1.882     albertel 13420: 
1.1139    www      13421:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13422:         $location = $file;
1.609     banghart 13423:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13424:         my ($udom,$uname,$filename)=
1.811     albertel 13425:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13426:         my $home=&homeserver($uname,$udom);
                   13427:         my $is_me=0;
                   13428:         my @ids=&current_machine_ids();
                   13429:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13430:         if ($is_me) {
1.1117    foxr     13431:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13432:         } else {
                   13433:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13434:   	      $udom.'/'.$uname.'/'.$filename;
                   13435:         }
1.882     albertel 13436:     } elsif ($file =~ m-^/adm/-) {
                   13437: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13438:     } else {
                   13439:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13440:         $file=~s:^/(res|priv)/:/:;
                   13441:         my $space=$1;
1.590     banghart 13442:         if ( !( $file =~ m:^/:) ) {
                   13443:             $location = $dir. '/'.$file;
                   13444:         } else {
1.1142    raeburn  13445:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13446:         }
1.59      albertel 13447:     }
1.590     banghart 13448:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13449:     while ($location=~m{/\.\./}) {
                   13450: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13451: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13452: 	} else {
                   13453: 	    $location=~ s{/\.\./}{/}g;
                   13454: 	}
                   13455:     } #remove dir/..
1.590     banghart 13456:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13457:     return $location;
1.46      www      13458: }
1.36      albertel 13459: 
1.46      www      13460: sub hreflocation {
                   13461:     my ($dir,$file)=@_;
1.980     raeburn  13462:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13463: 	$file=filelocation($dir,$file);
1.700     albertel 13464:     } elsif ($file=~m-^/adm/-) {
                   13465: 	$file=~s-^/adm/wrapper/-/-;
                   13466: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13467:     }
                   13468:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13469: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13470:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13471: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13472: 	        {/uploaded/$1/$2/}x;
1.46      www      13473:     }
1.913     albertel 13474:     if ($file=~ m{^/userfiles/}) {
                   13475: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13476:     }
1.462     albertel 13477:     return $file;
1.465     albertel 13478: }
                   13479: 
1.1139    www      13480: 
                   13481: 
                   13482: 
                   13483: 
1.465     albertel 13484: sub current_machine_domains {
1.853     albertel 13485:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13486: }
                   13487: 
                   13488: sub machine_domains {
                   13489:     my ($hostname) = @_;
1.465     albertel 13490:     my @domains;
1.838     albertel 13491:     my %hostname = &all_hostnames();
1.465     albertel 13492:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13493: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13494: 	if ($hostname eq $name) {
1.844     albertel 13495: 	    push(@domains,&host_domain($id));
1.465     albertel 13496: 	}
                   13497:     }
                   13498:     return @domains;
                   13499: }
                   13500: 
                   13501: sub current_machine_ids {
1.853     albertel 13502:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13503: }
                   13504: 
                   13505: sub machine_ids {
                   13506:     my ($hostname) = @_;
                   13507:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13508:     my @ids;
1.888     albertel 13509:     my %name_to_host = &all_names();
1.889     albertel 13510:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13511: 	return @{ $name_to_host{$hostname} };
                   13512:     }
                   13513:     return;
1.31      www      13514: }
                   13515: 
1.824     raeburn  13516: sub additional_machine_domains {
                   13517:     my @domains;
1.1172.2.142  raeburn  13518:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13519:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13520:             while( my $line = <$fh>) {
                   13521:                 chomp($line);
                   13522:                 $line =~ s/\s//g;
                   13523:                 push(@domains,$line);
                   13524:             }
                   13525:             close($fh);
                   13526:         }
1.824     raeburn  13527:     }
                   13528:     return @domains;
                   13529: }
                   13530: 
                   13531: sub default_login_domain {
                   13532:     my $domain = $perlvar{'lonDefDomain'};
                   13533:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13534:     foreach my $posdom (&current_machine_domains(),
                   13535:                         &additional_machine_domains()) {
                   13536:         if (lc($posdom) eq lc($testdomain)) {
                   13537:             $domain=$posdom;
                   13538:             last;
                   13539:         }
                   13540:     }
                   13541:     return $domain;
                   13542: }
                   13543: 
1.1172.2.106  raeburn  13544: sub shared_institution {
1.1172.2.136  raeburn  13545:     my ($dom,$lonhost) = @_;
                   13546:     if ($lonhost eq '') {
                   13547:         $lonhost = $perlvar{'lonHostID'};
                   13548:     }
1.1172.2.106  raeburn  13549:     my $same_intdom;
1.1172.2.136  raeburn  13550:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13551:     if ($hostintdom ne '') {
                   13552:         my %iphost = &get_iphost();
                   13553:         my $primary_id = &domain($dom,'primary');
                   13554:         my $primary_ip = &get_host_ip($primary_id);
                   13555:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13556:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13557:                 my $intdom = &internet_dom($id);
                   13558:                 if ($intdom eq $hostintdom) {
                   13559:                     $same_intdom = 1;
                   13560:                     last;
                   13561:                 }
                   13562:             }
                   13563:         }
                   13564:     }
                   13565:     return $same_intdom;
                   13566: }
                   13567: 
1.1172.2.120  raeburn  13568: sub uses_sts {
                   13569:     my ($ignore_cache) = @_;
                   13570:     my $lonhost = $perlvar{'lonHostID'};
                   13571:     my $hostname = &hostname($lonhost);
                   13572:     my $sts_on;
                   13573:     if ($protocol{$lonhost} eq 'https') {
                   13574:         my $cachetime = 12*3600;
                   13575:         if (!$ignore_cache) {
                   13576:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13577:             if (defined($cached)) {
                   13578:                 return $sts_on;
                   13579:             }
                   13580:         }
1.1172.2.121  raeburn  13581:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13582:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13583:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13584:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13585:         if ($response->is_success) {
                   13586:             my $has_sts = $response->header('Strict-Transport-Security');
                   13587:             if ($has_sts eq '') {
                   13588:                 $sts_on = 0;
                   13589:             } else {
                   13590:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13591:                     my $maxage = $1;
                   13592:                     if ($maxage) {
                   13593:                         $sts_on = 1;
                   13594:                     } else {
                   13595:                         $sts_on = 0;
                   13596:                     }
                   13597:                 } else {
                   13598:                     $sts_on = 0;
                   13599:                 }
                   13600:             }
                   13601:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13602:         }
                   13603:     }
                   13604:     return;
                   13605: }
                   13606: 
1.1172.2.142  raeburn  13607: sub waf_allssl {
                   13608:     my ($host_name) = @_;
                   13609:     my $alias = &get_proxy_alias();
                   13610:     if ($host_name eq '') {
                   13611:         $host_name = $ENV{'SERVER_NAME'};
                   13612:     }
                   13613:     if (($host_name ne '') && ($alias eq $host_name)) {
                   13614:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   13615:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   13616:         if ($defdomdefaults{'waf_sslopt'}) {
                   13617:             return $defdomdefaults{'waf_sslopt'};
                   13618:         }
                   13619:     }
                   13620:     return;
                   13621: }
                   13622: 
1.1172.2.134  raeburn  13623: sub get_requestor_ip {
                   13624:     my ($r,$nolookup,$noproxy) = @_;
                   13625:     my $from_ip;
                   13626:     if (ref($r)) {
1.1172.2.142  raeburn  13627:         if ($r->can('useragent_ip')) {
                   13628:             if ($noproxy && $r->can('client_ip')) {
                   13629:                 $from_ip = $r->client_ip();
                   13630:             } else {
                   13631:                 $from_ip = $r->useragent_ip();
                   13632:             }
                   13633:         } elsif ($r->connection->can('remote_ip')) {
                   13634:             $from_ip = $r->connection->remote_ip();
                   13635:         } else {
                   13636:             $from_ip = $r->get_remote_host($nolookup);
                   13637:         }
1.1172.2.134  raeburn  13638:     } else {
                   13639:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13640:     }
1.1172.2.142  raeburn  13641:     return $from_ip if ($noproxy);
                   13642:    # Who controls proxy settings for server
                   13643:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   13644:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   13645:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   13646:         if ($proxyinfo->{'vpnint'}) {
                   13647:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   13648:                 return $from_ip;
                   13649:             }
                   13650:         }
                   13651:         if ($proxyinfo->{'trusted'}) {
                   13652:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   13653:                 my $ipheader = $proxyinfo->{'ipheader'};
                   13654:                 my ($ip,$xfor);
                   13655:                 if (ref($r)) {
                   13656:                     if ($ipheader) {
                   13657:                         $ip = $r->headers_in->{$ipheader};
                   13658:                     }
                   13659:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   13660:                 } else {
                   13661:                     if ($ipheader) {
                   13662:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   13663:                     }
                   13664:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   13665:                 }
                   13666:                 if (($ip eq '') && ($xfor ne '')) {
                   13667:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   13668:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   13669:                             $ip = $poss_ip;
                   13670:                             last;
                   13671:                         }
                   13672:                     }
                   13673:                 }
                   13674:                 if ($ip ne '') {
                   13675:                     return $ip;
                   13676:                 }
                   13677:             }
                   13678:         }
                   13679:     }
1.1172.2.134  raeburn  13680:     return $from_ip;
                   13681: }
                   13682: 
1.1172.2.142  raeburn  13683: sub get_proxy_settings {
                   13684:     my ($dom_in_use) = @_;
                   13685:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   13686:     my $proxyinfo = {
                   13687:                        ipheader => $domdefaults{'waf_ipheader'},
                   13688:                        trusted  => $domdefaults{'waf_trusted'},
                   13689:                        vpnint   => $domdefaults{'waf_vpnint'},
                   13690:                        vpnext   => $domdefaults{'waf_vpnext'},
                   13691:                        sslopt   => $domdefaults{'waf_sslopt'},
                   13692:                     };
                   13693:     return $proxyinfo;
                   13694: }
                   13695: 
                   13696: sub ip_match {
                   13697:     my ($ip,$pattern_str) = @_;
                   13698:     $ip=Net::CIDR::cidrvalidate($ip);
                   13699:     if ($ip) {
                   13700:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   13701:     }
                   13702:     return;
                   13703: }
                   13704: 
                   13705: sub get_proxy_alias {
                   13706:     my ($lonid) = @_;
                   13707:     if ($lonid eq '') {
                   13708:         $lonid = $perlvar{'lonHostID'};
                   13709:     }
                   13710:     if (!defined(&hostname($lonid))) {
                   13711:         return;
                   13712:     }
                   13713:     if ($lonid ne '') {
                   13714:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   13715:         if ($cached) {
                   13716:             return $alias;
                   13717:         }
                   13718:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13719:         if ($dom ne '') {
                   13720:             my $cachetime = 60*60*24;
                   13721:             my %domconfig =
                   13722:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13723:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13724:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   13725:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   13726:                 }
                   13727:             }
                   13728:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   13729:         }
                   13730:     }
                   13731:     return;
                   13732: }
                   13733: 
                   13734: sub use_proxy_alias {
                   13735:     my ($r,$lonid) = @_;
                   13736:     my $alias = &get_proxy_alias($lonid);
                   13737:     if ($alias) {
                   13738:         my $dom = &host_domain($lonid);
                   13739:         if ($dom ne '') {
                   13740:             my $proxyinfo = &get_proxy_settings($dom);
                   13741:             my ($vpnint,$remote_ip);
                   13742:             if (ref($proxyinfo) eq 'HASH') {
                   13743:                 $vpnint = $proxyinfo->{'vpnint'};
                   13744:                 if ($vpnint) {
                   13745:                     $remote_ip = &get_requestor_ip($r,1,1);
                   13746:                 }
                   13747:             }
                   13748:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   13749:                 return $alias;
                   13750:             }
                   13751:         }
                   13752:     }
                   13753:     return;
                   13754: }
                   13755: 
                   13756: sub alias_sso {
                   13757:     my ($lonid) = @_;
                   13758:     if ($lonid eq '') {
                   13759:         $lonid = $perlvar{'lonHostID'};
                   13760:     }
                   13761:     if (!defined(&hostname($lonid))) {
                   13762:         return;
                   13763:     }
                   13764:     if ($lonid ne '') {
                   13765:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   13766:         if ($cached) {
                   13767:             return $use_alias;
                   13768:         }
                   13769:         my $dom = &Apache::lonnet::host_domain($lonid);
                   13770:         if ($dom ne '') {
                   13771:             my $cachetime = 60*60*24;
                   13772:             my %domconfig =
                   13773:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   13774:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   13775:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   13776:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   13777:                 }
                   13778:             }
                   13779:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   13780:         }
                   13781:     }
                   13782:     return;
                   13783: }
                   13784: 
                   13785: sub get_saml_landing {
                   13786:     my ($lonid) = @_;
                   13787:     if ($lonid eq '') {
                   13788:         my $defdom = &default_login_domain();
                   13789:         my @hosts = &current_machine_ids();
                   13790:         if (@hosts > 1) {
                   13791:             foreach my $hostid (@hosts) {
                   13792:                 if (&host_domain($hostid) eq $defdom) {
                   13793:                     $lonid = $hostid;
                   13794:                     last;
                   13795:                 }
                   13796:             }
                   13797:         } else {
                   13798:             $lonid = $perlvar{'lonHostID'};
                   13799:         }
                   13800:         if ($lonid) {
                   13801:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   13802:                 return;
                   13803:             }
                   13804:         } else {
                   13805:             return;
                   13806:         }
                   13807:     } elsif (!defined(&hostname($lonid))) {
                   13808:         return;
                   13809:     }
                   13810:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   13811:     if ($cached) {
                   13812:         return $landing;
                   13813:     }
                   13814:     my $dom = &Apache::lonnet::host_domain($lonid);
                   13815:     if ($dom ne '') {
                   13816:         my $cachetime = 60*60*24;
                   13817:         my %domconfig =
                   13818:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   13819:         if (ref($domconfig{'login'}) eq 'HASH') {
                   13820:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   13821:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   13822:                     $landing = 1;
                   13823:                 }
                   13824:             }
                   13825:         }
                   13826:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   13827:     }
                   13828:     return;
                   13829: }
                   13830: 
1.31      www      13831: # ------------------------------------------------------------- Declutters URLs
                   13832: 
                   13833: sub declutter {
                   13834:     my $thisfn=shift;
1.569     albertel 13835:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13836:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13837:         $thisfn=~s{^/home/httpd/html}{};
                   13838:     }
1.31      www      13839:     $thisfn=~s/^\///;
1.697     albertel 13840:     $thisfn=~s|^adm/wrapper/||;
                   13841:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13842:     $thisfn=~s/^res\///;
1.1172    bisitz   13843:     $thisfn=~s/^priv\///;
1.1032    raeburn  13844:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13845:         $thisfn=~s/\?.+$//;
                   13846:     }
1.268     www      13847:     return $thisfn;
                   13848: }
                   13849: 
                   13850: # ------------------------------------------------------------- Clutter up URLs
                   13851: 
                   13852: sub clutter {
                   13853:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13854:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13855: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13856:        $thisfn='/res'.$thisfn; 
                   13857:     }
1.1031    raeburn  13858:     if ($thisfn !~m|^/adm|) {
                   13859: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13860: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13861: 	} else {
                   13862: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13863: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13864: 	    if ($embstyle eq 'ssi'
                   13865: 		|| ($embstyle eq 'hdn')
                   13866: 		|| ($embstyle eq 'rat')
                   13867: 		|| ($embstyle eq 'prv')
                   13868: 		|| ($embstyle eq 'ign')) {
                   13869: 		#do nothing with these
                   13870: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13871: 		|| ($embstyle eq 'emb')
                   13872: 		|| ($embstyle eq 'wrp')) {
                   13873: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13874: 	    } elsif ($embstyle eq 'unk'
                   13875: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13876: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13877: 	    } else {
1.718     www      13878: #		&logthis("Got a blank emb style");
1.695     albertel 13879: 	    }
1.694     albertel 13880: 	}
                   13881:     }
1.31      www      13882:     return $thisfn;
1.12      www      13883: }
                   13884: 
1.787     albertel 13885: sub clutter_with_no_wrapper {
                   13886:     my $uri = &clutter(shift);
                   13887:     if ($uri =~ m-^/adm/-) {
                   13888: 	$uri =~ s-^/adm/wrapper/-/-;
                   13889: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13890:     }
                   13891:     return $uri;
                   13892: }
                   13893: 
1.557     albertel 13894: sub freeze_escape {
                   13895:     my ($value)=@_;
                   13896:     if (ref($value)) {
                   13897: 	$value=&nfreeze($value);
                   13898: 	return '__FROZEN__'.&escape($value);
                   13899:     }
                   13900:     return &escape($value);
                   13901: }
                   13902: 
1.11      www      13903: 
1.557     albertel 13904: sub thaw_unescape {
                   13905:     my ($value)=@_;
                   13906:     if ($value =~ /^__FROZEN__/) {
                   13907: 	substr($value,0,10,undef);
                   13908: 	$value=&unescape($value);
                   13909: 	return &thaw($value);
                   13910:     }
                   13911:     return &unescape($value);
                   13912: }
                   13913: 
1.436     albertel 13914: sub correct_line_ends {
                   13915:     my ($result)=@_;
                   13916:     $$result =~s/\r\n/\n/mg;
                   13917:     $$result =~s/\r/\n/mg;
1.415     albertel 13918: }
1.1       albertel 13919: # ================================================================ Main Program
                   13920: 
1.184     www      13921: sub goodbye {
1.204     albertel 13922:    &logthis("Starting Shut down");
1.443     albertel 13923: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13924:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13925: #converted
1.599     albertel 13926: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13927:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13928: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13929: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13930: #1.1 only
1.870     albertel 13931: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13932: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13933: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13934: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13935:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13936:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13937:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13938:    &flushcourselogs();
                   13939:    &logthis("Shutting down");
                   13940: }
                   13941: 
1.852     albertel 13942: sub get_dns {
1.1172.2.17  raeburn  13943:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13944:     if (!$ignore_cache) {
                   13945: 	my ($content,$cached)=
                   13946: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13947: 	if ($cached) {
1.1172.2.17  raeburn  13948: 	    &$func($content,$hashref);
1.869     albertel 13949: 	    return;
                   13950: 	}
                   13951:     }
                   13952: 
                   13953:     my %alldns;
1.1172.2.96  raeburn  13954:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13955:         foreach my $dns (<$config>) {
                   13956: 	    next if ($dns !~ /^\^(\S*)/x);
                   13957:             my $line = $1;
                   13958:             my ($host,$protocol) = split(/:/,$line);
                   13959:             if ($protocol ne 'https') {
                   13960:                 $protocol = 'http';
                   13961:             }
                   13962: 	    $alldns{$host} = $protocol;
1.979     raeburn  13963:         }
1.1172.2.96  raeburn  13964:         close($config);
1.869     albertel 13965:     }
                   13966:     while (%alldns) {
1.1172.2.52  raeburn  13967: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  13968:         my @content;
                   13969:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   13970:             my $command = (split('/',$url))[3];
                   13971:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   13972:             delete($alldns{$dns});
                   13973:             next if (($dir eq '') || ($file eq ''));
                   13974:             if (open(my $config,'<',"$dir/$file")) {
                   13975:                 @content = <$config>;
                   13976:                 close($config);
                   13977:             }
                   13978:         } else {
                   13979: 	    my $ua=new LWP::UserAgent;
                   13980:             $ua->timeout(30);
                   13981: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   13982: 	    my $response=$ua->request($request);
                   13983:             delete($alldns{$dns});
                   13984: 	    next if ($response->is_error());
                   13985: 	    @content = split("\n",$response->content);
                   13986:         }
1.1172.2.17  raeburn  13987:         unless ($nocache) {
1.1172.2.23  raeburn  13988: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13989:         }
                   13990: 	&$func(\@content,$hashref);
1.869     albertel 13991: 	return;
1.852     albertel 13992:     }
1.871     albertel 13993:     my $which = (split('/',$url))[3];
                   13994:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13995:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13996:         my @content = <$config>;
                   13997:         &$func(\@content,$hashref);
                   13998:     }
1.1172.2.17  raeburn  13999:     return;
                   14000: }
                   14001: 
                   14002: # ------------------------------------------------------Get DNS checksums file
                   14003: sub parse_dns_checksums_tab {
                   14004:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14005:     my $lonhost = $perlvar{'lonHostID'};
                   14006:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14007:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14008:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14009:     my $webconfdir = '/etc/httpd/conf';
                   14010:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14011:         $webconfdir = '/etc/apache2';
                   14012:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14013:         if ($1 >= 10) {
                   14014:             $webconfdir = '/etc/apache2';
                   14015:         }
                   14016:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14017:         if ($1 >= 10.0) {
                   14018:             $webconfdir = '/etc/apache2';
                   14019:         }
                   14020:     }
1.1172.2.17  raeburn  14021:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14022:     my (%chksum,%revnum);
                   14023:     if (ref($lines) eq 'ARRAY') {
                   14024:         chomp(@{$lines});
1.1172.2.34  raeburn  14025:         my $version = shift(@{$lines});
                   14026:         if ($version eq $release) {
1.1172.2.17  raeburn  14027:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14028:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14029:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14030:                     if ($webconfdir eq '/etc/apache2') {
                   14031:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14032:                     }
                   14033:                 }
1.1172.2.34  raeburn  14034:                 $chksum{$file} = $shasum;
                   14035:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14036:             }
                   14037:             if (ref($hashref) eq 'HASH') {
                   14038:                 %{$hashref} = (
                   14039:                                 sums     => \%chksum,
                   14040:                                 versions => \%revnum,
                   14041:                               );
                   14042:             }
                   14043:         }
                   14044:     }
1.869     albertel 14045:     return;
1.852     albertel 14046: }
1.1172.2.17  raeburn  14047: 
                   14048: sub fetch_dns_checksums {
                   14049:     my %checksums;
1.1172.2.34  raeburn  14050:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14051:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14052:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14053:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14054:              \%checksums);
                   14055:     return \%checksums;
                   14056: }
                   14057: 
1.1172.2.142  raeburn  14058: sub parse_getdns_url {
                   14059:     my ($command,$url) = @_;
                   14060:     my $dir = $perlvar{'lonTabDir'};
                   14061:     my $file;
                   14062:     if ($command eq 'hosts') {
                   14063:         $file = 'dns_hosts.tab';
                   14064:     } elsif ($command eq 'domain') {
                   14065:         $file = 'dns_domain.tab';
                   14066:     } elsif ($command eq 'checksums') {
                   14067:         my $version = (split('/',$url))[4];
                   14068:         $file = "dns_checksums/$version.tab",
                   14069:     }
                   14070:     return ($dir,$file);
                   14071: }
                   14072: 
1.327     albertel 14073: # ------------------------------------------------------------ Read domain file
                   14074: {
1.852     albertel 14075:     my $loaded;
1.846     albertel 14076:     my %domain;
                   14077: 
1.852     albertel 14078:     sub parse_domain_tab {
                   14079: 	my ($lines) = @_;
                   14080: 	foreach my $line (@$lines) {
                   14081: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14082: 
1.846     albertel 14083: 	    chomp($line);
1.852     albertel 14084: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14085: 	    my %this_domain;
                   14086: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14087: 			       'lang_def', 'city', 'longi', 'lati',
                   14088: 			       'primary') {
                   14089: 		$this_domain{$field} = shift(@elements);
                   14090: 	    }
                   14091: 	    $domain{$name} = \%this_domain;
1.852     albertel 14092: 	}
                   14093:     }
1.864     albertel 14094: 
                   14095:     sub reset_domain_info {
                   14096: 	undef($loaded);
                   14097: 	undef(%domain);
                   14098:     }
                   14099: 
1.852     albertel 14100:     sub load_domain_tab {
1.1172.2.70  raeburn  14101: 	my ($ignore_cache,$nocache) = @_;
                   14102: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14103: 	my $fh;
1.1172.2.96  raeburn  14104: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14105: 	    my @lines = <$fh>;
                   14106: 	    &parse_domain_tab(\@lines);
1.448     albertel 14107: 	}
1.852     albertel 14108: 	close($fh);
                   14109: 	$loaded = 1;
1.327     albertel 14110:     }
1.846     albertel 14111: 
                   14112:     sub domain {
1.852     albertel 14113: 	&load_domain_tab() if (!$loaded);
                   14114: 
1.846     albertel 14115: 	my ($name,$what) = @_;
                   14116: 	return if ( !exists($domain{$name}) );
                   14117: 
                   14118: 	if (!$what) {
                   14119: 	    return $domain{$name}{'description'};
                   14120: 	}
                   14121: 	return $domain{$name}{$what};
                   14122:     }
1.974     raeburn  14123: 
                   14124:     sub domain_info {
                   14125:         &load_domain_tab() if (!$loaded);
                   14126:         return %domain;
                   14127:     }
                   14128: 
1.327     albertel 14129: }
                   14130: 
                   14131: 
1.1       albertel 14132: # ------------------------------------------------------------- Read hosts file
                   14133: {
1.838     albertel 14134:     my %hostname;
1.844     albertel 14135:     my %hostdom;
1.845     albertel 14136:     my %libserv;
1.852     albertel 14137:     my $loaded;
1.888     albertel 14138:     my %name_to_host;
1.1074    raeburn  14139:     my %internetdom;
1.1107    raeburn  14140:     my %LC_dns_serv;
1.852     albertel 14141: 
                   14142:     sub parse_hosts_tab {
                   14143: 	my ($file) = @_;
                   14144: 	foreach my $configline (@$file) {
                   14145: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14146:             chomp($configline);
                   14147: 	    if ($configline =~ /^\^/) {
                   14148:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14149:                     $LC_dns_serv{$1} = 1;
                   14150:                 }
                   14151:                 next;
                   14152:             }
1.1074    raeburn  14153: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14154: 	    $name=~s/\s//g;
                   14155: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14156:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14157:                     my $curr = $hostname{$id};
                   14158:                     my $skip;
                   14159:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14160:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14161:                             $skip = 1;
                   14162:                         } else {
                   14163:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14164:                         }
                   14165:                     }
                   14166:                     unless ($skip) {
                   14167:                         push(@{$name_to_host{$name}},$id);
                   14168:                     }
                   14169:                 } else {
                   14170:                     push(@{$name_to_host{$name}},$id);
                   14171:                 }
1.852     albertel 14172: 		$hostname{$id}=$name;
                   14173: 		$hostdom{$id}=$domain;
                   14174: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14175:                 if (defined($protocol)) {
                   14176:                     if ($protocol eq 'https') {
                   14177:                         $protocol{$id} = $protocol;
                   14178:                     } else {
                   14179:                         $protocol{$id} = 'http'; 
                   14180:                     }
1.968     raeburn  14181:                 } else {
1.969     raeburn  14182:                     $protocol{$id} = 'http';
1.968     raeburn  14183:                 }
1.1074    raeburn  14184:                 if (defined($intdom)) {
                   14185:                     $internetdom{$id} = $intdom;
                   14186:                 }
1.852     albertel 14187: 	    }
                   14188: 	}
                   14189:     }
1.864     albertel 14190:     
                   14191:     sub reset_hosts_info {
1.897     albertel 14192: 	&purge_remembered();
1.864     albertel 14193: 	&reset_domain_info();
                   14194: 	&reset_hosts_ip_info();
1.892     albertel 14195: 	undef(%name_to_host);
1.864     albertel 14196: 	undef(%hostname);
                   14197: 	undef(%hostdom);
                   14198: 	undef(%libserv);
                   14199: 	undef($loaded);
                   14200:     }
1.1       albertel 14201: 
1.852     albertel 14202:     sub load_hosts_tab {
1.1172.2.70  raeburn  14203: 	my ($ignore_cache,$nocache) = @_;
                   14204: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14205: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14206: 	my @config = <$config>;
                   14207: 	&parse_hosts_tab(\@config);
                   14208: 	close($config);
                   14209: 	$loaded=1;
1.1       albertel 14210:     }
1.852     albertel 14211: 
1.838     albertel 14212:     sub hostname {
1.852     albertel 14213: 	&load_hosts_tab() if (!$loaded);
                   14214: 
1.838     albertel 14215: 	my ($lonid) = @_;
                   14216: 	return $hostname{$lonid};
                   14217:     }
1.845     albertel 14218: 
1.838     albertel 14219:     sub all_hostnames {
1.852     albertel 14220: 	&load_hosts_tab() if (!$loaded);
                   14221: 
1.838     albertel 14222: 	return %hostname;
                   14223:     }
1.845     albertel 14224: 
1.888     albertel 14225:     sub all_names {
1.1172.2.70  raeburn  14226:         my ($ignore_cache,$nocache) = @_;
                   14227: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14228: 
                   14229: 	return %name_to_host;
                   14230:     }
                   14231: 
1.974     raeburn  14232:     sub all_host_domain {
                   14233:         &load_hosts_tab() if (!$loaded);
                   14234:         return %hostdom;
                   14235:     }
                   14236: 
1.845     albertel 14237:     sub is_library {
1.852     albertel 14238: 	&load_hosts_tab() if (!$loaded);
                   14239: 
1.845     albertel 14240: 	return exists($libserv{$_[0]});
                   14241:     }
                   14242: 
                   14243:     sub all_library {
1.852     albertel 14244: 	&load_hosts_tab() if (!$loaded);
                   14245: 
1.845     albertel 14246: 	return %libserv;
                   14247:     }
                   14248: 
1.1062    droeschl 14249:     sub unique_library {
                   14250: 	#2x reverse removes all hostnames that appear more than once
                   14251:         my %unique = reverse &all_library();
                   14252:         return reverse %unique;
                   14253:     }
                   14254: 
1.841     albertel 14255:     sub get_servers {
1.852     albertel 14256: 	&load_hosts_tab() if (!$loaded);
                   14257: 
1.841     albertel 14258: 	my ($domain,$type) = @_;
                   14259: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14260: 	                                          : %hostname;
                   14261: 	my %result;
1.842     albertel 14262: 	if (ref($domain) eq 'ARRAY') {
                   14263: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14264: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14265: 		    $result{$host} = $hostname;
                   14266: 		}
                   14267: 	    }
                   14268: 	} else {
                   14269: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14270: 		if ($hostdom{$host} eq $domain) {
                   14271: 		    $result{$host} = $hostname;
                   14272: 		}
1.841     albertel 14273: 	    }
                   14274: 	}
                   14275: 	return %result;
                   14276:     }
1.845     albertel 14277: 
1.1062    droeschl 14278:     sub get_unique_servers {
                   14279:         my %unique = reverse &get_servers(@_);
                   14280: 	return reverse %unique;
                   14281:     }
                   14282: 
1.844     albertel 14283:     sub host_domain {
1.852     albertel 14284: 	&load_hosts_tab() if (!$loaded);
                   14285: 
1.844     albertel 14286: 	my ($lonid) = @_;
                   14287: 	return $hostdom{$lonid};
                   14288:     }
                   14289: 
1.841     albertel 14290:     sub all_domains {
1.852     albertel 14291: 	&load_hosts_tab() if (!$loaded);
                   14292: 
1.841     albertel 14293: 	my %seen;
                   14294: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14295: 	return @uniq;
                   14296:     }
1.1074    raeburn  14297: 
                   14298:     sub internet_dom {
                   14299:         &load_hosts_tab() if (!$loaded);
                   14300: 
                   14301:         my ($lonid) = @_;
                   14302:         return $internetdom{$lonid};
                   14303:     }
1.1107    raeburn  14304: 
                   14305:     sub is_LC_dns {
                   14306:         &load_hosts_tab() if (!$loaded);
                   14307: 
                   14308:         my ($hostname) = @_;
                   14309:         return exists($LC_dns_serv{$hostname});
                   14310:     }
                   14311: 
1.1       albertel 14312: }
                   14313: 
1.847     albertel 14314: { 
                   14315:     my %iphost;
1.856     albertel 14316:     my %name_to_ip;
                   14317:     my %lonid_to_ip;
1.869     albertel 14318: 
1.847     albertel 14319:     sub get_hosts_from_ip {
                   14320: 	my ($ip) = @_;
                   14321: 	my %iphosts = &get_iphost();
                   14322: 	if (ref($iphosts{$ip})) {
                   14323: 	    return @{$iphosts{$ip}};
                   14324: 	}
                   14325: 	return;
1.839     albertel 14326:     }
1.864     albertel 14327:     
                   14328:     sub reset_hosts_ip_info {
                   14329: 	undef(%iphost);
                   14330: 	undef(%name_to_ip);
                   14331: 	undef(%lonid_to_ip);
                   14332:     }
1.856     albertel 14333: 
                   14334:     sub get_host_ip {
                   14335: 	my ($lonid) = @_;
                   14336: 	if (exists($lonid_to_ip{$lonid})) {
                   14337: 	    return $lonid_to_ip{$lonid};
                   14338: 	}
                   14339: 	my $name=&hostname($lonid);
                   14340:    	my $ip = gethostbyname($name);
                   14341: 	return if (!$ip || length($ip) ne 4);
                   14342: 	$ip=inet_ntoa($ip);
                   14343: 	$name_to_ip{$name}   = $ip;
                   14344: 	$lonid_to_ip{$lonid} = $ip;
                   14345: 	return $ip;
                   14346:     }
1.847     albertel 14347:     
                   14348:     sub get_iphost {
1.1172.2.70  raeburn  14349: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14350: 
1.869     albertel 14351: 	if (!$ignore_cache) {
                   14352: 	    if (%iphost) {
                   14353: 		return %iphost;
                   14354: 	    }
                   14355: 	    my ($ip_info,$cached)=
                   14356: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14357: 	    if ($cached) {
                   14358: 		%iphost      = %{$ip_info->[0]};
                   14359: 		%name_to_ip  = %{$ip_info->[1]};
                   14360: 		%lonid_to_ip = %{$ip_info->[2]};
                   14361: 		return %iphost;
                   14362: 	    }
                   14363: 	}
1.894     albertel 14364: 
                   14365: 	# get yesterday's info for fallback
                   14366: 	my %old_name_to_ip;
                   14367: 	my ($ip_info,$cached)=
                   14368: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14369: 	if ($cached) {
                   14370: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14371: 	}
                   14372: 
1.1172.2.70  raeburn  14373: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14374: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14375: 	    my $ip;
                   14376: 	    if (!exists($name_to_ip{$name})) {
                   14377: 		$ip = gethostbyname($name);
                   14378: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14379: 		    if (defined($old_name_to_ip{$name})) {
                   14380: 			$ip = $old_name_to_ip{$name};
                   14381: 			&logthis("Can't find $name defaulting to old $ip");
                   14382: 		    } else {
                   14383: 			&logthis("Name $name no IP found");
                   14384: 			next;
                   14385: 		    }
                   14386: 		} else {
                   14387: 		    $ip=inet_ntoa($ip);
1.847     albertel 14388: 		}
                   14389: 		$name_to_ip{$name} = $ip;
                   14390: 	    } else {
                   14391: 		$ip = $name_to_ip{$name};
1.653     albertel 14392: 	    }
1.888     albertel 14393: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14394: 		$lonid_to_ip{$id} = $ip;
                   14395: 	    }
                   14396: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14397: 	}
1.1172.2.70  raeburn  14398:         unless ($nocache) {
                   14399: 	    &do_cache_new('iphost','iphost',
                   14400: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14401: 		          48*60*60);
                   14402:         }
1.869     albertel 14403: 
1.847     albertel 14404: 	return %iphost;
1.598     albertel 14405:     }
                   14406: 
1.992     raeburn  14407:     #
                   14408:     #  Given a DNS returns the loncapa host name for that DNS 
                   14409:     # 
                   14410:     sub host_from_dns {
                   14411:         my ($dns) = @_;
                   14412:         my @hosts;
                   14413:         my $ip;
                   14414: 
1.993     raeburn  14415:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14416:             $ip = $name_to_ip{$dns};
                   14417:         }
                   14418:         if (!$ip) {
                   14419:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14420:             if (length($ip) == 4) { 
                   14421: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14422:             }
                   14423:         }
                   14424:         if ($ip) {
                   14425: 	    @hosts = get_hosts_from_ip($ip);
                   14426: 	    return $hosts[0];
                   14427:         }
                   14428:         return undef;
1.986     foxr     14429:     }
1.992     raeburn  14430: 
1.1074    raeburn  14431:     sub get_internet_names {
                   14432:         my ($lonid) = @_;
                   14433:         return if ($lonid eq '');
                   14434:         my ($idnref,$cached)=
                   14435:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14436:         if ($cached) {
                   14437:             return $idnref;
                   14438:         }
                   14439:         my $ip = &get_host_ip($lonid);
                   14440:         my @hosts = &get_hosts_from_ip($ip);
                   14441:         my %iphost = &get_iphost();
                   14442:         my (@idns,%seen);
                   14443:         foreach my $id (@hosts) {
                   14444:             my $dom = &host_domain($id);
                   14445:             my $prim_id = &domain($dom,'primary');
                   14446:             my $prim_ip = &get_host_ip($prim_id);
                   14447:             next if ($seen{$prim_ip});
                   14448:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14449:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14450:                     my $intdom = &internet_dom($id);
                   14451:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14452:                         push(@idns,$intdom);
                   14453:                     }
                   14454:                 }
                   14455:             }
                   14456:             $seen{$prim_ip} = 1;
                   14457:         }
1.1172.2.23  raeburn  14458:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14459:     }
                   14460: 
1.986     foxr     14461: }
                   14462: 
1.1079    raeburn  14463: sub all_loncaparevs {
1.1172.2.39  raeburn  14464:     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  14465: }
                   14466: 
1.1172.2.27  raeburn  14467: # ------------------------------------------------------- Read loncaparev table
                   14468: {
                   14469:     sub load_loncaparevs {
                   14470:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14471:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14472:                 while (my $configline=<$config>) {
                   14473:                     chomp($configline);
                   14474:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14475:                     $loncaparevs{$hostid}=$loncaparev;
                   14476:                 }
                   14477:                 close($config);
                   14478:             }
                   14479:         }
                   14480:     }
                   14481: }
                   14482: 
                   14483: # ----------------------------------------------------- Read serverhostID table
                   14484: {
                   14485:     sub load_serverhomeIDs {
                   14486:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14487:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14488:                 while (my $configline=<$config>) {
                   14489:                     chomp($configline);
                   14490:                     my ($name,$id)=split(/:/,$configline);
                   14491:                     $serverhomeIDs{$name}=$id;
                   14492:                 }
                   14493:                 close($config);
                   14494:             }
                   14495:         }
                   14496:     }
                   14497: }
                   14498: 
                   14499: 
1.862     albertel 14500: BEGIN {
                   14501: 
                   14502: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14503:     unless ($readit) {
                   14504: {
                   14505:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14506:     %perlvar = (%perlvar,%{$configvars});
                   14507: }
                   14508: 
                   14509: 
1.1       albertel 14510: # ------------------------------------------------------ Read spare server file
                   14511: {
1.1172.2.96  raeburn  14512:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14513: 
                   14514:     while (my $configline=<$config>) {
                   14515:        chomp($configline);
1.284     matthew  14516:        if ($configline) {
1.784     albertel 14517: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14518: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14519: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14520:        }
                   14521:     }
1.448     albertel 14522:     close($config);
1.1       albertel 14523: }
1.11      www      14524: # ------------------------------------------------------------ Read permissions
                   14525: {
1.1172.2.96  raeburn  14526:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14527: 
                   14528:     while (my $configline=<$config>) {
1.448     albertel 14529: 	chomp($configline);
                   14530: 	if ($configline) {
                   14531: 	    my ($role,$perm)=split(/ /,$configline);
                   14532: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14533: 	}
1.11      www      14534:     }
1.448     albertel 14535:     close($config);
1.11      www      14536: }
                   14537: 
                   14538: # -------------------------------------------- Read plain texts for permissions
                   14539: {
1.1172.2.96  raeburn  14540:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14541: 
                   14542:     while (my $configline=<$config>) {
1.448     albertel 14543: 	chomp($configline);
                   14544: 	if ($configline) {
1.742     raeburn  14545: 	    my ($short,@plain)=split(/:/,$configline);
                   14546:             %{$prp{$short}} = ();
                   14547: 	    if (@plain > 0) {
                   14548:                 $prp{$short}{'std'} = $plain[0];
                   14549:                 for (my $i=1; $i<@plain; $i++) {
                   14550:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14551:                 }
                   14552:             }
1.448     albertel 14553: 	}
1.135     www      14554:     }
1.448     albertel 14555:     close($config);
1.135     www      14556: }
                   14557: 
                   14558: # ---------------------------------------------------------- Read package table
                   14559: {
1.1172.2.96  raeburn  14560:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14561: 
                   14562:     while (my $configline=<$config>) {
1.483     albertel 14563: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14564: 	chomp($configline);
                   14565: 	my ($short,$plain)=split(/:/,$configline);
                   14566: 	my ($pack,$name)=split(/\&/,$short);
                   14567: 	if ($plain ne '') {
                   14568: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14569: 	    $packagetab{$short}=$plain; 
                   14570: 	}
1.11      www      14571:     }
1.448     albertel 14572:     close($config);
1.329     matthew  14573: }
                   14574: 
1.1172.2.27  raeburn  14575: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14576: 
1.1172.2.27  raeburn  14577: &load_loncaparevs();
                   14578: 
                   14579: # ------------------------------------------------------- Read serverhostID table
                   14580: 
                   14581: &load_serverhomeIDs();
1.1074    raeburn  14582: 
1.1172.2.27  raeburn  14583: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14584: {
                   14585:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14586:     if (-e $file) {
                   14587:         my $parser = HTML::LCParser->new($file);
                   14588:         while (my $token = $parser->get_token()) {
                   14589:             if ($token->[0] eq 'S') {
                   14590:                 my $item = $token->[1];
                   14591:                 my $name = $token->[2]{'name'};
                   14592:                 my $value = $token->[2]{'value'};
                   14593:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14594:                     my $release = $parser->get_text();
                   14595:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14596:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14597:                 }
                   14598:             }
                   14599:         }
                   14600:     }
1.1073    raeburn  14601: }
                   14602: 
1.1138    raeburn  14603: # ---------------------------------------------------------- Read managers table
                   14604: {
                   14605:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14606:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14607:             while (my $configline=<$config>) {
                   14608:                 chomp($configline);
                   14609:                 next if ($configline =~ /^\#/);
                   14610:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14611:                     $managerstab{$configline} = 1;
                   14612:                 }
                   14613:             }
                   14614:             close($config);
                   14615:         }
                   14616:     }
                   14617: }
                   14618: 
1.329     matthew  14619: # ------------- set up temporary directory
                   14620: {
1.1117    foxr     14621:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14622: 
1.11      www      14623: }
                   14624: 
1.1172.2.104  raeburn  14625: # ------------- set default texengine (domain default overrides this)
                   14626: {
                   14627:     $deftex = LONCAPA::texengine();
                   14628: }
                   14629: 
1.1172.2.114  raeburn  14630: # ------------- set default minimum length for passwords for internal auth users
                   14631: {
                   14632:     $passwdmin = LONCAPA::passwd_min();
                   14633: }
                   14634: 
1.794     albertel 14635: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14636: 				'compress_threshold'=> 20_000,
                   14637:  			        });
1.185     www      14638: 
1.281     www      14639: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14640: $dumpcount=0;
1.958     www      14641: $locknum=0;
1.22      www      14642: 
1.163     harris41 14643: &logtouch();
1.672     albertel 14644: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14645: $readit=1;
1.564     albertel 14646:     {
                   14647: 	use integer;
                   14648: 	my $test=(2**32)+1;
1.568     albertel 14649: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14650: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14651:     }
1.195     www      14652: }
1.1       albertel 14653: }
1.179     www      14654: 
1.1       albertel 14655: 1;
1.191     harris41 14656: __END__
                   14657: 
1.243     albertel 14658: =pod
                   14659: 
1.191     harris41 14660: =head1 NAME
                   14661: 
1.243     albertel 14662: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14663: 
                   14664: =head1 SYNOPSIS
                   14665: 
1.243     albertel 14666: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14667: 
                   14668:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14669: 
1.243     albertel 14670: Common parameters:
                   14671: 
                   14672: =over 4
                   14673: 
                   14674: =item *
                   14675: 
                   14676: $uname : an internal username (if $cname expecting a course Id specifically)
                   14677: 
                   14678: =item *
                   14679: 
                   14680: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14681: 
                   14682: =item *
                   14683: 
                   14684: $symb : a resource instance identifier
                   14685: 
                   14686: =item *
                   14687: 
                   14688: $namespace : the name of a .db file that contains the data needed or
                   14689: being set.
                   14690: 
                   14691: =back
                   14692: 
1.394     bowersj2 14693: =head1 OVERVIEW
1.191     harris41 14694: 
1.394     bowersj2 14695: lonnet provides subroutines which interact with the
                   14696: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14697: about classes, users, and resources.
1.243     albertel 14698: 
                   14699: For many of these objects you can also use this to store data about
                   14700: them or modify them in various ways.
1.191     harris41 14701: 
1.394     bowersj2 14702: =head2 Symbs
1.191     harris41 14703: 
1.394     bowersj2 14704: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14705: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14706: map, the resource number of the resource in the map, and the URL of
                   14707: the resource itself. The latter is somewhat redundant, but might help
                   14708: if maps change.
                   14709: 
                   14710: An example is
                   14711: 
                   14712:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14713: 
                   14714: The respective map entry is
                   14715: 
                   14716:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14717:   title="Problem 2">
                   14718:  </resource>
                   14719: 
                   14720: Symbs are used by the random number generator, as well as to store and
                   14721: restore data specific to a certain instance of for example a problem.
                   14722: 
                   14723: =head2 Storing And Retrieving Data
                   14724: 
                   14725: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14726: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14727: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14728: is is the non-critical message twin of cstore. These functions are for
                   14729: handlers to store a perl hash to a user's permanent data space in an
                   14730: easy manner, and to retrieve it again on another call. It is expected
                   14731: that a handler would use this once at the beginning to retrieve data,
                   14732: and then again once at the end to send only the new data back.
                   14733: 
                   14734: The data is stored in the user's data directory on the user's
                   14735: homeserver under the ID of the course.
                   14736: 
                   14737: The hash that is returned by restore will have all of the previous
                   14738: value for all of the elements of the hash.
                   14739: 
                   14740: Example:
                   14741: 
                   14742:  #creating a hash
                   14743:  my %hash;
                   14744:  $hash{'foo'}='bar';
                   14745: 
                   14746:  #storing it
                   14747:  &Apache::lonnet::cstore(\%hash);
                   14748: 
                   14749:  #changing a value
                   14750:  $hash{'foo'}='notbar';
                   14751: 
                   14752:  #adding a new value
                   14753:  $hash{'bar'}='foo';
                   14754:  &Apache::lonnet::cstore(\%hash);
                   14755: 
                   14756:  #retrieving the hash
                   14757:  my %history=&Apache::lonnet::restore();
                   14758: 
                   14759:  #print the hash
                   14760:  foreach my $key (sort(keys(%history))) {
                   14761:    print("\%history{$key} = $history{$key}");
                   14762:  }
                   14763: 
                   14764: Will print out:
1.191     harris41 14765: 
1.394     bowersj2 14766:  %history{1:foo} = bar
                   14767:  %history{1:keys} = foo:timestamp
                   14768:  %history{1:timestamp} = 990455579
                   14769:  %history{2:bar} = foo
                   14770:  %history{2:foo} = notbar
                   14771:  %history{2:keys} = foo:bar:timestamp
                   14772:  %history{2:timestamp} = 990455580
                   14773:  %history{bar} = foo
                   14774:  %history{foo} = notbar
                   14775:  %history{timestamp} = 990455580
                   14776:  %history{version} = 2
                   14777: 
                   14778: Note that the special hash entries C<keys>, C<version> and
                   14779: C<timestamp> were added to the hash. C<version> will be equal to the
                   14780: total number of versions of the data that have been stored. The
                   14781: C<timestamp> attribute will be the UNIX time the hash was
                   14782: stored. C<keys> is available in every historical section to list which
                   14783: keys were added or changed at a specific historical revision of a
                   14784: hash.
                   14785: 
                   14786: B<Warning>: do not store the hash that restore returns directly. This
                   14787: will cause a mess since it will restore the historical keys as if the
                   14788: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14789: 
1.394     bowersj2 14790: Calling convention:
1.191     harris41 14791: 
1.1172.2.27  raeburn  14792:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14793:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14794: 
1.394     bowersj2 14795: For more detailed information, see lonnet specific documentation.
1.191     harris41 14796: 
1.394     bowersj2 14797: =head1 RETURN MESSAGES
1.191     harris41 14798: 
1.394     bowersj2 14799: =over 4
1.191     harris41 14800: 
1.394     bowersj2 14801: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14802: 
1.394     bowersj2 14803: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14804: when the connection is brought back up
1.191     harris41 14805: 
1.394     bowersj2 14806: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14807: for later delivery
1.191     harris41 14808: 
1.967     bisitz   14809: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14810: 
1.394     bowersj2 14811: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14812: that was requested
1.191     harris41 14813: 
1.243     albertel 14814: =back
1.191     harris41 14815: 
1.243     albertel 14816: =head1 PUBLIC SUBROUTINES
1.191     harris41 14817: 
1.243     albertel 14818: =head2 Session Environment Functions
1.191     harris41 14819: 
1.243     albertel 14820: =over 4
1.191     harris41 14821: 
1.394     bowersj2 14822: =item * 
                   14823: X<appenv()>
1.949     raeburn  14824: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14825: the user envirnoment file, and will be restored for each access this
1.620     albertel 14826: user makes during this session, also modifies the %env for the current
1.949     raeburn  14827: process. Optional rolesarrayref - if defined contains a reference to an array
                   14828: of roles which are exempt from the restriction on modifying user.role entries 
                   14829: in the user's environment.db and in %env.    
1.191     harris41 14830: 
                   14831: =item *
1.394     bowersj2 14832: X<delenv()>
1.987     raeburn  14833: B<delenv($delthis,$regexp)>: removes all items from the session
                   14834: environment file that begin with $delthis. If the 
                   14835: optional second arg - $regexp - is true, $delthis is treated as a 
                   14836: regular expression, otherwise \Q$delthis\E is used. 
                   14837: The values are also deleted from the current processes %env.
1.191     harris41 14838: 
1.795     albertel 14839: =item * get_env_multiple($name) 
                   14840: 
                   14841: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14842: values may be defined and end up as an array ref.
                   14843: 
                   14844: returns an array of values
                   14845: 
1.243     albertel 14846: =back
                   14847: 
                   14848: =head2 User Information
1.191     harris41 14849: 
1.243     albertel 14850: =over 4
1.191     harris41 14851: 
                   14852: =item *
1.394     bowersj2 14853: X<queryauthenticate()>
                   14854: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14855: authentication scheme
                   14856: 
                   14857: =item *
1.394     bowersj2 14858: X<authenticate()>
1.1073    raeburn  14859: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14860: authenticate user from domain's lib servers (first use the current
                   14861: one). C<$upass> should be the users password.
1.1073    raeburn  14862: $checkdefauth is optional (value is 1 if a check should be made to
                   14863:    authenticate user using default authentication method, and allow
                   14864:    account creation if username does not have account in the domain).
                   14865: $clientcancheckhost is optional (value is 1 if checking whether the
                   14866:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14867: 
                   14868: =item *
1.394     bowersj2 14869: X<homeserver()>
                   14870: B<homeserver($uname,$udom)>: find the server which has
                   14871: the user's directory and files (there must be only one), this caches
                   14872: the answer, and also caches if there is a borken connection.
1.191     harris41 14873: 
                   14874: =item *
1.394     bowersj2 14875: X<idget()>
                   14876: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14877: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14878: username, and only 1 username per ID in a specific domain) (returns
                   14879: hash: id=>name,id=>name)
1.191     harris41 14880: 
                   14881: =item *
1.394     bowersj2 14882: X<idrget()>
                   14883: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14884: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14885: 
                   14886: =item *
1.394     bowersj2 14887: X<idput()>
                   14888: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14889: 
                   14890: =item *
1.394     bowersj2 14891: X<rolesinit()>
1.1169    droeschl 14892: B<rolesinit($udom,$username)>: get user privileges.
                   14893: returns user role, first access and timer interval hashes
1.243     albertel 14894: 
                   14895: =item *
1.1171    droeschl 14896: X<privileged()>
                   14897: B<privileged($username,$domain)>: returns a true if user has a
                   14898: privileged and active role (i.e. su or dc), false otherwise.
                   14899: 
                   14900: =item *
1.551     albertel 14901: X<getsection()>
                   14902: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14903: course $cname, return section name/number or '' for "not in course"
                   14904: and '-1' for "no section"
                   14905: 
                   14906: =item *
1.394     bowersj2 14907: X<userenvironment()>
                   14908: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14909: passed in @what from the requested user's environment, returns a hash
                   14910: 
1.858     raeburn  14911: =item * 
                   14912: X<userlog_query()>
1.859     albertel 14913: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14914: activity.log file. %filters defines filters applied when parsing the
                   14915: log file. These can be start or end timestamps, or the type of action
                   14916: - log to look for Login or Logout events, check for Checkin or
                   14917: Checkout, role for role selection. The response is in the form
                   14918: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14919: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14920: 
1.243     albertel 14921: =back
                   14922: 
                   14923: =head2 User Roles
                   14924: 
                   14925: =over 4
                   14926: 
                   14927: =item *
                   14928: 
1.1172.2.65  raeburn  14929: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14930: returns codes for allowed actions.
                   14931: 
                   14932: The first argument is required, all others are optional.
                   14933: 
                   14934: $priv is the privilege being checked.
                   14935: $uri contains additional information about what is being checked for access (e.g.,
                   14936: URL, course ID etc.).
                   14937: $symb is the unique resource instance identifier in a course; if needed,
                   14938: but not provided, it will be retrieved via a call to &symbread().
                   14939: $role is the role for which a priv is being checked (only used if priv is evb).
                   14940: $clientip is the user's IP address (only used when checking for access to portfolio
                   14941: files).
                   14942: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14943: prevents recursive calls to &allowed.
                   14944: 
1.243     albertel 14945:  F: full access
                   14946:  U,I,K: authentication modes (cxx only)
                   14947:  '': forbidden
                   14948:  1: user needs to choose course
                   14949:  2: browse allowed
1.766     albertel 14950:  A: passphrase authentication needed
1.1172.2.65  raeburn  14951:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14952: 
                   14953: =item *
                   14954: 
1.1172.2.13  raeburn  14955: constructaccess($url,$setpriv) : check for access to construction space URL
                   14956: 
                   14957: See if the owner domain and name in the URL match those in the
                   14958: expected environment.  If so, return three element list
                   14959: ($ownername,$ownerdomain,$ownerhome).
                   14960: 
                   14961: Otherwise return the null string.
                   14962: 
                   14963: If second argument 'setpriv' is true, it assigns the privileges,
                   14964: and returns the same three element list, unless the owner has
                   14965: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14966: in which case the null string is returned.
                   14967: 
                   14968: =item *
                   14969: 
1.1172.2.84  raeburn  14970: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14971: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14972: for system, domain, and course level. $uname and $udom are optional (current
                   14973: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14974: 
                   14975: =item *
                   14976: 
1.988     raeburn  14977: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14978: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14979: $type is Course (default) or Community.
1.988     raeburn  14980: If $forcedefault evaluates to true, text returned will be default 
                   14981: text for $type. Otherwise, if this is a course, the text returned 
                   14982: will be a custom name for the role (if defined in the course's 
                   14983: environment).  If no custom name is defined the default is returned.
                   14984:    
1.832     raeburn  14985: =item *
                   14986: 
1.1172.2.23  raeburn  14987: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14988: All arguments are optional. Returns a hash of a roles, either for
                   14989: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14990: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14991: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14992: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14993: For each key, value is set to colon-separated start and end times for
                   14994: the role.  If no username and domain are specified, will default to
1.934     raeburn  14995: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14996: of role statuses (active, future or previous), roles 
                   14997: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14998: to restrict the list of roles reported. If no array ref is 
                   14999: provided for types, will default to return only active roles.
1.834     albertel 15000: 
1.1172.2.13  raeburn  15001: =item *
                   15002: 
                   15003: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15004: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15005: 
                   15006: Additional optional arguments are: $type (if role checking is to be restricted
                   15007: to certain user status types -- previous (expired roles), active (currently
                   15008: available roles) or future (roles available in the future), and
                   15009: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15010: have active Domain Coordinator role in course's domain or in additional
                   15011: domains (specified in 'Domains to check for privileged users' in course
                   15012: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15013: 
                   15014: =item *
                   15015: 
                   15016: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15017: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15018: $possdomains and $possroles are optional array refs -- to domains to check and
                   15019: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15020: users' roles.db to check for a dc or su role in any domain. This can be
                   15021: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15022: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15023: this then allows &privileged_by_domain() to be used, which caches the identity
                   15024: of privileged users, eliminating the need for repeated calls to &dump().
                   15025: 
                   15026: =item *
                   15027: 
                   15028: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15029: where the outer hash keys are domains specified in the $possdomains array ref,
                   15030: next inner hash keys are privileged roles specified in the $roles array ref,
                   15031: and the innermost hash contains key = value pairs for username:domain = end:start
                   15032: for active or future "privileged" users with that role in that domain. To avoid
                   15033: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15034: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15035: 
1.243     albertel 15036: =back
                   15037: 
                   15038: =head2 User Modification
                   15039: 
                   15040: =over 4
                   15041: 
                   15042: =item *
                   15043: 
1.957     raeburn  15044: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15045: user for the level given by URL.  Optional start and end dates (leave empty
                   15046: string or zero for "no date")
1.191     harris41 15047: 
                   15048: =item *
                   15049: 
1.243     albertel 15050: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15051: change a users, password, possible return values are: ok,
                   15052: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15053: refused
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.243     albertel 15057: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15058: 
                   15059: =item *
                   15060: 
1.1058    raeburn  15061: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15062:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15063: 
                   15064: will update user information (firstname,middlename,lastname,generation,
                   15065: permanentemail), and if forceid is true, student/employee ID also.
                   15066: A user's institutional affiliation(s) can also be updated.
                   15067: User information fields will not be overwritten with empty entries 
                   15068: unless the field is included in the $candelete array reference.
                   15069: This array is included when a single user is modified via "Manage Users",
                   15070: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15071: 
                   15072: =item *
                   15073: 
1.286     matthew  15074: modifystudent
                   15075: 
1.957     raeburn  15076: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15077: The course id is resolved based on the current user's environment.  
                   15078: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15079: associated with a course.
                   15080: 
1.297     matthew  15081: This call is essentially a wrapper for lonnet::modifyuser and
                   15082: lonnet::modify_student_enrollment
1.286     matthew  15083: 
                   15084: Inputs: 
                   15085: 
                   15086: =over 4
                   15087: 
1.957     raeburn  15088: =item B<$udom> Student's loncapa domain
1.286     matthew  15089: 
1.957     raeburn  15090: =item B<$uname> Student's loncapa login name
1.286     matthew  15091: 
1.964     bisitz   15092: =item B<$uid> Student/Employee ID
1.286     matthew  15093: 
1.957     raeburn  15094: =item B<$umode> Student's authentication mode
1.286     matthew  15095: 
1.957     raeburn  15096: =item B<$upass> Student's password
1.286     matthew  15097: 
1.957     raeburn  15098: =item B<$first> Student's first name
1.286     matthew  15099: 
1.957     raeburn  15100: =item B<$middle> Student's middle name
1.286     matthew  15101: 
1.957     raeburn  15102: =item B<$last> Student's last name
1.286     matthew  15103: 
1.957     raeburn  15104: =item B<$gene> Student's generation
1.286     matthew  15105: 
1.957     raeburn  15106: =item B<$usec> Student's section in course
1.286     matthew  15107: 
                   15108: =item B<$end> Unix time of the roles expiration
                   15109: 
                   15110: =item B<$start> Unix time of the roles start date
                   15111: 
                   15112: =item B<$forceid> If defined, allow $uid to be changed
                   15113: 
                   15114: =item B<$desiredhome> server to use as home server for student
                   15115: 
1.957     raeburn  15116: =item B<$email> Student's permanent e-mail address
                   15117: 
                   15118: =item B<$type> Type of enrollment (auto or manual)
                   15119: 
1.963     raeburn  15120: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15121: 
                   15122: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15123: 
1.963     raeburn  15124: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15125: 
1.963     raeburn  15126: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15127: 
1.1172.2.19  raeburn  15128: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15129: 
                   15130: =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  15131: 
1.286     matthew  15132: =back
1.297     matthew  15133: 
                   15134: =item *
                   15135: 
                   15136: modify_student_enrollment
                   15137: 
1.1172.2.31  raeburn  15138: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15139: 'role.request.course' must be defined for this function to proceed.
                   15140: 
                   15141: Inputs:
                   15142: 
                   15143: =over 4
                   15144: 
1.1172.2.31  raeburn  15145: =item $udom, student's domain
1.297     matthew  15146: 
1.1172.2.31  raeburn  15147: =item $uname, student's name
1.297     matthew  15148: 
1.1172.2.31  raeburn  15149: =item $uid, student's user id
1.297     matthew  15150: 
1.1172.2.31  raeburn  15151: =item $first, student's first name
1.297     matthew  15152: 
                   15153: =item $middle
                   15154: 
                   15155: =item $last
                   15156: 
                   15157: =item $gene
                   15158: 
                   15159: =item $usec
                   15160: 
                   15161: =item $end
                   15162: 
                   15163: =item $start
                   15164: 
1.957     raeburn  15165: =item $type
                   15166: 
                   15167: =item $locktype
                   15168: 
                   15169: =item $cid
                   15170: 
                   15171: =item $selfenroll
                   15172: 
                   15173: =item $context
                   15174: 
1.1172.2.19  raeburn  15175: =item $credits, number of credits student will earn from this class
                   15176: 
1.1172.2.76  raeburn  15177: =item $instsec, institutional course section code for student
                   15178: 
1.297     matthew  15179: =back
                   15180: 
1.191     harris41 15181: 
                   15182: =item *
                   15183: 
1.243     albertel 15184: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15185: custom role; give a custom role to a user for the level given by URL.  Specify
                   15186: name and domain of role author, and role name
1.191     harris41 15187: 
                   15188: =item *
                   15189: 
1.243     albertel 15190: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15191: 
                   15192: =item *
                   15193: 
1.243     albertel 15194: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15195: 
                   15196: =back
                   15197: 
                   15198: =head2 Course Infomation
                   15199: 
                   15200: =over 4
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.1118    foxr     15204: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15205: specified course id, including all environment settings for the
                   15206: course, the description of the course will be in the hash under the
                   15207: key 'description'
1.191     harris41 15208: 
1.1118    foxr     15209: $options is an optional parameter that if supplied is a hash reference that controls
                   15210: what how this function works.  It has the following key/values:
                   15211: 
                   15212: =over 4
                   15213: 
                   15214: =item freshen_cache
                   15215: 
                   15216: If defined, and the environment cache for the course is valid, it is 
                   15217: returned in the returned hash.
                   15218: 
                   15219: =item one_time
                   15220: 
                   15221: If defined, the last cache time is set to _now_
                   15222: 
                   15223: =item user
                   15224: 
                   15225: If defined, the supplied username is used instead of the current user.
                   15226: 
                   15227: 
                   15228: =back
                   15229: 
1.191     harris41 15230: =item *
                   15231: 
1.624     albertel 15232: resdata($name,$domain,$type,@which) : request for current parameter
                   15233: setting for a specific $type, where $type is either 'course' or 'user',
                   15234: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15235: answers for 10 minutes.
1.243     albertel 15236: 
1.877     foxr     15237: =item *
                   15238: 
                   15239: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15240: data base, returning a hash that is keyed by the resource name and has
                   15241: values that are the resource value.  I believe that the timestamps and
                   15242: versions are also returned.
                   15243: 
1.1172.2.31  raeburn  15244: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15245: supplemental content area. This routine caches the number of files for
                   15246: 10 minutes.
                   15247: 
1.243     albertel 15248: =back
                   15249: 
                   15250: =head2 Course Modification
                   15251: 
                   15252: =over 4
1.191     harris41 15253: 
                   15254: =item *
                   15255: 
1.243     albertel 15256: writecoursepref($courseid,%prefs) : write preferences (environment
                   15257: database) for a course
1.191     harris41 15258: 
                   15259: =item *
                   15260: 
1.1011    raeburn  15261: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15262: 
                   15263: =item *
                   15264: 
1.1038    raeburn  15265: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15266: 
1.1167    droeschl 15267: =item *
                   15268: 
                   15269: is_course($courseid), is_course($cdom, $cnum)
                   15270: 
                   15271: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15272: two component version $cdom, $cnum. It checks if the specified course exists.
                   15273: 
                   15274: Returns:
                   15275:     undef if the course doesn't exist, otherwise
                   15276:     in scalar context the combined courseid.
                   15277:     in list context the two components of the course identifier, domain and 
                   15278:     courseid.    
                   15279: 
1.243     albertel 15280: =back
                   15281: 
1.1172.2.109  raeburn  15282: =head2 Bubblesheet Configuration
                   15283: 
                   15284: =over 4
                   15285: 
                   15286: =item *
                   15287: 
                   15288: get_scantron_config($which)
                   15289: 
                   15290: $which - the name of the configuration to parse from the file.
                   15291: 
                   15292: Parses and returns the bubblesheet configuration line selected as a
                   15293: hash of configuration file fields.
                   15294: 
                   15295: 
                   15296: Returns:
                   15297:     If the named configuration is not in the file, an empty
                   15298:     hash is returned.
                   15299: 
                   15300:     a hash with the fields
                   15301:       name         - internal name for the this configuration setup
                   15302:       description  - text to display to operator that describes this config
                   15303:       CODElocation - if 0 or the string 'none'
                   15304:                           - no CODE exists for this config
                   15305:                      if -1 || the string 'letter'
                   15306:                           - a CODE exists for this config and is
                   15307:                             a string of letters
                   15308:                      Unsupported value (but planned for future support)
                   15309:                           if a positive integer
                   15310:                                - The CODE exists as the first n items from
                   15311:                                  the question section of the form
                   15312:                           if the string 'number'
                   15313:                                - The CODE exists for this config and is
                   15314:                                  a string of numbers
                   15315:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15316:                      the CODE starts
                   15317:       CODElength  - length of the CODE
                   15318:       IDstart     - column where the student/employee ID starts
                   15319:       IDlength    - length of the student/employee ID info
                   15320:       Qstart      - column where the information from the bubbled
                   15321:                     'questions' start
                   15322:       Qlength     - number of columns comprising a single bubble line from
                   15323:                     the sheet. (usually either 1 or 10)
                   15324:       Qon         - either a single character representing the character used
                   15325:                     to signal a bubble was chosen in the positional setup, or
                   15326:                     the string 'letter' if the letter of the chosen bubble is
                   15327:                     in the final, or 'number' if a number representing the
                   15328:                     chosen bubble is in the file (1->A 0->J)
                   15329:       Qoff        - the character used to represent that a bubble was
                   15330:                     left blank
                   15331:       PaperID     - if the scanning process generates a unique number for each
                   15332:                     sheet scanned the column that this ID number starts in
                   15333:       PaperIDlength - number of columns that comprise the unique ID number
                   15334:                       for the sheet of paper
                   15335:       FirstName   - column that the first name starts in
                   15336:       FirstNameLength - number of columns that the first name spans
                   15337:       LastName    - column that the last name starts in
                   15338:       LastNameLength - number of columns that the last name spans
                   15339:       BubblesPerRow - number of bubbles available in each row used to
                   15340:                       bubble an answer. (If not specified, 10 assumed).
                   15341: 
                   15342: 
                   15343: =item *
                   15344: 
                   15345: get_scantronformat_file($cdom)
                   15346: 
                   15347: $cdom - the course's domain (optional); if not supplied, uses
                   15348: domain for current $env{'request.course.id'}.
                   15349: 
                   15350: Returns an array containing lines from the scantron format file for
                   15351: the domain of the course.
                   15352: 
                   15353: If a url for a custom.tab file is listed in domain's configuration.db,
                   15354: lines are from this file.
                   15355: 
                   15356: Otherwise, if a default.tab has been published in RES space by the
                   15357: domainconfig user, lines are from this file.
                   15358: 
                   15359: Otherwise, fall back to getting lines from the legacy file on the
                   15360: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15361: 
                   15362: =back
                   15363: 
1.243     albertel 15364: =head2 Resource Subroutines
                   15365: 
                   15366: =over 4
1.191     harris41 15367: 
                   15368: =item *
                   15369: 
1.243     albertel 15370: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15371: 
                   15372: =item *
                   15373: 
1.243     albertel 15374: repcopy($filename) : subscribes to the requested file, and attempts to
                   15375: replicate from the owning library server, Might return
1.607     raeburn  15376: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15377: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15378: resource. Expects the local filesystem pathname
                   15379: (/home/httpd/html/res/....)
                   15380: 
                   15381: =back
                   15382: 
                   15383: =head2 Resource Information
                   15384: 
                   15385: =over 4
1.191     harris41 15386: 
                   15387: =item *
                   15388: 
1.1172.2.28  raeburn  15389: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15390: and returns the value of a variety of different possible values,
                   15391: $varname should be a request string, and the other parameters can be
                   15392: used to specify who and what one is asking about. Ordinarily, $cid 
                   15393: does not need to be specified, as it is retrived from 
                   15394: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15395: within lonuserstate::loadmap() when initializing a course, before
                   15396: $env{'request.course.id'} has been set, so it needs to be provided
                   15397: in that one case.
1.243     albertel 15398: 
                   15399: Possible values for $varname are environment.lastname (or other item
                   15400: from the envirnment hash), user.name (or someother aspect about the
                   15401: user), resource.0.maxtries (or some other part and parameter of a
                   15402: resource)
1.204     albertel 15403: 
                   15404: =item *
                   15405: 
1.243     albertel 15406: directcondval($number) : get current value of a condition; reads from a state
                   15407: string
1.204     albertel 15408: 
                   15409: =item *
                   15410: 
1.243     albertel 15411: condval($condidx) : value of condition index based on state
1.204     albertel 15412: 
                   15413: =item *
                   15414: 
1.243     albertel 15415: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15416: resource's metadata, $what should be either a specific key, or either
                   15417: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15418: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15419: 
                   15420: this function automatically caches all requests
1.191     harris41 15421: 
                   15422: =item *
                   15423: 
1.243     albertel 15424: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15425: network of library servers; returns file handle of where SQL and regex results
                   15426: will be stored for query
1.191     harris41 15427: 
                   15428: =item *
                   15429: 
1.1172.2.66  raeburn  15430: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15431: return symbolic list entry (all arguments optional).
                   15432: 
                   15433: Args: filename is the filename (including path) for the file for which a symb
                   15434: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15435: to check access status if more than one resource was found in the bighash
                   15436: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15437: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15438: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15439: cause possible symbs to be checked to determine if they are subject to content
                   15440: blocking, if so they will not be included as possible symbs; possibles is a
                   15441: ref to a hash, which, as a side effect, will be populated with all possible
                   15442: symbs (content blocking not tested).
                   15443: 
1.243     albertel 15444: returns the data handle
1.191     harris41 15445: 
                   15446: =item *
                   15447: 
1.1172.2.17  raeburn  15448: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15449: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15450: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15451: on failure, user must be in a course, as it assumes the existence of
                   15452: the course initial hash, and uses $env('request.course.id'}.  The third
                   15453: arg is an optional reference to a scalar.  If this arg is passed in the
                   15454: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15455: encrypted; otherwise it will be null.
1.243     albertel 15456: 
1.191     harris41 15457: =item *
                   15458: 
1.243     albertel 15459: symbclean($symb) : removes versions numbers from a symb, returns the
                   15460: cleaned symb
1.191     harris41 15461: 
                   15462: =item *
                   15463: 
1.243     albertel 15464: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15465: course map, user must be in a course for it to work.
1.191     harris41 15466: 
                   15467: =item *
                   15468: 
1.243     albertel 15469: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15470: 
                   15471: =item *
                   15472: 
1.243     albertel 15473: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15474: a random seed, all arguments are optional, if they aren't sent it uses the
                   15475: environment to derive them. Note: if symb isn't sent and it can't get one
                   15476: from &symbread it will use the current time as its return value
1.191     harris41 15477: 
                   15478: =item *
                   15479: 
1.243     albertel 15480: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15481: unfakeable, receipt
1.191     harris41 15482: 
                   15483: =item *
                   15484: 
1.620     albertel 15485: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15486: 
                   15487: =item *
                   15488: 
1.243     albertel 15489: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15490: 
                   15491: =item *
                   15492: 
1.243     albertel 15493: 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 15494: 
                   15495: =item *
                   15496: 
1.243     albertel 15497: 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 15498: 
                   15499: =item *
                   15500: 
1.243     albertel 15501: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15502: 
                   15503: =item *
                   15504: 
1.243     albertel 15505: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15506: forcing spreadsheet to reevaluate the resource scores next time.
                   15507: 
1.1172.2.13  raeburn  15508: =item *
                   15509: 
                   15510: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15511: when viewing in course context.
                   15512: 
                   15513:  input: six args -- filename (decluttered), course number, course domain,
                   15514:                     url, symb (if registered) and group (if this is a
                   15515:                     group item -- e.g., bulletin board, group page etc.).
                   15516: 
                   15517:  output: array of five scalars --
                   15518:          $cfile -- url for file editing if editable on current server
                   15519:          $home -- homeserver of resource (i.e., for author if published,
                   15520:                                           or course if uploaded.).
                   15521:          $switchserver --  1 if server switch will be needed.
                   15522:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15523:          $forceview -- 1 if icon/link should be to go to view mode
                   15524: 
                   15525: =item *
                   15526: 
                   15527: is_course_upload($file,$cnum,$cdom)
                   15528: 
                   15529: Used in course context to determine if current file was uploaded to
                   15530: the course (i.e., would be found in /userfiles/docs on the course's
                   15531: homeserver.
                   15532: 
                   15533:   input: 3 args -- filename (decluttered), course number and course domain.
                   15534:   output: boolean -- 1 if file was uploaded.
                   15535: 
1.243     albertel 15536: =back
                   15537: 
                   15538: =head2 Storing/Retreiving Data
                   15539: 
                   15540: =over 4
1.191     harris41 15541: 
                   15542: =item *
                   15543: 
1.1172.2.64  raeburn  15544: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15545: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15546: the remaining args aren't required and if they aren't passed or are '' they will
                   15547: be derived from the env (with the exception of $laststore, which is an
                   15548: optional arg used when a user's submission is stored in grading).
                   15549: $laststore is $version=$timestamp, where $version is the most recent version
                   15550: number retrieved for the corresponding $symb in the $namespace db file, and
                   15551: $timestamp is the timestamp for that transaction (UNIX time).
                   15552: $laststore is currently only passed when cstore() is called by
                   15553: structuretags::finalize_storage().
1.191     harris41 15554: 
                   15555: =item *
                   15556: 
1.1172.2.64  raeburn  15557: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15558: but uses critical subroutine
1.191     harris41 15559: 
                   15560: =item *
                   15561: 
1.243     albertel 15562: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15563: all args are optional
1.191     harris41 15564: 
                   15565: =item *
                   15566: 
1.717     albertel 15567: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15568: dumps the complete (or key matching regexp) namespace into a hash
                   15569: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15570: normally &store()ed into
                   15571: 
                   15572: $range should be either an integer '100' (give me the first 100
                   15573:                                            matching records)
                   15574:               or be  two integers sperated by a - with no spaces
                   15575:                  '30-50' (give me the 30th through the 50th matching
                   15576:                           records)
                   15577: 
                   15578: 
                   15579: =item *
                   15580: 
1.1172.2.59  raeburn  15581: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15582: replaces a &store() version of data with a replacement set of data
                   15583: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15584: reference. If $tolog is true, the transaction is logged in the courselog
                   15585: with an action=PUTSTORE.
1.717     albertel 15586: 
                   15587: =item *
                   15588: 
1.243     albertel 15589: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15590: works very similar to store/cstore, but all data is stored in a
                   15591: temporary location and can be reset using tmpreset, $storehash should
                   15592: be a hash reference, returns nothing on success
1.191     harris41 15593: 
                   15594: =item *
                   15595: 
1.243     albertel 15596: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15597: similar to restore, but all data is stored in a temporary location and
                   15598: can be reset using tmpreset. Returns a hash of values on success,
                   15599: error string otherwise.
1.191     harris41 15600: 
                   15601: =item *
                   15602: 
1.243     albertel 15603: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15604: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15605: 
                   15606: =item *
                   15607: 
1.243     albertel 15608: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15609: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15610: 
                   15611: =item *
                   15612: 
1.243     albertel 15613: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15614: namesp ($udom and $uname are optional)
1.191     harris41 15615: 
                   15616: =item *
                   15617: 
1.702     albertel 15618: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15619: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15620: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15621: 
1.702     albertel 15622: $range should be either an integer '100' (give me the first 100
                   15623:                                            matching records)
                   15624:               or be  two integers sperated by a - with no spaces
                   15625:                  '30-50' (give me the 30th through the 50th matching
                   15626:                           records)
1.449     matthew  15627: =item *
                   15628: 
                   15629: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15630: $store can be a scalar, an array reference, or if the amount to be 
                   15631: incremented is > 1, a hash reference.
                   15632: 
                   15633: ($udom and $uname are optional)
1.191     harris41 15634: 
                   15635: =item *
                   15636: 
1.243     albertel 15637: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15638: ($udom and $uname are optional)
1.191     harris41 15639: 
                   15640: =item *
                   15641: 
1.243     albertel 15642: cput($namespace,$storehash,$udom,$uname) : critical put
                   15643: ($udom and $uname are optional)
1.191     harris41 15644: 
                   15645: =item *
                   15646: 
1.748     albertel 15647: newput($namespace,$storehash,$udom,$uname) :
                   15648: 
                   15649: Attempts to store the items in the $storehash, but only if they don't
                   15650: currently exist, if this succeeds you can be certain that you have 
                   15651: successfully created a new key value pair in the $namespace db.
                   15652: 
                   15653: 
                   15654: Args:
                   15655:  $namespace: name of database to store values to
                   15656:  $storehash: hashref to store to the db
                   15657:  $udom: (optional) domain of user containing the db
                   15658:  $uname: (optional) name of user caontaining the db
                   15659: 
                   15660: Returns:
                   15661:  'ok' -> succeeded in storing all keys of $storehash
                   15662:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15663:                         least <key> already existed in the db (other
                   15664:                         requested keys may also already exist)
1.967     bisitz   15665:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15666:  'con_lost' -> unable to contact request server
                   15667:  'refused' -> action was not allowed by remote machine
                   15668: 
                   15669: 
                   15670: =item *
                   15671: 
1.243     albertel 15672: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15673: reference filled in from namesp (encrypts the return communication)
                   15674: ($udom and $uname are optional)
1.191     harris41 15675: 
                   15676: =item *
                   15677: 
1.243     albertel 15678: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15679: critical subroutine
                   15680: 
1.806     raeburn  15681: =item *
                   15682: 
1.860     raeburn  15683: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15684: array reference filled in from namespace found in domain level on either
                   15685: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15686: 
                   15687: =item *
                   15688: 
1.860     raeburn  15689: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15690: domain level either on specified domain server ($uhome) or primary domain 
                   15691: server ($udom and $uhome are optional)
1.806     raeburn  15692: 
1.943     raeburn  15693: =item * 
                   15694: 
1.1172.2.35  raeburn  15695: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15696: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15697: the target domain.
                   15698: 
                   15699: May also include additional key => value pairs for the following groups:
                   15700: 
                   15701: =over
                   15702: 
                   15703: =item
                   15704: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15705: 
                   15706: =over
                   15707: 
                   15708: =item defaultquota, authorquota
                   15709: 
                   15710: =back
                   15711: 
                   15712: =item
                   15713: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15714: portfolio for users).
                   15715: 
                   15716: =over
                   15717: 
                   15718: =item
                   15719: aboutme, blog, webdav, portfolio
                   15720: 
                   15721: =back
                   15722: 
                   15723: =item
                   15724: requestcourses: ability to request courses, and how requests are processed.
                   15725: 
                   15726: =over
                   15727: 
                   15728: =item
1.1172.2.37  raeburn  15729: official, unofficial, community, textbook
1.1172.2.35  raeburn  15730: 
                   15731: =back
                   15732: 
                   15733: =item
                   15734: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15735: 
                   15736: =over
                   15737: 
                   15738: =item
1.1172.2.44  raeburn  15739: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15740: 
                   15741: =back
                   15742: 
                   15743: =item
                   15744: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15745: for course's uploaded content.
                   15746: 
                   15747: =over
                   15748: 
                   15749: =item
1.1172.2.68  raeburn  15750: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15751: communityquota, textbookquota
1.1172.2.35  raeburn  15752: 
                   15753: =back
                   15754: 
                   15755: =item
                   15756: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15757: on your servers.
                   15758: 
                   15759: =over
                   15760: 
                   15761: =item
                   15762: remotesessions, hostedsessions
                   15763: 
                   15764: =back
                   15765: 
                   15766: =back
                   15767: 
                   15768: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15769: utility to create a configuration.db file on a domain's primary library server
                   15770: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15771: -- corresponding values are authentication type (internal, krb4, krb5,
                   15772: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15773: will be available. Values are retrieved from cache (if current), unless the
                   15774: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15775: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15776: 
                   15777: Typical usage:
1.943     raeburn  15778: 
1.1172.2.35  raeburn  15779: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15780: 
1.243     albertel 15781: =back
                   15782: 
                   15783: =head2 Network Status Functions
                   15784: 
                   15785: =over 4
1.191     harris41 15786: 
                   15787: =item *
                   15788: 
1.1137    raeburn  15789: dirlist() : return directory list based on URI (first arg).
                   15790: 
                   15791: Inputs: 1 required, 5 optional.
                   15792: 
                   15793: =over
                   15794: 
                   15795: =item 
                   15796: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15797: 
                   15798: =item
                   15799: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15800: 
                   15801: =item
                   15802: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15803: 
                   15804: =item
                   15805: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15806: 
                   15807: =item
                   15808: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15809: 
                   15810: =item 
                   15811: $alternateRoot - path to prepend in place of path from $uri.
                   15812: 
                   15813: =back
                   15814: 
                   15815: Returns: Array of up to two items.
                   15816: 
                   15817: =over
                   15818: 
                   15819: a reference to an array of files/subdirectories
                   15820: 
                   15821: =over
                   15822: 
                   15823: Each element in the array of files/subdirectories is a & separated list of
                   15824: item name and the result of running stat on the item.  If dirlist was requested
                   15825: for a file instead of a directory, the item name will be ''. For a directory 
                   15826: listing, if the item is a metadata file, the element will end &N&M 
                   15827: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15828: default copyright set (1).  
                   15829: 
                   15830: =back
                   15831: 
                   15832: a scalar containing error condition (if encountered).
                   15833: 
                   15834: =over
                   15835: 
                   15836: =item 
                   15837: no_host (no homeserver identified for $username:$domain).
                   15838: 
                   15839: =item 
                   15840: no_such_host (server contacted for listing not identified as valid host).
                   15841: 
                   15842: =item 
                   15843: con_lost (connection to remote server failed).
                   15844: 
                   15845: =item 
                   15846: refused (invalid $username:$domain received on lond side).
                   15847: 
                   15848: =item 
                   15849: no_such_dir (directory at specified path on lond side does not exist). 
                   15850: 
                   15851: =item 
                   15852: empty (directory at specified path on lond side is empty).
                   15853: 
                   15854: =over
                   15855: 
                   15856: This is currently not encountered because the &ls3, &ls2, 
                   15857: &ls (_handler) routines on the lond side do not filter out
                   15858: . and .. from a directory listing. 
                   15859: 
                   15860: =back
                   15861: 
                   15862: =back
                   15863: 
                   15864: =back
1.191     harris41 15865: 
                   15866: =item *
                   15867: 
1.243     albertel 15868: spareserver() : find server with least workload from spare.tab
                   15869: 
1.986     foxr     15870: 
                   15871: =item *
                   15872: 
                   15873: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15874: if there is no corresponding loncapa host.
                   15875: 
1.243     albertel 15876: =back
                   15877: 
1.986     foxr     15878: 
1.243     albertel 15879: =head2 Apache Request
                   15880: 
                   15881: =over 4
1.191     harris41 15882: 
                   15883: =item *
                   15884: 
1.243     albertel 15885: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15886: localhost, posts hash
                   15887: 
                   15888: =back
                   15889: 
                   15890: =head2 Data to String to Data
                   15891: 
                   15892: =over 4
1.191     harris41 15893: 
                   15894: =item *
                   15895: 
1.243     albertel 15896: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15897: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15898: 
                   15899: =item *
                   15900: 
1.243     albertel 15901: hashref2str($hashref) : convert a hashref into a string complete with
                   15902: escaping and '=' and '&' separators, supports elements that are
                   15903: arrayrefs and hashrefs
1.191     harris41 15904: 
                   15905: =item *
                   15906: 
1.243     albertel 15907: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15908: with escaping and '&' separators, supports elements that are arrayrefs
                   15909: and hashrefs
1.191     harris41 15910: 
                   15911: =item *
                   15912: 
1.243     albertel 15913: str2hash($string) : convert string to hash using unescaping and
                   15914: splitting on '=' and '&', supports elements that are arrayrefs and
                   15915: hashrefs
1.191     harris41 15916: 
                   15917: =item *
                   15918: 
1.243     albertel 15919: str2array($string) : convert string to hash using unescaping and
                   15920: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15921: 
                   15922: =back
                   15923: 
                   15924: =head2 Logging Routines
                   15925: 
                   15926: 
                   15927: These routines allow one to make log messages in the lonnet.log and
                   15928: lonnet.perm logfiles.
1.191     harris41 15929: 
1.1119    foxr     15930: =over 4
                   15931: 
1.191     harris41 15932: =item *
                   15933: 
1.243     albertel 15934: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15935: 
                   15936: =item *
                   15937: 
1.243     albertel 15938: logthis() : append message to the normal lonnet.log file, it gets
                   15939: preiodically rolled over and deleted.
1.191     harris41 15940: 
                   15941: =item *
                   15942: 
1.243     albertel 15943: logperm() : append a permanent message to lonnet.perm.log, this log
                   15944: file never gets deleted by any automated portion of the system, only
                   15945: messages of critical importance should go in here.
                   15946: 
1.1119    foxr     15947: 
1.243     albertel 15948: =back
                   15949: 
                   15950: =head2 General File Helper Routines
                   15951: 
                   15952: =over 4
1.191     harris41 15953: 
                   15954: =item *
                   15955: 
1.481     raeburn  15956: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15957: (a) files in /uploaded
                   15958:   (i) If a local copy of the file exists - 
                   15959:       compares modification date of local copy with last-modified date for 
                   15960:       definitive version stored on home server for course. If local copy is 
                   15961:       stale, requests a new version from the home server and stores it. 
                   15962:       If the original has been removed from the home server, then local copy 
                   15963:       is unlinked.
                   15964:   (ii) If local copy does not exist -
                   15965:       requests the file from the home server and stores it. 
                   15966:   
                   15967:   If $caller is 'uploadrep':  
                   15968:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15969:     for request for files originally uploaded via DOCS. 
                   15970:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15971:   
                   15972:   Otherwise:
                   15973:      This indicates a call from the content generation phase of the request.
                   15974:      -  returns the entire contents of the file or -1.
                   15975:      
                   15976: (b) files in /res
                   15977:    - returns the entire contents of a file or -1; 
                   15978:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15979: 
1.712     albertel 15980: 
                   15981: =item *
                   15982: 
                   15983: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15984:                   reference
                   15985: 
                   15986: returns either a stat() list of data about the file or an empty list
                   15987: if the file doesn't exist or couldn't find out about it (connection
                   15988: problems or user unknown)
                   15989: 
1.191     harris41 15990: =item *
                   15991: 
1.243     albertel 15992: filelocation($dir,$file) : returns file system location of a file
                   15993: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15994: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15995: and a file of ../bob will become /a/bob)
1.191     harris41 15996: 
                   15997: =item *
                   15998: 
                   15999: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16000: filelocation except for hrefs
                   16001: 
                   16002: =item *
                   16003: 
1.1172.2.49  raeburn  16004: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16005: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16006: 
1.243     albertel 16007: =back
                   16008: 
1.608     albertel 16009: =head2 Usererfile file routines (/uploaded*)
                   16010: 
                   16011: =over 4
                   16012: 
                   16013: =item *
                   16014: 
                   16015: userfileupload(): main rotine for putting a file in a user or course's
                   16016:                   filespace, arguments are,
                   16017: 
1.620     albertel 16018:  formname - required - this is the name of the element in $env where the
1.608     albertel 16019:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16020:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16021:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16022:  context - if coursedoc, store the file in the course of the active role
                   16023:              of the current user; 
                   16024:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16025:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16026:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16027:          if undefined, it will be placed in "unknown"
                   16028: 
                   16029:  (This routine calls clean_filename() to remove any dangerous
                   16030:  characters from the filename, and then calls finuserfileupload() to
                   16031:  complete the transaction)
                   16032: 
                   16033:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16034:  and /adm/notfound.html if unsuccessful
                   16035: 
                   16036: =item *
                   16037: 
                   16038: clean_filename(): routine for cleaing a filename up for storage in
                   16039:                  userfile space, argument is:
                   16040: 
                   16041:  filename - proposed filename
                   16042: 
                   16043: returns: the new clean filename
                   16044: 
                   16045: =item *
                   16046: 
1.1090    raeburn  16047: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16048: userspace, probably shouldn't be called directly
                   16049: 
                   16050:   docuname: username or courseid of destination for the file
                   16051:   docudom: domain of user/course of destination for the file
                   16052:   formname: same as for userfileupload()
1.1090    raeburn  16053:   fname: filename (including subdirectories) for the file
                   16054:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16055:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16056:   allfiles: reference to hash used to store objects found by parser
                   16057:   codebase: reference to hash used for codebases of java objects found by parser
                   16058:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16059:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16060:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16061:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16062:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16063:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16064:   mimetype: reference to scalar to accommodate mime type determined
                   16065:             from File::MMagic if $parser = parse.
1.608     albertel 16066: 
                   16067:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16068:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16069:  was 'overwrite').
                   16070:  
1.608     albertel 16071: 
                   16072: =item *
                   16073: 
                   16074: renameuserfile(): renames an existing userfile to a new name
                   16075: 
                   16076:   Args:
                   16077:    docuname: username or courseid of destination for the file
                   16078:    docudom: domain of user/course of destination for the file
                   16079:    old: current file name (including any subdirs under userfiles)
                   16080:    new: desired file name (including any subdirs under userfiles)
                   16081: 
                   16082: =item *
                   16083: 
                   16084: mkdiruserfile(): creates a directory is a userfiles dir
                   16085: 
                   16086:   Args:
                   16087:    docuname: username or courseid of destination for the file
                   16088:    docudom: domain of user/course of destination for the file
                   16089:    dir: dir to create (including any subdirs under userfiles)
                   16090: 
                   16091: =item *
                   16092: 
                   16093: removeuserfile(): removes a file that exists in userfiles
                   16094: 
                   16095:   Args:
                   16096:    docuname: username or courseid of destination for the file
                   16097:    docudom: domain of user/course of destination for the file
                   16098:    fname: filname to delete (including any subdirs under userfiles)
                   16099: 
                   16100: =item *
                   16101: 
                   16102: removeuploadedurl(): convience function for removeuserfile()
                   16103: 
                   16104:   Args:
                   16105:    url:  a full /uploaded/... url to delete
                   16106: 
1.747     albertel 16107: =item * 
                   16108: 
                   16109: get_portfile_permissions():
                   16110:   Args:
                   16111:     domain: domain of user or course contain the portfolio files
                   16112:     user: name of user or num of course contain the portfolio files
                   16113:   Returns:
                   16114:     hashref of a dump of the proper file_permissions.db
                   16115:    
                   16116: 
                   16117: =item * 
                   16118: 
                   16119: get_access_controls():
                   16120: 
                   16121: Args:
                   16122:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16123:   group: (optional) the group you want the files associated with
                   16124:   file: (optional) the file you want access info on
                   16125: 
                   16126: Returns:
1.749     raeburn  16127:     a hash (keys are file names) of hashes containing
                   16128:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16129:         values are XML containing access control settings (see below) 
1.747     albertel 16130: 
                   16131: Internal notes:
                   16132: 
1.749     raeburn  16133:  access controls are stored in file_permissions.db as key=value pairs.
                   16134:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16135:         where scope -> public,guest,course,group,domains or users.
                   16136:               end -> UNIX time for end of access (0 -> no end date)
                   16137:               start -> UNIX time for start of access
                   16138: 
                   16139:     value -> XML description of access control
                   16140:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16141:             <start></start>
                   16142:             <end></end>
                   16143: 
                   16144:             <password></password>  for scope type = guest
                   16145: 
                   16146:             <domain></domain>     for scope type = course or group
                   16147:             <number></number>
                   16148:             <roles id="">
                   16149:              <role></role>
                   16150:              <access></access>
                   16151:              <section></section>
                   16152:              <group></group>
                   16153:             </roles>
                   16154: 
                   16155:             <dom></dom>         for scope type = domains
                   16156: 
                   16157:             <users>             for scope type = users
                   16158:              <user>
                   16159:               <uname></uname>
                   16160:               <udom></udom>
                   16161:              </user>
                   16162:             </users>
                   16163:            </scope> 
                   16164:               
                   16165:  Access data is also aggregated for each file in an additional key=value pair:
                   16166:  key -> path to file/file_name\0accesscontrol 
                   16167:  value -> reference to hash
                   16168:           hash contains key = value pairs
                   16169:           where key = uniqueID:scope_end_start
                   16170:                 value = UNIX time record was last updated
                   16171: 
                   16172:           Used to improve speed of look-ups of access controls for each file.  
                   16173:  
                   16174:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16175: 
1.1172.2.13  raeburn  16176: =item *
                   16177: 
1.749     raeburn  16178: modify_access_controls():
                   16179: 
                   16180: Modifies access controls for a portfolio file
                   16181: Args
                   16182: 1. file name
                   16183: 2. reference to hash of required changes,
                   16184: 3. domain
                   16185: 4. username
                   16186:   where domain,username are the domain of the portfolio owner 
                   16187:   (either a user or a course) 
                   16188: 
                   16189: Returns:
                   16190: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16191: 2. result of deletions ('ok' or 'error', with error message).
                   16192: 3. reference to hash of any new or updated access controls.
                   16193: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16194:    key = integer (inbound ID)
1.1172.2.13  raeburn  16195:    value = uniqueID
                   16196: 
                   16197: =item *
                   16198: 
                   16199: get_timebased_id():
                   16200: 
                   16201: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16202: course via the Course Editor (e.g., folders, composite pages,
                   16203: group bulletin boards).
                   16204: 
                   16205: Args: (first three required; six others optional)
                   16206: 
                   16207: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16208:    docssequence, or name of group
                   16209: 
                   16210: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16211:    e.g., num, boardids
                   16212: 
                   16213: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16214:    file will be named nohist_namespace.db
                   16215: 
                   16216: 4. cdom: domain of course; default is current course domain from %env
                   16217: 
                   16218: 5. cnum: course number; default is current course number from %env
                   16219: 
                   16220: 6. idtype: set to concat if an additional digit is to be appended to the
                   16221:    unix timestamp to form the suffix, if the plain timestamp is already
                   16222:    in use.  Default is to not do this, but simply increment the unix
                   16223:    timestamp by 1 until a unique key is obtained.
                   16224: 
                   16225: 7. who: holder of locking key; defaults to user:domain for user.
                   16226: 
                   16227: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16228:    retrying); default is 3.
                   16229: 
                   16230: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16231: 
                   16232: Returns:
                   16233: 
                   16234: 1. suffix obtained (numeric)
                   16235: 
                   16236: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16237: 
                   16238: 3. error: contains (localized) error message if an error occurred.
                   16239: 
1.747     albertel 16240: 
1.608     albertel 16241: =back
                   16242: 
1.243     albertel 16243: =head2 HTTP Helper Routines
                   16244: 
                   16245: =over 4
                   16246: 
1.191     harris41 16247: =item *
                   16248: 
                   16249: escape() : unpack non-word characters into CGI-compatible hex codes
                   16250: 
                   16251: =item *
                   16252: 
                   16253: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16254: 
1.243     albertel 16255: =back
                   16256: 
                   16257: =head1 PRIVATE SUBROUTINES
                   16258: 
                   16259: =head2 Underlying communication routines (Shouldn't call)
                   16260: 
                   16261: =over 4
                   16262: 
                   16263: =item *
                   16264: 
                   16265: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16266: 
                   16267: =item *
                   16268: 
                   16269: reply() : uses subreply to send a message to remote machine, logs all failures
                   16270: 
                   16271: =item *
                   16272: 
                   16273: critical() : passes a critical message to another server; if cannot
                   16274: get through then place message in connection buffer directory and
                   16275: returns con_delayed, if incapable of saving message, returns
                   16276: con_failed
                   16277: 
                   16278: =item *
                   16279: 
                   16280: reconlonc() : tries to reconnect lonc client processes.
                   16281: 
                   16282: =back
                   16283: 
                   16284: =head2 Resource Access Logging
                   16285: 
                   16286: =over 4
                   16287: 
                   16288: =item *
                   16289: 
                   16290: flushcourselogs() : flush (save) buffer logs and access logs
                   16291: 
                   16292: =item *
                   16293: 
                   16294: courselog($what) : save message for course in hash
                   16295: 
                   16296: =item *
                   16297: 
                   16298: courseacclog($what) : save message for course using &courselog().  Perform
                   16299: special processing for specific resource types (problems, exams, quizzes, etc).
                   16300: 
1.191     harris41 16301: =item *
                   16302: 
                   16303: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16304: as a PerlChildExitHandler
1.243     albertel 16305: 
                   16306: =back
                   16307: 
                   16308: =head2 Other
                   16309: 
                   16310: =over 4
                   16311: 
                   16312: =item *
                   16313: 
                   16314: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16315: 
                   16316: =back
                   16317: 
                   16318: =cut
1.877     foxr     16319: 

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