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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .5(raebu    4:22): # $Id: lonnet.pm,v 1.1172.2.146.2.4 2022/02/20 20:40:57 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.146.  .1(raebu  130:22):         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.146.  .5(raebu 1257:22):     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.146.  .5(raebu 1306:22): 	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.1172.2.146.  .1(raebu 1885:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
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");
1.1172.2.146.  .1(raebu 1912:22):         } else {
                   1913:22):             if ($encrypt) {
                   1914:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1915:22):             } else {
                   1916:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1917:22):             }
1.1172.2.139  raeburn  1918:         }
1.866     raeburn  1919:         my %returnhash;
1.875     albertel 1920:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1921:             return %returnhash;
                   1922:         }
1.806     raeburn  1923:         my @pairs=split(/\&/,$rep);
                   1924:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1925:             return @pairs;
                   1926:         }
                   1927:         my $i=0;
                   1928:         foreach my $item (@$storearr) {
                   1929:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1930:             $i++;
                   1931:         }
                   1932:         return %returnhash;
                   1933:     } else {
1.880     banghart 1934:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1935:     }
                   1936: }
                   1937: 
                   1938: # -------------------------------------------- put items in domain db files 
                   1939: 
                   1940: sub put_dom {
1.1172.2.146.  .1(raebu 1941:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  1942:     if (!$udom) {
                   1943:         $udom=$env{'user.domain'};
                   1944:         if (defined(&domain($udom,'primary'))) {
                   1945:             $uhome=&domain($udom,'primary');
                   1946:         } else {
1.874     albertel 1947:             undef($uhome);
1.860     raeburn  1948:         }
                   1949:     } else {
                   1950:         if (!$uhome) {
                   1951:             if (defined(&domain($udom,'primary'))) {
                   1952:                 $uhome=&domain($udom,'primary');
                   1953:             }
                   1954:         }
                   1955:     } 
                   1956:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1957:         my $items='';
                   1958:         foreach my $item (keys(%$storehash)) {
                   1959:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1960:         }
                   1961:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 1962:22):         if ($encrypt) {
                   1963:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1964:22):         } else {
                   1965:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1966:22):         }
1.806     raeburn  1967:     } else {
1.860     raeburn  1968:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1969:     }
                   1970: }
                   1971: 
1.1023    raeburn  1972: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1973: sub newput_dom {
1.1023    raeburn  1974:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1975:     my $result;
                   1976:     if (!$udom) {
                   1977:         $udom=$env{'user.domain'};
                   1978:     }
1.1023    raeburn  1979:     if ($udom) {
                   1980:         my $uname = &get_domainconfiguser($udom);
                   1981:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1982:     }
                   1983:     return $result;
                   1984: }
                   1985: 
1.1023    raeburn  1986: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1987: sub del_dom {
1.1023    raeburn  1988:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1989:     if (ref($storearr) eq 'ARRAY') {
                   1990:         if (!$udom) {
                   1991:             $udom=$env{'user.domain'};
                   1992:         }
1.1023    raeburn  1993:         if ($udom) {
                   1994:             my $uname = &get_domainconfiguser($udom); 
                   1995:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1996:         }
                   1997:     }
                   1998: }
                   1999: 
1.1172.2.146.  .4(raebu 2000:22): sub store_dom {
                   2001:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2002:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2003:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2004:22):     my $namevalue='';
                   2005:22):     foreach my $key (keys(%{$storehash})) {
                   2006:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2007:22):     }
                   2008:22):     $namevalue=~s/\&$//;
                   2009:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2010:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2011:22):     } else {
                   2012:22):         if ($namespace eq 'private') {
                   2013:22):             return 'refused';
                   2014:22):         } elsif ($encrypt) {
                   2015:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2016:22):         } else {
                   2017:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2018:22):         }
                   2019:22):     }
                   2020:22): }
                   2021:22): 
                   2022:22): sub restore_dom {
                   2023:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2024:22):     my $answer;
                   2025:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2026:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2027:22):     } elsif ($namespace ne 'private') {
                   2028:22):         if ($encrypt) {
                   2029:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2030:22):         } else {
                   2031:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2032:22):         }
                   2033:22):     }
                   2034:22):     my %returnhash=();
                   2035:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2036:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2037:22):         foreach my $line (split(/\&/,$answer)) {
                   2038:22):             my ($name,$value)=split(/\=/,$line);
                   2039:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2040:22):         }
                   2041:22):         my $version;
                   2042:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2043:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2044:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2045:22):             }
                   2046:22):         }
                   2047:22):     }
                   2048:22):     return %returnhash;
                   2049:22): }
                   2050:22): 
1.1023    raeburn  2051: # ----------------------------------construct domainconfig user for a domain 
                   2052: sub get_domainconfiguser {
                   2053:     my ($udom) = @_;
                   2054:     return $udom.'-domainconfig';
                   2055: }
                   2056: 
1.837     raeburn  2057: sub retrieve_inst_usertypes {
                   2058:     my ($udom) = @_;
                   2059:     my (%returnhash,@order);
1.989     raeburn  2060:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2061:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2062:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2063:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2064:     } else {
                   2065:         if (defined(&domain($udom,'primary'))) {
                   2066:             my $uhome=&domain($udom,'primary');
                   2067:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2068:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2069:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2070:                 return (\%returnhash,\@order);
                   2071:             }
                   2072:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2073:             my @pairs=split(/\&/,$hashitems);
                   2074:             foreach my $item (@pairs) {
                   2075:                 my ($key,$value)=split(/=/,$item,2);
                   2076:                 $key = &unescape($key);
                   2077:                 next if ($key =~ /^error: 2 /);
                   2078:                 $returnhash{$key}=&thaw_unescape($value);
                   2079:             }
                   2080:             my @esc_order = split(/\&/,$orderitems);
                   2081:             foreach my $item (@esc_order) {
                   2082:                 push(@order,&unescape($item));
                   2083:             }
                   2084:         } else {
1.1172.2.44  raeburn  2085:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2086:         }
1.1172.2.44  raeburn  2087:         return (\%returnhash,\@order);
1.837     raeburn  2088:     }
                   2089: }
                   2090: 
1.868     raeburn  2091: sub is_domainimage {
                   2092:     my ($url) = @_;
1.1172.2.142  raeburn  2093:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2094:         if (&domain($1) ne '') {
                   2095:             return '1';
                   2096:         }
                   2097:     }
                   2098:     return;
                   2099: }
                   2100: 
1.899     raeburn  2101: sub inst_directory_query {
                   2102:     my ($srch) = @_;
                   2103:     my $udom = $srch->{'srchdomain'};
                   2104:     my %results;
                   2105:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2106:     my $outcome;
1.899     raeburn  2107:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2108:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2109:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2110:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2111:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2112:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2113:                     (($major == 2) && ($minor < 11)) ||
                   2114:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2115:                     return;
                   2116:                 }
                   2117:             }
                   2118:         }
1.904     albertel 2119: 	my $queryid=&reply("querysend:instdirsearch:".
                   2120: 			   &escape($srch->{'srchby'}).':'.
                   2121: 			   &escape($srch->{'srchterm'}).':'.
                   2122: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2123: 	my $host=&hostname($homeserver);
                   2124: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2125: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2126: 	    return;
                   2127: 	}
                   2128: 	my $response = &get_query_reply($queryid);
                   2129: 	my $maxtries = 5;
                   2130: 	my $tries = 1;
                   2131: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2132: 	    $response = &get_query_reply($queryid);
                   2133: 	    $tries ++;
                   2134: 	}
                   2135: 
                   2136:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2137:             if ($response eq 'unavailable') {
                   2138:                 $outcome = $response;
                   2139:             } else {
                   2140:                 $outcome = 'ok';
                   2141:                 my @matches = split(/\n/,$response);
                   2142:                 foreach my $match (@matches) {
                   2143:                     my ($key,$value) = split(/=/,$match);
                   2144:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2145:                 }
1.899     raeburn  2146:             }
                   2147:         }
                   2148:     }
1.909     raeburn  2149:     return ($outcome,%results);
1.899     raeburn  2150: }
                   2151: 
                   2152: sub usersearch {
                   2153:     my ($srch) = @_;
                   2154:     my $dom = $srch->{'srchdomain'};
                   2155:     my %results;
                   2156:     my %libserv = &all_library();
                   2157:     my $query = 'usersearch';
                   2158:     foreach my $tryserver (keys(%libserv)) {
                   2159:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2160:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2161:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2162:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2163:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2164:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2165:                              (($major == 2) && ($minor < 11)) ||
                   2166:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2167:                 }
                   2168:             }
1.899     raeburn  2169:             my $host=&hostname($tryserver);
                   2170:             my $queryid=
1.911     raeburn  2171:                 &reply("querysend:".&escape($query).':'.
                   2172:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2173:                        &escape($srch->{'srchtype'}).':'.
                   2174:                        &escape($srch->{'srchterm'}),$tryserver);
                   2175:             if ($queryid !~/^\Q$host\E\_/) {
                   2176:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2177:                 next;
1.899     raeburn  2178:             }
                   2179:             my $reply = &get_query_reply($queryid);
                   2180:             my $maxtries = 1;
                   2181:             my $tries = 1;
                   2182:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2183:                 $reply = &get_query_reply($queryid);
                   2184:                 $tries ++;
                   2185:             }
                   2186:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2187:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2188:             } else {
1.911     raeburn  2189:                 my @matches;
                   2190:                 if ($reply =~ /\n/) {
                   2191:                     @matches = split(/\n/,$reply);
                   2192:                 } else {
                   2193:                     @matches = split(/\&/,$reply);
                   2194:                 }
1.899     raeburn  2195:                 foreach my $match (@matches) {
                   2196:                     my ($uname,$udom,%userhash);
1.911     raeburn  2197:                     foreach my $entry (split(/:/,$match)) {
                   2198:                         my ($key,$value) =
                   2199:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2200:                         $userhash{$key} = $value;
                   2201:                         if ($key eq 'username') {
                   2202:                             $uname = $value;
                   2203:                         } elsif ($key eq 'domain') {
                   2204:                             $udom = $value;
1.911     raeburn  2205:                         }
1.899     raeburn  2206:                     }
                   2207:                     $results{$uname.':'.$udom} = \%userhash;
                   2208:                 }
                   2209:             }
                   2210:         }
                   2211:     }
                   2212:     return %results;
                   2213: }
                   2214: 
1.912     raeburn  2215: sub get_instuser {
                   2216:     my ($udom,$uname,$id) = @_;
                   2217:     my $homeserver = &domain($udom,'primary');
                   2218:     my ($outcome,%results);
                   2219:     if ($homeserver ne '') {
                   2220:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2221:                            &escape($id).':'.&escape($udom),$homeserver);
                   2222:         my $host=&hostname($homeserver);
                   2223:         if ($queryid !~/^\Q$host\E\_/) {
                   2224:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2225:             return;
                   2226:         }
                   2227:         my $response = &get_query_reply($queryid);
                   2228:         my $maxtries = 5;
                   2229:         my $tries = 1;
                   2230:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2231:             $response = &get_query_reply($queryid);
                   2232:             $tries ++;
                   2233:         }
                   2234:         if (!&error($response) && $response ne 'refused') {
                   2235:             if ($response eq 'unavailable') {
                   2236:                 $outcome = $response;
                   2237:             } else {
                   2238:                 $outcome = 'ok';
                   2239:                 my @matches = split(/\n/,$response);
                   2240:                 foreach my $match (@matches) {
                   2241:                     my ($key,$value) = split(/=/,$match);
                   2242:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2243:                 }
                   2244:             }
                   2245:         }
                   2246:     }
                   2247:     my %userinfo;
                   2248:     if (ref($results{$uname}) eq 'HASH') {
                   2249:         %userinfo = %{$results{$uname}};
                   2250:     } 
                   2251:     return ($outcome,%userinfo);
                   2252: }
                   2253: 
1.1172.2.69  raeburn  2254: sub get_multiple_instusers {
                   2255:     my ($udom,$users,$caller) = @_;
                   2256:     my ($outcome,$results);
                   2257:     if (ref($users) eq 'HASH') {
                   2258:         my $count = keys(%{$users});
                   2259:         my $requested = &freeze_escape($users);
                   2260:         my $homeserver = &domain($udom,'primary');
                   2261:         if ($homeserver ne '') {
                   2262:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2263:             my $host=&hostname($homeserver);
                   2264:             if ($queryid !~/^\Q$host\E\_/) {
                   2265:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2266:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2267:                 return ($outcome,$results);
                   2268:             }
                   2269:             my $response = &get_query_reply($queryid);
                   2270:             my $maxtries = 5;
                   2271:             if ($count > 100) {
                   2272:                 $maxtries = 1+int($count/20);
                   2273:             }
                   2274:             my $tries = 1;
                   2275:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2276:                 $response = &get_query_reply($queryid);
                   2277:                 $tries ++;
                   2278:             }
                   2279:             if ($response eq '') {
                   2280:                 $results = {};
                   2281:                 foreach my $key (keys(%{$users})) {
                   2282:                     my ($uname,$id);
                   2283:                     if ($caller eq 'id') {
                   2284:                         $id = $key;
                   2285:                     } else {
                   2286:                         $uname = $key;
                   2287:                     }
                   2288:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2289:                     $outcome = $resp;
                   2290:                     if ($resp eq 'ok') {
                   2291:                         %{$results} = (%{$results}, %info);
                   2292:                     } else {
                   2293:                         last;
                   2294:                     }
                   2295:                 }
                   2296:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2297:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2298:                     $outcome = $response;
                   2299:                 } else {
                   2300:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2301:                     if ($outcome eq 'ok') {
                   2302:                         $results = &thaw_unescape($userdata);
                   2303:                     }
                   2304:                 }
                   2305:             }
                   2306:         }
                   2307:     }
                   2308:     return ($outcome,$results);
                   2309: }
                   2310: 
1.912     raeburn  2311: sub inst_rulecheck {
1.923     raeburn  2312:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2313:     my %returnhash;
                   2314:     if ($udom ne '') {
                   2315:         if (ref($rules) eq 'ARRAY') {
                   2316:             @{$rules} = map {&escape($_);} (@{$rules});
                   2317:             my $rulestr = join(':',@{$rules});
                   2318:             my $homeserver=&domain($udom,'primary');
                   2319:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2320:                 my $response;
                   2321:                 if ($item eq 'username') {                
                   2322:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2323:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2324:                                               $homeserver));
1.923     raeburn  2325:                 } elsif ($item eq 'id') {
                   2326:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2327:                                               ':'.&escape($id).':'.$rulestr,
                   2328:                                               $homeserver));
1.1172.2.146.  .5(raebu 2329:22):                 } elsif ($item eq 'unamemap') {
                   2330:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2331:22):                                                &escape($udom).':'.&escape($uname).
                   2332:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2333:                 } elsif ($item eq 'selfcreate') {
                   2334:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2335:                                                &escape($udom).':'.&escape($uname).
                   2336:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2337:                 }
1.912     raeburn  2338:                 if ($response ne 'refused') {
                   2339:                     my @pairs=split(/\&/,$response);
                   2340:                     foreach my $item (@pairs) {
                   2341:                         my ($key,$value)=split(/=/,$item,2);
                   2342:                         $key = &unescape($key);
                   2343:                         next if ($key =~ /^error: 2 /);
                   2344:                         $returnhash{$key}=&thaw_unescape($value);
                   2345:                     }
                   2346:                 }
                   2347:             }
                   2348:         }
                   2349:     }
                   2350:     return %returnhash;
                   2351: }
                   2352: 
                   2353: sub inst_userrules {
1.923     raeburn  2354:     my ($udom,$check) = @_;
1.912     raeburn  2355:     my (%ruleshash,@ruleorder);
                   2356:     if ($udom ne '') {
                   2357:         my $homeserver=&domain($udom,'primary');
                   2358:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2359:             my $response;
                   2360:             if ($check eq 'id') {
                   2361:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2362:                                  $homeserver);
1.943     raeburn  2363:             } elsif ($check eq 'email') {
                   2364:                 $response=&reply('instemailrules:'.&escape($udom),
                   2365:                                  $homeserver);
1.1172.2.146.  .5(raebu 2366:22):             } elsif ($check eq 'unamemap') {
                   2367:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2368:22):                                  $homeserver);
1.923     raeburn  2369:             } else {
                   2370:                 $response=&reply('instuserrules:'.&escape($udom),
                   2371:                                  $homeserver);
                   2372:             }
1.912     raeburn  2373:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2374:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2375:                 ($response ne 'no_such_host')) {
                   2376:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2377:                 my @pairs=split(/\&/,$hashitems);
                   2378:                 foreach my $item (@pairs) {
                   2379:                     my ($key,$value)=split(/=/,$item,2);
                   2380:                     $key = &unescape($key);
                   2381:                     next if ($key =~ /^error: 2 /);
                   2382:                     $ruleshash{$key}=&thaw_unescape($value);
                   2383:                 }
                   2384:                 my @esc_order = split(/\&/,$orderitems);
                   2385:                 foreach my $item (@esc_order) {
                   2386:                     push(@ruleorder,&unescape($item));
                   2387:                 }
                   2388:             }
                   2389:         }
                   2390:     }
                   2391:     return (\%ruleshash,\@ruleorder);
                   2392: }
                   2393: 
1.976     raeburn  2394: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2395: 
                   2396: sub get_domain_defaults {
1.1172.2.35  raeburn  2397:     my ($domain,$ignore_cache) = @_;
                   2398:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2399:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2400:     unless ($ignore_cache) {
                   2401:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2402:         if (defined($cached)) {
                   2403:             if (ref($result) eq 'HASH') {
                   2404:                 return %{$result};
                   2405:             }
1.943     raeburn  2406:         }
                   2407:     }
                   2408:     my %domdefaults;
                   2409:     my %domconfig =
1.989     raeburn  2410:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2411:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2412:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2413:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2414:                                   'coursecategories','autoenroll',
1.1172.2.146.  .4(raebu 2415:22):                                   'helpsettings','wafproxy','ltisec'],$domain);
1.1172.2.41  raeburn  2416:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2417:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2418:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2419:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2420:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2421:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2422:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2423:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2424:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2425:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2426:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2427:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2428:     } else {
                   2429:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2430:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2431:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2432:     }
1.976     raeburn  2433:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2434:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2435:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2436:         } else {
                   2437:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2438:         }
1.1172.2.6  raeburn  2439:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2440:         foreach my $item (@usertools) {
                   2441:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2442:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2443:             }
                   2444:         }
1.1172.2.29  raeburn  2445:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2446:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2447:         }
1.976     raeburn  2448:     }
1.985     raeburn  2449:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2450:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2451:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2452:         }
                   2453:     }
1.1172.2.9  raeburn  2454:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2455:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2456:     }
1.989     raeburn  2457:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2458:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2459:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2460:         }
                   2461:     }
1.1047    raeburn  2462:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2463:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2464:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2465:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2466:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2467:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2468:         }
1.1172.2.41  raeburn  2469:         foreach my $type (@coursetypes) {
                   2470:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2471:                 unless ($type eq 'community') {
                   2472:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2473:                 }
                   2474:             }
                   2475:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2476:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2477:             }
1.1172.2.60  raeburn  2478:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2479:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2480:                     $domdefaults{$type.'postsubtimeout'} =
                   2481:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2482:                 }
                   2483:             }
1.1172.2.30  raeburn  2484:         }
1.1172.2.67  raeburn  2485:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2486:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2487:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2488:                 if (@clonecodes) {
                   2489:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2490:                 }
                   2491:             }
                   2492:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2493:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2494:         }
1.1172.2.103  raeburn  2495:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2496:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2497:         }
1.1172.2.146.  .3(raebu 2498:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2499:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2500:22):         }
1.1047    raeburn  2501:     }
1.1073    raeburn  2502:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2503:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2504:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2505:         }
                   2506:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2507:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2508:         }
1.1172.2.62  raeburn  2509:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2510:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2511:         }
1.1172.2.137  raeburn  2512:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2513:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2514:         }
1.1073    raeburn  2515:     }
1.1172.2.41  raeburn  2516:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2517:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2518:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2519:                             'approval','limit');
                   2520:             foreach my $type (@coursetypes) {
                   2521:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2522:                     my @mgrdc = ();
                   2523:                     foreach my $item (@settings) {
                   2524:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2525:                             push(@mgrdc,$item);
                   2526:                         }
                   2527:                     }
                   2528:                     if (@mgrdc) {
                   2529:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2530:                     }
                   2531:                 }
                   2532:             }
                   2533:         }
                   2534:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2535:             foreach my $type (@coursetypes) {
                   2536:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2537:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2538:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2539:                     }
                   2540:                 }
                   2541:             }
                   2542:         }
                   2543:     }
1.1172.2.46  raeburn  2544:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2545:         $domdefaults{'catauth'} = 'std';
                   2546:         $domdefaults{'catunauth'} = 'std';
                   2547:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2548:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2549:         }
                   2550:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2551:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2552:         }
                   2553:     }
1.1172.2.76  raeburn  2554:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2555:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2556:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2557:     }
1.1172.2.89  raeburn  2558:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2559:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2560:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2561:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2562:         }
                   2563:     }
1.1172.2.142  raeburn  2564:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2565:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2566:             if ($domconfig{'wafproxy'}{$item}) {
                   2567:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2568:             }
                   2569:         }
                   2570:     }
1.1172.2.146.  .4(raebu 2571:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2572:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2573:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2574:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2575:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2576:22):         }
                   2577:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2578:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2579:22):                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2580:22):             }
                   2581:22):         }
                   2582:22):     }
1.1172.2.23  raeburn  2583:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2584:     return %domdefaults;
                   2585: }
                   2586: 
1.1172.2.106  raeburn  2587: sub get_dom_cats {
                   2588:     my ($dom) = @_;
                   2589:     return unless (&domain($dom));
                   2590:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2591:     unless (defined($cached)) {
                   2592:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2593:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2594:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2595:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2596:             } else {
                   2597:                 $cats = {};
                   2598:             }
                   2599:         } else {
                   2600:             $cats = {};
                   2601:         }
                   2602:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2603:     }
                   2604:     return $cats;
                   2605: }
                   2606: 
                   2607: sub get_dom_instcats {
                   2608:     my ($dom) = @_;
                   2609:     return unless (&domain($dom));
                   2610:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2611:     unless (defined($cached)) {
                   2612:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2613:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2614:         if ($totcodes > 0) {
                   2615:             my $caller = 'global';
                   2616:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2617:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2618:                 $instcats = {
                   2619:                                 codes => \%codes,
                   2620:                                 codetitles => \@codetitles,
                   2621:                                 cat_titles => \%cat_titles,
                   2622:                                 cat_order => \%cat_order,
                   2623:                             };
                   2624:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2625:             }
                   2626:         }
                   2627:     }
                   2628:     return $instcats;
                   2629: }
                   2630: 
                   2631: sub retrieve_instcodes {
                   2632:     my ($coursecodes,$dom) = @_;
                   2633:     my $totcodes;
                   2634:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2635:     foreach my $course (keys(%courses)) {
                   2636:         if (ref($courses{$course}) eq 'HASH') {
                   2637:             if ($courses{$course}{'inst_code'} ne '') {
                   2638:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2639:                 $totcodes ++;
                   2640:             }
                   2641:         }
                   2642:     }
                   2643:     return $totcodes;
                   2644: }
                   2645: 
1.1172.2.113  raeburn  2646: # --------------------------------------------- Get domain config for passwords
                   2647: 
                   2648: sub get_passwdconf {
                   2649:     my ($dom) = @_;
                   2650:     my (%passwdconf,$gotconf,$lookup);
                   2651:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2652:     if (defined($cached)) {
                   2653:         if (ref($result) eq 'HASH') {
                   2654:             %passwdconf = %{$result};
                   2655:             $gotconf = 1;
                   2656:         }
                   2657:     }
                   2658:     unless ($gotconf) {
                   2659:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2660:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2661:             %passwdconf = %{$domconfig{'passwords'}};
                   2662:         }
                   2663:         my $cachetime = 24*60*60;
                   2664:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2665:     }
                   2666:     return %passwdconf;
                   2667: }
                   2668: 
1.1172.2.146.  .1(raebu 2669:22): sub course_portal_url {
                   2670:22):     my ($cnum,$cdom,$r) = @_;
                   2671:22):     my $chome = &homeserver($cnum,$cdom);
                   2672:22):     my $hostname = &hostname($chome);
                   2673:22):     my $protocol = $protocol{$chome};
                   2674:22):     $protocol = 'http' if ($protocol ne 'https');
                   2675:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2676:22):     my $firsturl;
                   2677:22):     if ($domdefaults{'portal_def'}) {
                   2678:22):         $firsturl = $domdefaults{'portal_def'};
                   2679:22):     } else {
                   2680:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2681:22):         $hostname = $alias if ($alias ne '');
                   2682:22):         $firsturl = $protocol.'://'.$hostname;
                   2683:22):     }
                   2684:22):     return $firsturl;
                   2685:22): }
                   2686:22): 
1.344     www      2687: # --------------------------------------------------- Assign a key to a student
                   2688: 
                   2689: sub assign_access_key {
1.364     www      2690: #
                   2691: # a valid key looks like uname:udom#comments
                   2692: # comments are being appended
                   2693: #
1.498     www      2694:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2695:     $kdom=
1.620     albertel 2696:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2697:     $knum=
1.620     albertel 2698:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2699:     $cdom=
1.620     albertel 2700:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2701:     $cnum=
1.620     albertel 2702:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2703:     $udom=$env{'user.name'} unless (defined($udom));
                   2704:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2705:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2706:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2707:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2708:                                                   # assigned to this person
                   2709:                                                   # - this should not happen,
1.345     www      2710:                                                   # unless something went wrong
                   2711:                                                   # the first time around
                   2712: # ready to assign
1.364     www      2713:         $logentry=$1.'; '.$logentry;
1.496     www      2714:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2715:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2716: # key now belongs to user
1.346     www      2717: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2718:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2719:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2720:                 return 'ok';
                   2721:             } else {
                   2722:                 return 
                   2723:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2724: 	    }
                   2725:         } else {
                   2726:             return 'error: Could not assign key, try again later.';
                   2727:         }
1.364     www      2728:     } elsif (!$existing{$ckey}) {
1.345     www      2729: # the key does not exist
                   2730: 	return 'error: The key does not exist';
                   2731:     } else {
                   2732: # the key is somebody else's
                   2733: 	return 'error: The key is already in use';
                   2734:     }
1.344     www      2735: }
                   2736: 
1.364     www      2737: # ------------------------------------------ put an additional comment on a key
                   2738: 
                   2739: sub comment_access_key {
                   2740: #
                   2741: # a valid key looks like uname:udom#comments
                   2742: # comments are being appended
                   2743: #
                   2744:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2745:     $cdom=
1.620     albertel 2746:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2747:     $cnum=
1.620     albertel 2748:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2749:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2750:     if ($existing{$ckey}) {
                   2751:         $existing{$ckey}.='; '.$logentry;
                   2752: # ready to assign
1.367     www      2753:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2754:                                                  $cdom,$cnum) eq 'ok') {
                   2755: 	    return 'ok';
                   2756:         } else {
                   2757: 	    return 'error: Count not store comment.';
                   2758:         }
                   2759:     } else {
                   2760: # the key does not exist
                   2761: 	return 'error: The key does not exist';
                   2762:     }
                   2763: }
                   2764: 
1.344     www      2765: # ------------------------------------------------------ Generate a set of keys
                   2766: 
                   2767: sub generate_access_keys {
1.364     www      2768:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2769:     $cdom=
1.620     albertel 2770:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2771:     $cnum=
1.620     albertel 2772:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2773:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2774:     unless (($cdom) && ($cnum)) { return 0; }
                   2775:     if ($number>10000) { return 0; }
                   2776:     sleep(2); # make sure don't get same seed twice
                   2777:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2778:     my $total=0;
                   2779:     for (my $i=1;$i<=$number;$i++) {
                   2780:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2781:                   sprintf("%lx",int(100000*rand)).'-'.
                   2782:                   sprintf("%lx",int(100000*rand));
                   2783:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2784:        $newkey=~s/0/h/g; # and also 0 and O
                   2785:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2786:        if ($existing{$newkey}) {
                   2787:            $i--;
                   2788:        } else {
1.364     www      2789: 	  if (&put('accesskeys',
                   2790:               { $newkey => '# generated '.localtime().
1.620     albertel 2791:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2792:                            '; '.$logentry },
                   2793: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2794:               $total++;
                   2795: 	  }
                   2796:        }
                   2797:     }
1.620     albertel 2798:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2799:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2800:     return $total;
                   2801: }
                   2802: 
                   2803: # ------------------------------------------------------- Validate an accesskey
                   2804: 
                   2805: sub validate_access_key {
                   2806:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2807:     $cdom=
1.620     albertel 2808:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2809:     $cnum=
1.620     albertel 2810:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2811:     $udom=$env{'user.domain'} unless (defined($udom));
                   2812:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2813:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2814:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2815: }
                   2816: 
                   2817: # ------------------------------------- Find the section of student in a course
1.652     albertel 2818: sub devalidate_getsection_cache {
                   2819:     my ($udom,$unam,$courseid)=@_;
                   2820:     my $hashid="$udom:$unam:$courseid";
                   2821:     &devalidate_cache_new('getsection',$hashid);
                   2822: }
1.298     matthew  2823: 
1.815     albertel 2824: sub courseid_to_courseurl {
                   2825:     my ($courseid) = @_;
                   2826:     #already url style courseid
                   2827:     return $courseid if ($courseid =~ m{^/});
                   2828: 
                   2829:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2830: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2831: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2832: 	return "/$cdom/$cnum";
                   2833:     }
                   2834: 
                   2835:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2836:     if (exists($courseinfo{'num'})) {
                   2837: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2838:     }
                   2839: 
                   2840:     return undef;
                   2841: }
                   2842: 
1.298     matthew  2843: sub getsection {
                   2844:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2845:     my $cachetime=1800;
1.551     albertel 2846: 
                   2847:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2848:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2849:     if (defined($cached)) { return $result; }
                   2850: 
1.298     matthew  2851:     my %Pending; 
                   2852:     my %Expired;
                   2853:     #
                   2854:     # Each role can either have not started yet (pending), be active, 
                   2855:     #    or have expired.
                   2856:     #
                   2857:     # If there is an active role, we are done.
                   2858:     #
                   2859:     # If there is more than one role which has not started yet, 
                   2860:     #     choose the one which will start sooner
                   2861:     # If there is one role which has not started yet, return it.
                   2862:     #
                   2863:     # If there is more than one expired role, choose the one which ended last.
                   2864:     # If there is a role which has expired, return it.
                   2865:     #
1.815     albertel 2866:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2867:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2868:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2869:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2870:         my $section=$1;
                   2871:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2872:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2873:         my $now=time;
1.548     albertel 2874:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2875:             $Expired{$end}=$section;
                   2876:             next;
                   2877:         }
1.548     albertel 2878:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2879:             $Pending{$start}=$section;
                   2880:             next;
                   2881:         }
1.599     albertel 2882:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2883:     }
                   2884:     #
                   2885:     # Presumedly there will be few matching roles from the above
                   2886:     # loop and the sorting time will be negligible.
                   2887:     if (scalar(keys(%Pending))) {
                   2888:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2889:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2890:     } 
                   2891:     if (scalar(keys(%Expired))) {
                   2892:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2893:         my $time = pop(@sorted);
1.599     albertel 2894:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2895:     }
1.599     albertel 2896:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2897: }
1.70      www      2898: 
1.599     albertel 2899: sub save_cache {
                   2900:     &purge_remembered();
1.722     albertel 2901:     #&Apache::loncommon::validate_page();
1.620     albertel 2902:     undef(%env);
1.780     albertel 2903:     undef($env_loaded);
1.599     albertel 2904: }
1.452     albertel 2905: 
1.599     albertel 2906: my $to_remember=-1;
                   2907: my %remembered;
                   2908: my %accessed;
                   2909: my $kicks=0;
                   2910: my $hits=0;
1.849     albertel 2911: sub make_key {
                   2912:     my ($name,$id) = @_;
1.872     albertel 2913:     if (length($id) > 65 
                   2914: 	&& length(&escape($id)) > 200) {
                   2915: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2916:     }
1.849     albertel 2917:     return &escape($name.':'.$id);
                   2918: }
                   2919: 
1.599     albertel 2920: sub devalidate_cache_new {
                   2921:     my ($name,$id,$debug) = @_;
                   2922:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2923:     my $remembered_id=$name.':'.$id;
1.849     albertel 2924:     $id=&make_key($name,$id);
1.599     albertel 2925:     $memcache->delete($id);
1.1172.2.81  raeburn  2926:     delete($remembered{$remembered_id});
                   2927:     delete($accessed{$remembered_id});
1.599     albertel 2928: }
                   2929: 
                   2930: sub is_cached_new {
                   2931:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2932:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2933:                                      # keys in %remembered hash, which persists for
                   2934:                                      # duration of request (no restriction on key length).
                   2935:     if (exists($remembered{$remembered_id})) {
                   2936: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2937: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2938: 	$hits++;
1.1172.2.81  raeburn  2939: 	return ($remembered{$remembered_id},1);
1.599     albertel 2940:     }
1.1172.2.81  raeburn  2941:     $id=&make_key($name,$id);
1.599     albertel 2942:     my $value = $memcache->get($id);
                   2943:     if (!(defined($value))) {
                   2944: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2945: 	return (undef,undef);
1.416     albertel 2946:     }
1.599     albertel 2947:     if ($value eq '__undef__') {
                   2948: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2949: 	$value=undef;
                   2950:     }
1.1172.2.81  raeburn  2951:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2952:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2953:     return ($value,1);
                   2954: }
                   2955: 
                   2956: sub do_cache_new {
                   2957:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2958:     my $remembered_id=$name.':'.$id;
1.849     albertel 2959:     $id=&make_key($name,$id);
1.599     albertel 2960:     my $setvalue=$value;
                   2961:     if (!defined($setvalue)) {
                   2962: 	$setvalue='__undef__';
                   2963:     }
1.623     albertel 2964:     if (!defined($time) ) {
                   2965: 	$time=600;
                   2966:     }
1.599     albertel 2967:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2968:     my $result = $memcache->set($id,$setvalue,$time);
                   2969:     if (! $result) {
1.872     albertel 2970: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2971: 	$memcache->disconnect_all();
1.872     albertel 2972:     }
1.600     albertel 2973:     # need to make a copy of $value
1.1172.2.81  raeburn  2974:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2975:     return $value;
                   2976: }
                   2977: 
                   2978: sub make_room {
1.1172.2.81  raeburn  2979:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2980: 
1.1172.2.81  raeburn  2981:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2982:                                     : $value;
1.599     albertel 2983:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2984:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2985:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2986:     my $to_kick;
                   2987:     my $max_time=0;
                   2988:     foreach my $other (keys(%accessed)) {
                   2989: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2990: 	    $to_kick=$other;
                   2991: 	    $max_time=&tv_interval($accessed{$other});
                   2992: 	}
                   2993:     }
                   2994:     delete($remembered{$to_kick});
                   2995:     delete($accessed{$to_kick});
                   2996:     $kicks++;
                   2997:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2998:     return;
                   2999: }
                   3000: 
1.599     albertel 3001: sub purge_remembered {
1.604     albertel 3002:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3003:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3004:     undef(%remembered);
                   3005:     undef(%accessed);
1.428     albertel 3006: }
1.70      www      3007: # ------------------------------------- Read an entry from a user's environment
                   3008: 
                   3009: sub userenvironment {
                   3010:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3011:     my $items;
                   3012:     foreach my $item (@what) {
                   3013:         $items.=&escape($item).'&';
                   3014:     }
                   3015:     $items=~s/\&$//;
1.70      www      3016:     my %returnhash=();
1.1009    raeburn  3017:     my $uhome = &homeserver($unam,$udom);
                   3018:     unless ($uhome eq 'no_host') {
                   3019:         my @answer=split(/\&/, 
                   3020:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3021:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3022:             return %returnhash;
                   3023:         }
1.1009    raeburn  3024:         my $i;
                   3025:         for ($i=0;$i<=$#what;$i++) {
                   3026: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3027:         }
1.70      www      3028:     }
                   3029:     return %returnhash;
1.1       albertel 3030: }
                   3031: 
1.617     albertel 3032: # ---------------------------------------------------------- Get a studentphoto
                   3033: sub studentphoto {
                   3034:     my ($udom,$unam,$ext) = @_;
                   3035:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3036:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3037:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3038:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3039:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3040:             } else {
                   3041:                 my ($result,$perm_reqd)=
1.707     albertel 3042: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3043:                 if ($result eq 'ok') {
                   3044:                     if (!($perm_reqd eq 'yes')) {
                   3045:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3046:                     }
                   3047:                 }
                   3048:             }
                   3049:         }
                   3050:     } else {
                   3051:         my ($result,$perm_reqd) = 
1.707     albertel 3052: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3053:         if ($result eq 'ok') {
                   3054:             if (!($perm_reqd eq 'yes')) {
                   3055:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3056:             }
                   3057:         }
                   3058:     }
                   3059:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3060: }
                   3061: 
                   3062: sub retrievestudentphoto {
                   3063:     my ($udom,$unam,$ext,$type) = @_;
                   3064:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3065:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3066:     if ($ret eq 'ok') {
                   3067:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3068:         if ($type eq 'thumbnail') {
                   3069:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3070:         }
                   3071:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3072:         return $tokenurl;
                   3073:     } else {
                   3074:         if ($type eq 'thumbnail') {
                   3075:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3076:         } else { 
                   3077:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3078:         }
1.617     albertel 3079:     }
                   3080: }
                   3081: 
1.263     www      3082: # -------------------------------------------------------------------- New chat
                   3083: 
                   3084: sub chatsend {
1.724     raeburn  3085:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3086:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3087:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3088:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3089:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3090: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3091: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3092: }
                   3093: 
                   3094: # ------------------------------------------ Find current version of a resource
                   3095: 
                   3096: sub getversion {
                   3097:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3098:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3099:     return &currentversion(&filelocation('',$fname));
                   3100: }
                   3101: 
                   3102: sub currentversion {
                   3103:     my $fname=shift;
                   3104:     my $author=$fname;
                   3105:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3106:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3107:     my $home=&homeserver($uname,$udom);
1.292     www      3108:     if ($home eq 'no_host') { 
                   3109:         return -1; 
                   3110:     }
1.1112    www      3111:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3112:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3113: 	return -1;
                   3114:     }
1.1112    www      3115:     return $answer;
1.263     www      3116: }
                   3117: 
1.1111    www      3118: #
                   3119: # Return special version number of resource if set by override, empty otherwise
                   3120: #
                   3121: sub usedversion {
                   3122:     my $fname=shift;
                   3123:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3124:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3125:     if ($urlversion) { return $urlversion; }
                   3126:     return '';
                   3127: }
                   3128: 
1.1       albertel 3129: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3130: 
1.1       albertel 3131: sub subscribe {
                   3132:     my $fname=shift;
1.761     raeburn  3133:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3134:     $fname=~s/[\n\r]//g;
1.1       albertel 3135:     my $author=$fname;
                   3136:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3137:     my ($udom,$uname)=split(/\//,$author);
                   3138:     my $home=homeserver($uname,$udom);
1.335     albertel 3139:     if ($home eq 'no_host') {
                   3140:         return 'not_found';
1.1       albertel 3141:     }
                   3142:     my $answer=reply("sub:$fname",$home);
1.64      www      3143:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3144: 	$answer.=' by '.$home;
                   3145:     }
1.1       albertel 3146:     return $answer;
                   3147: }
                   3148:     
1.8       www      3149: # -------------------------------------------------------------- Replicate file
                   3150: 
                   3151: sub repcopy {
                   3152:     my $filename=shift;
1.23      www      3153:     $filename=~s/\/+/\//g;
1.1142    raeburn  3154:     my $londocroot = $perlvar{'lonDocRoot'};
                   3155:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3156:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3157:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3158: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3159: 	return &repcopy_userfile($filename);
                   3160:     }
1.532     albertel 3161:     $filename=~s/[\n\r]//g;
1.8       www      3162:     my $transname="$filename.in.transfer";
1.828     www      3163: # FIXME: this should flock
1.607     raeburn  3164:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3165:     my $remoteurl=subscribe($filename);
1.64      www      3166:     if ($remoteurl =~ /^con_lost by/) {
                   3167: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3168:            return 'unavailable';
1.8       www      3169:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3170: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3171: 	   return 'not_found';
1.64      www      3172:     } elsif ($remoteurl =~ /^rejected by/) {
                   3173: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3174:            return 'forbidden';
1.20      www      3175:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3176:            return 'ok';
1.8       www      3177:     } else {
1.290     www      3178:         my $author=$filename;
                   3179:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3180:         my ($udom,$uname)=split(/\//,$author);
                   3181:         my $home=homeserver($uname,$udom);
                   3182:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3183:            my @parts=split(/\//,$filename);
                   3184:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3185:            if ($path ne "$londocroot/res") {
1.8       www      3186:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3187: 	       return 'bad_request';
1.8       www      3188:            }
                   3189:            my $count;
                   3190:            for ($count=5;$count<$#parts;$count++) {
                   3191:                $path.="/$parts[$count]";
                   3192:                if ((-e $path)!=1) {
                   3193: 		   mkdir($path,0777);
                   3194:                }
                   3195:            }
                   3196:            my $ua=new LWP::UserAgent;
                   3197:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3198:            my $response=$ua->request($request,$transname);
                   3199:            if ($response->is_error()) {
                   3200: 	       unlink($transname);
                   3201:                my $message=$response->status_line;
1.672     albertel 3202:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3203:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3204:                return 'unavailable';
1.8       www      3205:            } else {
1.16      www      3206: 	       if ($remoteurl!~/\.meta$/) {
                   3207:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3208:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3209:                   if ($mresponse->is_error()) {
                   3210: 		      unlink($filename.'.meta');
                   3211:                       &logthis(
1.672     albertel 3212:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3213:                   }
                   3214: 	       }
1.8       www      3215:                rename($transname,$filename);
1.607     raeburn  3216:                return 'ok';
1.8       www      3217:            }
1.290     www      3218:        }
1.8       www      3219:     }
1.330     www      3220: }
                   3221: 
1.1172.2.124  raeburn  3222: # ------------------------------------------------- Unsubscribe from a resource
                   3223: 
                   3224: sub unsubscribe {
                   3225:     my ($fname) = @_;
                   3226:     my $answer;
                   3227:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3228:     $fname=~s/[\n\r]//g;
                   3229:     my $author=$fname;
                   3230:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3231:     my ($udom,$uname)=split(/\//,$author);
                   3232:     my $home=homeserver($uname,$udom);
                   3233:     if ($home eq 'no_host') {
                   3234:         $answer = 'no_host';
                   3235:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3236:         $answer = 'home';
                   3237:     } else {
1.1172.2.125  raeburn  3238:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3239:     }
                   3240:     return $answer;
                   3241: }
                   3242: 
1.330     www      3243: # ------------------------------------------------ Get server side include body
                   3244: sub ssi_body {
1.381     albertel 3245:     my ($filelink,%form)=@_;
1.606     matthew  3246:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3247:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3248:     }
1.953     www      3249:     my $output='';
                   3250:     my $response;
1.980     raeburn  3251:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3252:        ($output,$response)=&externalssi($filelink);
1.953     www      3253:     } else {
1.1004    droeschl 3254:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3255:        $filelink .= 'inhibitmenu=yes';
1.953     www      3256:        ($output,$response)=&ssi($filelink,%form);
                   3257:     }
1.778     albertel 3258:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3259:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3260:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3261:     if (wantarray) {
                   3262:         return ($output, $response);
                   3263:     } else {
                   3264:         return $output;
                   3265:     }
1.8       www      3266: }
                   3267: 
1.15      www      3268: # --------------------------------------------------------- Server Side Include
                   3269: 
1.782     albertel 3270: sub absolute_url {
1.1172.2.145  raeburn  3271:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3272:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3273:     if ($host_name eq '') {
                   3274: 	$host_name = $ENV{'SERVER_NAME'};
                   3275:     }
1.1172.2.145  raeburn  3276:     if ($unalias) {
                   3277:         my $alias = &get_proxy_alias();
                   3278:         if ($alias eq $host_name) {
                   3279:             my $lonhost = $perlvar{'lonHostID'};
                   3280:             my $hostname = &hostname($lonhost);
                   3281:             my $lcproto;
                   3282:             if (($keep_proto) || ($hostname eq '')) {
                   3283:                 $lcproto = $protocol;
                   3284:             } else {
                   3285:                 $lcproto = $protocol{$lonhost};
                   3286:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3287:                 $lcproto .= '://';
                   3288:             }
                   3289:             unless ($hostname eq '') {
                   3290:                 return $lcproto.$hostname;
                   3291:             }
                   3292:         }
                   3293:     } 
1.782     albertel 3294:     return $protocol.$host_name;
                   3295: }
                   3296: 
1.942     foxr     3297: #
                   3298: #   Server side include.
                   3299: # Parameters:
                   3300: #  fn     Possibly encrypted resource name/id.
                   3301: #  form   Hash that describes how the rendering should be done
                   3302: #         and other things.
1.944     foxr     3303: # Returns:
1.950     raeburn  3304: #   Scalar context: The content of the response.
                   3305: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3306: #     
1.15      www      3307: sub ssi {
                   3308: 
1.944     foxr     3309:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3310:     my ($host,$request,$response);
                   3311:     $host = &absolute_url('',1);
1.711     albertel 3312: 
                   3313:     $form{'no_update_last_known'}=1;
1.895     albertel 3314:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3315:     if (%form) {
1.1172.2.145  raeburn  3316:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3317:       $request->content(join('&',map {
                   3318:             my $name = escape($_);
                   3319:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3320:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3321:             : &escape($form{$_}) );
                   3322:         } keys(%form)));
1.23      www      3323:     } else {
1.1172.2.145  raeburn  3324:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3325:     }
                   3326: 
1.15      www      3327:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3328: 
1.1172.2.101  raeburn  3329:     if (($env{'request.course.id'}) &&
                   3330:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3331:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3332:         ($form{'grade_symb'} ne '') &&
                   3333:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3334:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3335:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3336:             my $ua=new LWP::UserAgent;
                   3337:             $ua->local_address('127.0.0.1');
                   3338:             $response = $ua->request($request);
                   3339:         } else {
                   3340:             {
                   3341:                 require LWP::Protocol::http;
                   3342:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3343:                 my $ua=new LWP::UserAgent;
                   3344:                 $response = $ua->request($request);
                   3345:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3346:             }
                   3347:         }
                   3348:     } else {
                   3349:         my $ua=new LWP::UserAgent;
                   3350:         $response = $ua->request($request);
                   3351:     }
1.944     foxr     3352:     if (wantarray) {
1.1172.2.3  raeburn  3353: 	return ($response->content, $response);
1.944     foxr     3354:     } else {
1.1172.2.3  raeburn  3355: 	return $response->content;
1.942     foxr     3356:     }
1.324     www      3357: }
                   3358: 
                   3359: sub externalssi {
                   3360:     my ($url)=@_;
                   3361:     my $ua=new LWP::UserAgent;
                   3362:     my $request=new HTTP::Request('GET',$url);
                   3363:     my $response=$ua->request($request);
1.954     raeburn  3364:     if (wantarray) {
                   3365:         return ($response->content, $response);
                   3366:     } else {
                   3367:         return $response->content;
                   3368:     }
1.15      www      3369: }
1.254     www      3370: 
1.1172.2.98  raeburn  3371: # If the local copy of a replicated resource is outdated, trigger a
                   3372: # connection from the homeserver to flush the delayed queue. If no update
                   3373: # happens, remove local copies of outdated resource (and corresponding
                   3374: # metadata file).
                   3375: 
                   3376: sub remove_stale_resfile {
                   3377:     my ($url) = @_;
                   3378:     my $removed;
                   3379:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3380:         my $audom = $1;
                   3381:         my $auname = $2;
                   3382:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3383:             my $homeserver = &homeserver($auname,$audom);
                   3384:             unless (($homeserver eq 'no_host') ||
                   3385:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3386:                 my $fname = &filelocation('',$url);
                   3387:                 if (-e $fname) {
                   3388:                     my $hostname = &hostname($homeserver);
                   3389:                     if ($hostname) {
1.1172.2.120  raeburn  3390:                         my $protocol = $protocol{$homeserver};
                   3391:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3392:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3393:                         my $ua=new LWP::UserAgent;
                   3394:                         $ua->timeout(5);
1.1172.2.98  raeburn  3395:                         my $request=new HTTP::Request('HEAD',$uri);
                   3396:                         my $response=$ua->request($request);
                   3397:                         if ($response->is_success()) {
                   3398:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3399:                             my $locmodtime = (stat($fname))[9];
                   3400:                             if ($locmodtime < $remmodtime) {
                   3401:                                 my $stale;
                   3402:                                 my $answer = &reply('pong',$homeserver);
                   3403:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3404:                                     sleep(0.2);
                   3405:                                     $locmodtime = (stat($fname))[9];
                   3406:                                     if ($locmodtime < $remmodtime) {
                   3407:                                         my $posstransfer = $fname.'.in.transfer';
                   3408:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3409:                                             $removed = 1;
                   3410:                                         } else {
                   3411:                                             $stale = 1;
                   3412:                                         }
                   3413:                                     } else {
                   3414:                                         $removed = 1;
                   3415:                                     }
                   3416:                                 } else {
                   3417:                                     $stale = 1;
                   3418:                                 }
                   3419:                                 if ($stale) {
1.1172.2.124  raeburn  3420:                                     if (unlink($fname)) {
                   3421:                                         if ($uri!~/\.meta$/) {
                   3422:                                             if (-e $fname.'.meta') {
                   3423:                                                 unlink($fname.'.meta');
                   3424:                                             }
                   3425:                                         }
                   3426:                                         my $unsubresult = &unsubscribe($fname);
                   3427:                                         unless ($unsubresult eq 'ok') {
                   3428:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3429:                                         }
                   3430:                                         $removed = 1;
1.1172.2.98  raeburn  3431:                                     }
                   3432:                                 }
                   3433:                             }
                   3434:                         }
                   3435:                     }
                   3436:                 }
                   3437:             }
                   3438:         }
                   3439:     }
                   3440:     return $removed;
                   3441: }
                   3442: 
1.492     albertel 3443: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3444: 
                   3445: sub allowuploaded {
                   3446:     my ($srcurl,$url)=@_;
                   3447:     $url=&clutter(&declutter($url));
                   3448:     my $dir=$url;
                   3449:     $dir=~s/\/[^\/]+$//;
                   3450:     my %httpref=();
                   3451:     my $httpurl=&hreflocation('',$url);
                   3452:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3453:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3454: }
1.477     raeburn  3455: 
1.1172.2.13  raeburn  3456: #
                   3457: # Determine if the current user should be able to edit a particular resource,
                   3458: # when viewing in course context.
                   3459: # (a) When viewing resource used to determine if "Edit" item is included in
                   3460: #     Functions.
                   3461: # (b) When displaying folder contents in course editor, used to determine if
                   3462: #     "Edit" link will be displayed alongside resource.
                   3463: #
                   3464: #  input: six args -- filename (decluttered), course number, course domain,
                   3465: #                   url, symb (if registered) and group (if this is a group
                   3466: #                   item -- e.g., bulletin board, group page etc.).
                   3467: #  output: array of five scalars --
                   3468: #          $cfile -- url for file editing if editable on current server
                   3469: #          $home -- homeserver of resource (i.e., for author if published,
                   3470: #                                           or course if uploaded.).
                   3471: #          $switchserver --  1 if server switch will be needed.
                   3472: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3473: #          $forceview -- 1 if icon/link should be to go to view mode
                   3474: #
                   3475: 
                   3476: sub can_edit_resource {
                   3477:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3478:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3479: #
                   3480: # For aboutme pages user can only edit his/her own.
                   3481: #
                   3482:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3483:         my ($sdom,$sname) = ($1,$2);
                   3484:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3485:             $home = $env{'user.home'};
                   3486:             $cfile = $resurl;
                   3487:             if ($env{'form.forceedit'}) {
                   3488:                 $forceview = 1;
                   3489:             } else {
                   3490:                 $forceedit = 1;
                   3491:             }
                   3492:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3493:         } else {
                   3494:             return;
                   3495:         }
                   3496:     }
                   3497: 
                   3498:     if ($env{'request.course.id'}) {
                   3499:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3500:         if ($group ne '') {
                   3501: # if this is a group homepage or group bulletin board, check group privs
                   3502:             my $allowed = 0;
                   3503:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3504:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3505:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3506:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3507:                     $allowed = 1;
                   3508:                 }
                   3509:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3510:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3511:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3512:                     $allowed = 1;
                   3513:                 }
                   3514:             }
                   3515:             if ($allowed) {
                   3516:                 $home=&homeserver($cnum,$cdom);
                   3517:                 if ($env{'form.forceedit'}) {
                   3518:                     $forceview = 1;
                   3519:                 } else {
                   3520:                     $forceedit = 1;
                   3521:                 }
                   3522:                 $cfile = $resurl;
                   3523:             } else {
                   3524:                 return;
                   3525:             }
                   3526:         } else {
1.1172.2.15  raeburn  3527:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3528:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3529:                     return;
                   3530:                 }
                   3531:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3532: #
                   3533: # No edit allowed where CC has switched to student role.
                   3534: #
                   3535:                 return;
                   3536:             }
                   3537:         }
                   3538:     }
                   3539: 
                   3540:     if ($file ne '') {
                   3541:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3542:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3543:                 $uploaded = 1;
                   3544:                 $incourse = 1;
                   3545:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3546:                     $cfile = &hreflocation('',$file);
                   3547:                     if ($env{'form.forceedit'}) {
                   3548:                         $forceview = 1;
                   3549:                     } else {
                   3550:                         $forceedit = 1;
                   3551:                     }
                   3552:                 }
                   3553:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3554:                 $incourse = 1;
                   3555:                 if ($env{'form.forceedit'}) {
                   3556:                     $forceview = 1;
                   3557:                 } else {
                   3558:                     $forceedit = 1;
                   3559:                 }
                   3560:                 $cfile = $resurl;
                   3561:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3562:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3563:                     $incourse = 1;
                   3564:                     if ($env{'form.forceedit'}) {
                   3565:                         $forceview = 1;
                   3566:                     } else {
                   3567:                         $forceedit = 1;
                   3568:                     }
                   3569:                     $cfile = $resurl;
                   3570:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3571:                     $incourse = 1;
                   3572:                     $cfile = $resurl.'/smpedit';
                   3573:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3574:                     $incourse = 1;
                   3575:                     if ($env{'form.forceedit'}) {
                   3576:                         $forceview = 1;
                   3577:                     } else {
                   3578:                         $forceedit = 1;
                   3579:                     }
                   3580:                     $cfile = $resurl;
1.1172.2.122  raeburn  3581:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3582:                     my ($map,$id,$res) = &decode_symb($symb);
                   3583:                     if ($map =~ /\.page$/) {
                   3584:                         $incourse = 1;
                   3585:                         if ($env{'form.forceedit'}) {
                   3586:                             $forceview = 1;
                   3587:                             $cfile = $map;
                   3588:                         } else {
                   3589:                             $forceedit = 1;
                   3590:                             $cfile =  '/adm/wrapper'.$resurl;
                   3591:                         }
                   3592:                     }
1.1172.2.146.  .1(raebu 3593:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3594:22):                     $incourse = 1;
                   3595:22):                     if ($env{'form.forceedit'}) {
                   3596:22):                         $forceview = 1;
                   3597:22):                     } else {
                   3598:22):                         $forceedit = 1;
                   3599:22):                     }
                   3600:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3601:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3602:                     $incourse = 1;
                   3603:                     if ($env{'form.forceedit'}) {
                   3604:                         $forceview = 1;
                   3605:                     } else {
                   3606:                         $forceedit = 1;
                   3607:                     }
                   3608:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3609:                 }
                   3610:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3611:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3612:                 if (&is_on_map($template)) {
                   3613:                     $incourse = 1;
                   3614:                     $forceview = 1;
                   3615:                     $cfile = $template;
                   3616:                 }
                   3617:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3618:                 $incourse = 1;
                   3619:                 if ($env{'form.forceedit'}) {
                   3620:                     $forceview = 1;
                   3621:                 } else {
                   3622:                     $forceedit = 1;
                   3623:                 }
                   3624:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3625:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3626:22):                 $incourse = 1;
                   3627:22):                 if ($env{'form.forceedit'}) {
                   3628:22):                     $forceview = 1;
                   3629:22):                 } else {
                   3630:22):                     $forceedit = 1;
                   3631:22):                 }
                   3632:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3633:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3634:                 $incourse = 1;
                   3635:                 $forceview = 1;
                   3636:                 if ($symb) {
                   3637:                     my ($map,$id,$res)=&decode_symb($symb);
                   3638:                     $env{'request.symb'} = $symb;
                   3639:                     $cfile = &clutter($res);
                   3640:                 } else {
                   3641:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3642:22):                     my $escfile = &unescape($cfile);
                   3643:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3644:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3645:22):                     } else {
                   3646:22):                         $escfile =~ s{^http://}{};
                   3647:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3648:22):                     }
1.1172.2.13  raeburn  3649:                 }
1.1172.2.31  raeburn  3650:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3651:                 if ($env{'form.forceedit'}) {
                   3652:                     $forceview = 1;
                   3653:                 } else {
                   3654:                     $forceedit = 1;
                   3655:                 }
                   3656:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3657:             }
                   3658:         }
                   3659:         if ($uploaded || $incourse) {
                   3660:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3661:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3662:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3663:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3664:             # Check that the user has permission to edit this resource
                   3665:             my $setpriv = 1;
                   3666:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3667:             if (defined($cfudom)) {
                   3668:                 $home=&homeserver($cfuname,$cfudom);
                   3669:                 $cfile=$file;
                   3670:             }
                   3671:         }
                   3672:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3673:             (($home ne '') && ($home ne 'no_host'))) {
                   3674:             my @ids=&current_machine_ids();
                   3675:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3676:                 $switchserver=1;
                   3677:             }
                   3678:         }
                   3679:     }
                   3680:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3681: }
                   3682: 
                   3683: sub is_course_upload {
                   3684:     my ($file,$cnum,$cdom) = @_;
                   3685:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3686:     $uploadpath =~ s{^\/}{};
                   3687:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3688:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3689:         return 1;
                   3690:     }
                   3691:     return;
                   3692: }
                   3693: 
                   3694: sub in_course {
                   3695:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3696:     if ($hideprivileged) {
                   3697:         my $skipuser;
1.1172.2.23  raeburn  3698:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3699:         my @possdoms = ($cdom);
                   3700:         if ($coursehash{'checkforpriv'}) {
                   3701:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3702:         }
                   3703:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3704:             $skipuser = 1;
                   3705:             if ($coursehash{'nothideprivileged'}) {
                   3706:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3707:                     my $user;
                   3708:                     if ($item =~ /:/) {
                   3709:                         $user = $item;
                   3710:                     } else {
                   3711:                         $user = join(':',split(/[\@]/,$item));
                   3712:                     }
                   3713:                     if ($user eq $uname.':'.$udom) {
                   3714:                         undef($skipuser);
                   3715:                         last;
                   3716:                     }
                   3717:                 }
                   3718:             }
                   3719:             if ($skipuser) {
                   3720:                 return 0;
                   3721:             }
                   3722:         }
                   3723:     }
                   3724:     $type ||= 'any';
                   3725:     if (!defined($cdom) || !defined($cnum)) {
                   3726:         my $cid  = $env{'request.course.id'};
                   3727:         $cdom = $env{'course.'.$cid.'.domain'};
                   3728:         $cnum = $env{'course.'.$cid.'.num'};
                   3729:     }
                   3730:     my $typesref;
                   3731:     if (($type eq 'any') || ($type eq 'all')) {
                   3732:         $typesref = ['active','previous','future'];
                   3733:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3734:         $typesref = [$type];
                   3735:     }
                   3736:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3737:                               $typesref,undef,[$cdom]);
                   3738:     my ($tmp) = keys(%roles);
                   3739:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3740:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3741:     if (@course_roles > 0) {
                   3742:         return 1;
                   3743:     }
                   3744:     return 0;
                   3745: }
                   3746: 
1.478     albertel 3747: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3748: # input: action, courseID, current domain, intended
1.637     raeburn  3749: #        path to file, source of file, instruction to parse file for objects,
                   3750: #        ref to hash for embedded objects,
                   3751: #        ref to hash for codebase of java objects.
1.1095    raeburn  3752: #        reference to scalar to accommodate mime type determined
                   3753: #          from File::MMagic if $parser = parse.
1.637     raeburn  3754: #
1.485     raeburn  3755: # output: url to file (if action was uploaddoc), 
                   3756: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3757: #
1.478     albertel 3758: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3759: # course.
1.477     raeburn  3760: #
1.478     albertel 3761: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3762: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3763: #          course's home server.
1.477     raeburn  3764: #
1.478     albertel 3765: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3766: #          be copied from $source (current location) to 
                   3767: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3768: #         and will then be copied to
                   3769: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3770: #         course's home server.
1.485     raeburn  3771: #
1.481     raeburn  3772: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3773: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3774: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3775: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3776: #         in course's home server.
1.637     raeburn  3777: #
1.477     raeburn  3778: 
                   3779: sub process_coursefile {
1.1095    raeburn  3780:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3781:         $mimetype)=@_;
1.477     raeburn  3782:     my $fetchresult;
1.638     albertel 3783:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3784:     if ($action eq 'propagate') {
1.638     albertel 3785:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3786: 			     $home);
1.481     raeburn  3787:     } else {
1.477     raeburn  3788:         my $fpath = '';
                   3789:         my $fname = $file;
1.478     albertel 3790:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3791:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3792:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3793:         if ($action eq 'copy') {
                   3794:             if ($source eq '') {
                   3795:                 $fetchresult = 'no source file';
                   3796:                 return $fetchresult;
                   3797:             } else {
                   3798:                 my $destination = $filepath.'/'.$fname;
                   3799:                 rename($source,$destination);
                   3800:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3801:                                  $home);
1.481     raeburn  3802:             }
                   3803:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3804:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3805:             print $fh $env{'form.'.$source};
1.481     raeburn  3806:             close($fh);
1.637     raeburn  3807:             if ($parser eq 'parse') {
1.1024    raeburn  3808:                 my $mm = new File::MMagic;
1.1095    raeburn  3809:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3810:                 if ($type eq 'text/html') {
1.1024    raeburn  3811:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3812:                     unless ($parse_result eq 'ok') {
                   3813:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3814:                     }
1.637     raeburn  3815:                 }
1.1095    raeburn  3816:                 if (ref($mimetype)) {
                   3817:                     $$mimetype = $type;
                   3818:                 } 
1.637     raeburn  3819:             }
1.477     raeburn  3820:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3821:                                  $home);
1.481     raeburn  3822:             if ($fetchresult eq 'ok') {
                   3823:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3824:             } else {
                   3825:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3826:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3827:                 return '/adm/notfound.html';
                   3828:             }
1.477     raeburn  3829:         }
                   3830:     }
1.485     raeburn  3831:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3832:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3833:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3834:     }
                   3835:     return $fetchresult;
                   3836: }
                   3837: 
1.637     raeburn  3838: sub build_filepath {
                   3839:     my ($fpath) = @_;
                   3840:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3841:     unless ($fpath eq '') {
                   3842:         my @parts=split('/',$fpath);
                   3843:         foreach my $part (@parts) {
                   3844:             $filepath.= '/'.$part;
                   3845:             if ((-e $filepath)!=1) {
                   3846:                 mkdir($filepath,0777);
                   3847:             }
                   3848:         }
                   3849:     }
                   3850:     return $filepath;
                   3851: }
                   3852: 
                   3853: sub store_edited_file {
1.638     albertel 3854:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3855:     my $file = $primary_url;
                   3856:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3857:     my $fpath = '';
                   3858:     my $fname = $file;
                   3859:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3860:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3861:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3862:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3863:     print $fh $content;
                   3864:     close($fh);
1.638     albertel 3865:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3866:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3867: 			  $home);
1.637     raeburn  3868:     if ($$fetchresult eq 'ok') {
                   3869:         return '/uploaded/'.$fpath.'/'.$fname;
                   3870:     } else {
1.638     albertel 3871:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3872: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3873:         return '/adm/notfound.html';
                   3874:     }
                   3875: }
                   3876: 
1.531     albertel 3877: sub clean_filename {
1.831     albertel 3878:     my ($fname,$args)=@_;
1.315     www      3879: # Replace Windows backslashes by forward slashes
1.257     www      3880:     $fname=~s/\\/\//g;
1.831     albertel 3881:     if (!$args->{'keep_path'}) {
                   3882:         # Get rid of everything but the actual filename
                   3883: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3884:     }
1.315     www      3885: # Replace spaces by underscores
                   3886:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3887: # Transliterate non-ascii text to ascii
                   3888:     my $lang = &Apache::lonlocal::current_language();
                   3889:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3890: # Replace all other weird characters by nothing
1.831     albertel 3891:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3892: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3893: # numbers
                   3894:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3895: # Replace three or more adjacent underscores with one for consistency
                   3896: # with loncfile::filename_check() so complete url can be extracted by
                   3897: # lonnet::decode_symb()
                   3898:     $fname=~s/_{3,}/_/g;
1.531     albertel 3899:     return $fname;
                   3900: }
1.1172.2.110  raeburn  3901: 
1.1051    raeburn  3902: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3903: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3904: # image with the same aspect ratio as the original, but with dimensions which do 
                   3905: # not exceed $resizewidth and $resizeheight.
                   3906:  
1.984     neumanie 3907: sub resizeImage {
1.1051    raeburn  3908:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3909:     my $ima = Image::Magick->new;
                   3910:     my $resized;
                   3911:     if (-e $img_path) {
                   3912:         $ima->Read($img_path);
                   3913:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3914:             my $width = $ima->Get('width');
                   3915:             my $height = $ima->Get('height');
                   3916:             if ($width > $resizewidth) {
                   3917: 	        my $factor = $width/$resizewidth;
                   3918:                 my $newheight = $height/$factor;
                   3919:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3920:                 $resized = 1;
                   3921:             }
                   3922:         }
                   3923:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3924:             my $width = $ima->Get('width');
                   3925:             my $height = $ima->Get('height');
                   3926:             if ($height > $resizeheight) {
                   3927:                 my $factor = $height/$resizeheight;
                   3928:                 my $newwidth = $width/$factor;
                   3929:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3930:                 $resized = 1;
                   3931:             }
                   3932:         }
                   3933:         if ($resized) {
                   3934:             $ima->Write($img_path);
                   3935:         }
                   3936:     }
                   3937:     return;
1.977     amueller 3938: }
                   3939: 
1.608     albertel 3940: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3941: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3942: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3943: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3944: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3945: #                   if 'coursedoc': upload to the current course
                   3946: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3947: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3948: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3949: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3950: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3951: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3952: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3953: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3954: #        $allfiles - reference to hash for embedded objects
                   3955: #        $codebase - reference to hash for codebase of java objects
                   3956: #        $desuname - username for permanent storage of uploaded file
                   3957: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3958: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3959: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3960: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3961: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3962: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3963: #                    from File::MMagic.
1.858     raeburn  3964: # 
1.686     albertel 3965: # output: url of file in userspace, or error: <message> 
                   3966: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3967: 
1.531     albertel 3968: sub userfileupload {
1.1090    raeburn  3969:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3970:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3971:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3972:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3973:     $fname=&clean_filename($fname);
1.1090    raeburn  3974:     # See if there is anything left
1.257     www      3975:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3976:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3977:     if ($fname =~ /^\./) {
                   3978:         my ($s,$usec) = &gettimeofday();
                   3979:         while (length($usec) < 6) {
                   3980:             $usec = '0'.$usec;
                   3981:         }
                   3982:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3983:     }
1.1090    raeburn  3984:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3985:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3986:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3987:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3988:         my $now = time;
1.1090    raeburn  3989:         my $filepath;
1.1095    raeburn  3990:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3991:              $filepath = 'tmp/helprequests/'.$now;
                   3992:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3993:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3994:                          '_'.$env{'user.domain'}.'/pending';
                   3995:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3996:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3997:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3998:                 $docudom = $destudom;
                   3999:             } else {
                   4000:                 $docudom = $env{'user.domain'};
                   4001:             }
1.1172.2.96  raeburn  4002:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4003:                 $docuname = $destuname;
                   4004:             } else {
                   4005:                 $docuname = $env{'user.name'};
                   4006:             }
                   4007:             if (exists($env{'form.group'})) {
                   4008:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4009:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4010:             }
                   4011:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4012:             if ($context eq 'canceloverwrite') {
                   4013:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4014:                 if (-e  $tempfile) {
                   4015:                     my @info = stat($tempfile);
                   4016:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4017:                         unlink($tempfile);
                   4018:                     }
                   4019:                 }
                   4020:                 return;
1.523     raeburn  4021:             }
                   4022:         }
1.1090    raeburn  4023:         # Create the directory if not present
1.741     raeburn  4024:         my @parts=split(/\//,$filepath);
                   4025:         my $fullpath = $perlvar{'lonDaemons'};
                   4026:         for (my $i=0;$i<@parts;$i++) {
                   4027:             $fullpath .= '/'.$parts[$i];
                   4028:             if ((-e $fullpath)!=1) {
                   4029:                 mkdir($fullpath,0777);
                   4030:             }
                   4031:         }
1.1172.2.96  raeburn  4032:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4033:         print $fh $env{'form.'.$formname};
                   4034:         close($fh);
1.1090    raeburn  4035:         if ($context eq 'existingfile') {
                   4036:             my @info = stat($fullpath.'/'.$fname);
                   4037:             return ($fullpath.'/'.$fname,$info[9]);
                   4038:         } else {
                   4039:             return $fullpath.'/'.$fname;
                   4040:         }
1.523     raeburn  4041:     }
1.995     raeburn  4042:     if ($subdir eq 'scantron') {
                   4043:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4044:     } else {
1.995     raeburn  4045:         $fname="$subdir/$fname";
                   4046:     }
1.1090    raeburn  4047:     if ($context eq 'coursedoc') {
1.638     albertel 4048: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4049: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4050:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4051:             return &finishuserfileupload($docuname,$docudom,
                   4052: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4053: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4054:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4055:         } else {
1.1172.2.21  raeburn  4056:             if ($env{'form.folder'}) {
                   4057:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4058:             }
1.638     albertel 4059:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4060: 				       $fname,$formname,$parser,
1.1095    raeburn  4061: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4062:         }
1.719     banghart 4063:     } elsif (defined($destuname)) {
                   4064:         my $docuname=$destuname;
                   4065:         my $docudom=$destudom;
1.860     raeburn  4066: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4067: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4068:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4069:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4070:     } else {
1.638     albertel 4071:         my $docuname=$env{'user.name'};
                   4072:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4073:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4074:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4075:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4076:         }
1.860     raeburn  4077: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4078: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4079:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4080:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4081:     }
1.271     www      4082: }
                   4083: 
                   4084: sub finishuserfileupload {
1.860     raeburn  4085:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4086:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4087:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4088:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4089:   
1.860     raeburn  4090:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4091:     $file=$fname;
                   4092:     if ($fname=~m|/|) {
                   4093:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4094: 	$path.=$fnamepath.'/';
                   4095:     }
1.259     www      4096:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4097:     my $count;
                   4098:     for ($count=4;$count<=$#parts;$count++) {
                   4099:         $filepath.="/$parts[$count]";
                   4100:         if ((-e $filepath)!=1) {
                   4101: 	    mkdir($filepath,0777);
                   4102:         }
                   4103:     }
1.984     neumanie 4104: 
1.258     www      4105: # Save the file
                   4106:     {
1.1172.2.96  raeburn  4107: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4108: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4109: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4110: 	    return '/adm/notfound.html';
                   4111: 	}
1.1090    raeburn  4112:         if ($context eq 'overwrite') {
1.1117    foxr     4113:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4114:             my $target = $filepath.'/'.$file;
                   4115:             if (-e $source) {
                   4116:                 my @info = stat($source);
                   4117:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4118:                     unless (&File::Copy::move($source,$target)) {
                   4119:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4120:                         return "Moving from $source failed";
                   4121:                     }
                   4122:                 } else {
                   4123:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4124:                 }
                   4125:             } else {
                   4126:                 return "Temporary file: $source missing";
                   4127:             }
                   4128:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4129: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4130: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4131: 	    return '/adm/notfound.html';
                   4132: 	}
1.570     albertel 4133: 	close(FH);
1.1051    raeburn  4134:         if ($resizewidth && $resizeheight) {
                   4135:             my $mm = new File::MMagic;
                   4136:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4137:             if ($mime_type =~ m{^image/}) {
                   4138: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4139:             }  
1.977     amueller 4140: 	}
1.258     www      4141:     }
1.1152    raeburn  4142:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4143:         if (ref($mimetype)) {
                   4144:             if ($$mimetype eq '') {
                   4145:                 my $mm = new File::MMagic;
                   4146:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4147:                 $$mimetype = $type;
                   4148:             }
                   4149:         }
                   4150:     }
1.1172.2.109  raeburn  4151:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4152:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4153:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4154:                                                        $allfiles,$codebase);
                   4155:             unless ($parse_result eq 'ok') {
                   4156:                 &logthis('Failed to parse '.$filepath.$file.
                   4157: 	   	         ' for embedded media: '.$parse_result); 
                   4158:             }
1.637     raeburn  4159:         }
1.1172.2.109  raeburn  4160:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4161:         my $format = $env{'form.scantron_format'};
                   4162:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4163:     }
1.860     raeburn  4164:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4165:         my $input = $filepath.'/'.$file;
                   4166:         my $output = $filepath.'/'.'tn-'.$file;
                   4167:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4168:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4169:         system({$args[0]} @args);
1.860     raeburn  4170:         if (-e $filepath.'/'.'tn-'.$file) {
                   4171:             $fetchthumb  = 1; 
                   4172:         }
                   4173:     }
1.858     raeburn  4174:  
1.259     www      4175: # Notify homeserver to grep it
                   4176: #
1.984     neumanie 4177:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4178:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4179:     if ($fetchresult eq 'ok') {
1.860     raeburn  4180:         if ($fetchthumb) {
                   4181:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4182:             if ($thumbresult ne 'ok') {
                   4183:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4184:                          $docuhome.': '.$thumbresult);
                   4185:             }
                   4186:         }
1.259     www      4187: #
1.258     www      4188: # Return the URL to it
1.494     albertel 4189:         return '/uploaded/'.$path.$file;
1.263     www      4190:     } else {
1.494     albertel 4191:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4192: 		 ': '.$fetchresult);
1.263     www      4193:         return '/adm/notfound.html';
1.858     raeburn  4194:     }
1.493     albertel 4195: }
                   4196: 
1.637     raeburn  4197: sub extract_embedded_items {
1.961     raeburn  4198:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4199:     my @state = ();
1.1164    raeburn  4200:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4201:     my %javafiles = (
                   4202:                       codebase => '',
                   4203:                       code => '',
                   4204:                       archive => ''
                   4205:                     );
                   4206:     my %mediafiles = (
                   4207:                       src => '',
                   4208:                       movie => '',
                   4209:                      );
1.648     raeburn  4210:     my $p;
                   4211:     if ($content) {
                   4212:         $p = HTML::LCParser->new($content);
                   4213:     } else {
1.961     raeburn  4214:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4215:     }
1.641     albertel 4216:     while (my $t=$p->get_token()) {
1.640     albertel 4217: 	if ($t->[0] eq 'S') {
                   4218: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4219: 	    push(@state, $tagname);
1.648     raeburn  4220:             if (lc($tagname) eq 'allow') {
                   4221:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4222:             }
1.640     albertel 4223: 	    if (lc($tagname) eq 'img') {
                   4224: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4225: 	    }
1.886     albertel 4226: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4227:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4228: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4229:                 }
1.886     albertel 4230: 	    }
1.645     raeburn  4231:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4232:                 my $src;
1.645     raeburn  4233:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4234:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4235:                 } else {
1.1164    raeburn  4236:                     if ($attr->{'src'} ne '') {
                   4237:                         $src = $attr->{'src'};
                   4238:                         &add_filetype($allfiles,$src,'src');
                   4239:                     }
                   4240:                 }
                   4241:                 my $text = $p->get_trimmed_text();
                   4242:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4243:                     my @swfargs = split(/,/,$1);
                   4244:                     foreach my $item (@swfargs) {
                   4245:                         $item =~ s/["']//g;
                   4246:                         $item =~ s/^\s+//;
                   4247:                         $item =~ s/\s+$//;
                   4248:                     }
                   4249:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4250:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4251:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4252:                         } else {
                   4253:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4254:                         }
                   4255:                     }
1.645     raeburn  4256:                 }
                   4257:             }
                   4258:             if (lc($tagname) eq 'link') {
                   4259:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4260:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4261:                 }
                   4262:             }
1.640     albertel 4263: 	    if (lc($tagname) eq 'object' ||
                   4264: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4265: 		foreach my $item (keys(%javafiles)) {
                   4266: 		    $javafiles{$item} = '';
                   4267: 		}
1.1164    raeburn  4268:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4269:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4270:                 }
1.640     albertel 4271: 	    }
                   4272: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4273: 		my $name = lc($attr->{'name'});
                   4274: 		foreach my $item (keys(%javafiles)) {
                   4275: 		    if ($name eq $item) {
                   4276: 			$javafiles{$item} = $attr->{'value'};
                   4277: 			last;
                   4278: 		    }
                   4279: 		}
1.1164    raeburn  4280:                 my $pathfrom;
1.640     albertel 4281: 		foreach my $item (keys(%mediafiles)) {
                   4282: 		    if ($name eq $item) {
1.1164    raeburn  4283:                         $pathfrom = $attr->{'value'};
                   4284:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4285: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4286: 			last;
                   4287: 		    }
                   4288: 		}
1.1164    raeburn  4289:                 if ($name eq 'flashvars') {
                   4290:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4291:                 }
                   4292:                 if ($pathfrom ne '') {
                   4293:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4294:                                          $pathfrom);
                   4295:                 }
1.640     albertel 4296: 	    }
                   4297: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4298: 		foreach my $item (keys(%javafiles)) {
                   4299: 		    if ($attr->{$item}) {
                   4300: 			$javafiles{$item} = $attr->{$item};
                   4301: 			last;
                   4302: 		    }
                   4303: 		}
                   4304: 		foreach my $item (keys(%mediafiles)) {
                   4305: 		    if ($attr->{$item}) {
                   4306: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4307: 			last;
                   4308: 		    }
                   4309: 		}
1.1164    raeburn  4310:                 if (lc($tagname) eq 'embed') {
                   4311:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4312:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4313:                                              $attr->{'src'});
                   4314:                     }
                   4315:                 }
1.640     albertel 4316: 	    }
1.1172.2.35  raeburn  4317:             if (lc($tagname) eq 'iframe') {
                   4318:                 my $src = $attr->{'src'} ;
                   4319:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4320:                     &add_filetype($allfiles,$src,'src');
                   4321:                 } elsif ($src =~ m{^/}) {
                   4322:                     if ($env{'request.course.id'}) {
                   4323:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4324:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4325:                         my $url = &hreflocation('',$fullpath);
                   4326:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4327:                             my $relpath = $1;
                   4328:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4329:                                 &add_filetype($allfiles,$1,'src');
                   4330:                             }
                   4331:                         }
                   4332:                     }
                   4333:                 }
                   4334:             }
1.1164    raeburn  4335:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4336:                 pop(@state);
1.1164    raeburn  4337:             }
1.640     albertel 4338: 	} elsif ($t->[0] eq 'E') {
                   4339: 	    my ($tagname) = ($t->[1]);
                   4340: 	    if ($javafiles{'codebase'} ne '') {
                   4341: 		$javafiles{'codebase'} .= '/';
                   4342: 	    }  
                   4343: 	    if (lc($tagname) eq 'applet' ||
                   4344: 		lc($tagname) eq 'object' ||
                   4345: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4346: 		) {
                   4347: 		foreach my $item (keys(%javafiles)) {
                   4348: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4349: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4350: 			&add_filetype($allfiles,$file,$item);
                   4351: 		    }
                   4352: 		}
                   4353: 	    } 
                   4354: 	    pop @state;
                   4355: 	}
                   4356:     }
1.1164    raeburn  4357:     foreach my $id (sort(keys(%flashvars))) {
                   4358:         if ($shockwave{$id} ne '') {
                   4359:             my @pairs = split(/\&/,$flashvars{$id});
                   4360:             foreach my $pair (@pairs) {
                   4361:                 my ($key,$value) = split(/\=/,$pair);
                   4362:                 if ($key eq 'thumb') {
                   4363:                     &add_filetype($allfiles,$value,$key);
                   4364:                 } elsif ($key eq 'content') {
                   4365:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4366:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4367:                     if ($ext ne '') {
                   4368:                         &add_filetype($allfiles,$path.$value,$ext);
                   4369:                     }
                   4370:                 }
                   4371:             }
                   4372:         }
                   4373:     }
1.637     raeburn  4374:     return 'ok';
                   4375: }
                   4376: 
1.639     albertel 4377: sub add_filetype {
                   4378:     my ($allfiles,$file,$type)=@_;
                   4379:     if (exists($allfiles->{$file})) {
                   4380: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4381: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4382: 	}
                   4383:     } else {
                   4384: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4385:     }
                   4386: }
                   4387: 
1.1164    raeburn  4388: sub embedded_dependency {
                   4389:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4390:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4391:         if (($identifier ne '') &&
                   4392:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4393:             ($pathfrom ne '')) {
                   4394:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4395:             foreach my $dep (@{$related->{$identifier}}) {
                   4396:                 &add_filetype($allfiles,$path.$dep,'object');
                   4397:             }
                   4398:         }
                   4399:     }
                   4400:     return;
                   4401: }
                   4402: 
1.1172.2.109  raeburn  4403: sub bubblesheet_converter {
                   4404:     my ($cdom,$fullpath,$config,$format) = @_;
                   4405:     if ((&domain($cdom) ne '') &&
                   4406:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4407:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4408:         my (%csvcols,%csvoptions);
                   4409:         if (ref($config->{'fields'}) eq 'HASH') {
                   4410:             %csvcols = %{$config->{'fields'}};
                   4411:         }
                   4412:         if (ref($config->{'options'}) eq 'HASH') {
                   4413:             %csvoptions = %{$config->{'options'}};
                   4414:         }
                   4415:         my %csvbynum = reverse(%csvcols);
                   4416:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4417:         if (keys(%scantronconf)) {
                   4418:             my %bynum = (
                   4419:                           $scantronconf{CODEstart} => 'CODEstart',
                   4420:                           $scantronconf{IDstart}   => 'IDstart',
                   4421:                           $scantronconf{PaperID}   => 'PaperID',
                   4422:                           $scantronconf{FirstName} => 'FirstName',
                   4423:                           $scantronconf{LastName}  => 'LastName',
                   4424:                           $scantronconf{Qstart}    => 'Qstart',
                   4425:                         );
                   4426:             my @ordered;
                   4427:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4428:                 push(@ordered,$bynum{$item});
                   4429:             }
                   4430:             my %mapstart = (
                   4431:                               CODEstart => 'CODE',
                   4432:                               IDstart   => 'ID',
                   4433:                               PaperID   => 'PaperID',
                   4434:                               FirstName => 'FirstName',
                   4435:                               LastName  => 'LastName',
                   4436:                               Qstart    => 'FirstQuestion',
                   4437:                            );
                   4438:             my %maplength = (
                   4439:                               CODEstart => 'CODElength',
                   4440:                               IDstart   => 'IDlength',
                   4441:                               PaperID   => 'PaperIDlength',
                   4442:                               FirstName => 'FirstNamelength',
                   4443:                               LastName  => 'LastNamelength',
                   4444:             );
                   4445:             if (open(my $fh,'<',$fullpath)) {
                   4446:                 my $output;
                   4447:                 my %lettdig = &letter_to_digits();
                   4448:                 my %diglett = reverse(%lettdig);
                   4449:                 my $numletts = scalar(keys(%lettdig));
                   4450:                 my $num = 0;
                   4451:                 while (my $line=<$fh>) {
                   4452:                     $num ++;
                   4453:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4454:                     $line =~ s{[\r\n]+$}{};
                   4455:                     my %found;
1.1172.2.143  raeburn  4456:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4457:                     my ($qstart,$record);
                   4458:                     for (my $i=0; $i<@values; $i++) {
                   4459:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4460:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4461:                             if ($values[$i] eq '') {
                   4462:                                 $values[$i] = $scantronconf{'Qoff'};
                   4463:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4464:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4465:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4466:                                 }
                   4467:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4468:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4469:                                     $values[$i] = $diglett{$values[$i]};
                   4470:                                 }
                   4471:                             } else {
                   4472:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4473:                                     my $digit;
                   4474:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4475:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4476:                                         if ($values[$i] eq 'J') {
                   4477:                                             $digit += $numletts;
                   4478:                                         }
                   4479:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4480:                                         $digit = $values[$i]-1;
                   4481:                                         if ($values[$i] eq '0') {
                   4482:                                             $digit += $numletts;
                   4483:                                         }
                   4484:                                     }
                   4485:                                     my $qval='';
                   4486:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4487:                                         if ($j == $digit) {
                   4488:                                             $qval .= $scantronconf{'Qon'};
                   4489:                                         } else {
                   4490:                                             $qval .= $scantronconf{'Qoff'};
                   4491:                                         }
                   4492:                                     }
                   4493:                                     $values[$i] = $qval;
                   4494:                                 }
                   4495:                             }
                   4496:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4497:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4498:                             }
                   4499:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4500:                             if ($numblank > 0) {
                   4501:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4502:                             }
                   4503:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4504:                                 $qstart = $i;
                   4505:                                 $found{$csvbynum{$i}} = $values[$i];
                   4506:                             } else {
                   4507:                                 $found{'FirstQuestion'} .= $values[$i];
                   4508:                             }
                   4509:                         } elsif (exists($csvbynum{$i})) {
                   4510:                             if ($csvoptions{'rem'}) {
                   4511:                                 $values[$i] =~ s/^\s+//;
                   4512:                             }
                   4513:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4514:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4515:                                     $values[$i] = '0'.$values[$i];
                   4516:                                 }
                   4517:                             }
                   4518:                             $found{$csvbynum{$i}} = $values[$i];
                   4519:                         }
                   4520:                     }
                   4521:                     foreach my $item (@ordered) {
                   4522:                         my $currlength = 1+length($record);
                   4523:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4524:                         if ($numspaces > 0) {
                   4525:                             $record .= (' ' x $numspaces);
                   4526:                         }
                   4527:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4528:                             unless ($item eq 'Qstart') {
                   4529:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4530:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4531:                                 }
                   4532:                             }
                   4533:                             $record .= $found{$mapstart{$item}};
                   4534:                         }
                   4535:                     }
                   4536:                     $output .= "$record\n";
                   4537:                 }
                   4538:                 close($fh);
                   4539:                 if ($output) {
                   4540:                     if (open(my $fh,'>',$fullpath)) {
                   4541:                         print $fh $output;
                   4542:                         close($fh);
                   4543:                     }
                   4544:                 }
                   4545:             }
                   4546:         }
                   4547:         return;
                   4548:     }
                   4549: }
                   4550: 
                   4551: sub letter_to_digits {
                   4552:     my %lettdig = (
                   4553:                     A => 1,
                   4554:                     B => 2,
                   4555:                     C => 3,
                   4556:                     D => 4,
                   4557:                     E => 5,
                   4558:                     F => 6,
                   4559:                     G => 7,
                   4560:                     H => 8,
                   4561:                     I => 9,
                   4562:                     J => 0,
                   4563:                   );
                   4564:     return %lettdig;
                   4565: }
                   4566: 
                   4567: sub get_scantron_config {
                   4568:     my ($which,$cdom) = @_;
                   4569:     my @lines = &get_scantronformat_file($cdom);
                   4570:     my %config;
                   4571:     #FIXME probably should move to XML it has already gotten a bit much now
                   4572:     foreach my $line (@lines) {
                   4573:         my ($name,$descrip)=split(/:/,$line);
                   4574:         if ($name ne $which ) { next; }
                   4575:         chomp($line);
                   4576:         my @config=split(/:/,$line);
                   4577:         $config{'name'}=$config[0];
                   4578:         $config{'description'}=$config[1];
                   4579:         $config{'CODElocation'}=$config[2];
                   4580:         $config{'CODEstart'}=$config[3];
                   4581:         $config{'CODElength'}=$config[4];
                   4582:         $config{'IDstart'}=$config[5];
                   4583:         $config{'IDlength'}=$config[6];
                   4584:         $config{'Qstart'}=$config[7];
                   4585:         $config{'Qlength'}=$config[8];
                   4586:         $config{'Qoff'}=$config[9];
                   4587:         $config{'Qon'}=$config[10];
                   4588:         $config{'PaperID'}=$config[11];
                   4589:         $config{'PaperIDlength'}=$config[12];
                   4590:         $config{'FirstName'}=$config[13];
                   4591:         $config{'FirstNamelength'}=$config[14];
                   4592:         $config{'LastName'}=$config[15];
                   4593:         $config{'LastNamelength'}=$config[16];
                   4594:         $config{'BubblesPerRow'}=$config[17];
                   4595:         last;
                   4596:     }
                   4597:     return %config;
                   4598: }
                   4599: 
                   4600: sub get_scantronformat_file {
                   4601:     my ($cdom) = @_;
                   4602:     if ($cdom eq '') {
                   4603:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4604:     }
                   4605:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4606:     my $gottab = 0;
                   4607:     my @lines;
                   4608:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4609:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4610:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4611:             if ($formatfile ne '-1') {
                   4612:                 @lines = split("\n",$formatfile,-1);
                   4613:                 $gottab = 1;
                   4614:             }
                   4615:         }
                   4616:     }
                   4617:     if (!$gottab) {
                   4618:         my $confname = $cdom.'-domainconfig';
                   4619:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4620:         my $formatfile = &getfile($default);
                   4621:         if ($formatfile ne '-1') {
                   4622:             @lines = split("\n",$formatfile,-1);
                   4623:             $gottab = 1;
                   4624:         }
                   4625:     }
                   4626:     if (!$gottab) {
                   4627:         my @domains = &current_machine_domains();
                   4628:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4629:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4630:                 @lines = <$fh>;
                   4631:                 close($fh);
                   4632:             }
                   4633:         } else {
                   4634:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4635:                 @lines = <$fh>;
                   4636:                 close($fh);
                   4637:             }
                   4638:         }
                   4639:     }
                   4640:     return @lines;
                   4641: }
                   4642: 
1.493     albertel 4643: sub removeuploadedurl {
1.984     neumanie 4644:     my ($url)=@_;	
                   4645:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4646:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4647: }
                   4648: 
                   4649: sub removeuserfile {
                   4650:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4651:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4652:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4653:     if ($result eq 'ok') {	
1.798     raeburn  4654:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4655:             my $metafile = $fname.'.meta';
                   4656:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4657: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4658:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4659:             my $sqlresult = 
1.823     albertel 4660:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4661:                                         'portfolio_metadata',$group,
                   4662:                                         'delete');
1.798     raeburn  4663:         }
                   4664:     }
                   4665:     return $result;
1.257     www      4666: }
1.15      www      4667: 
1.530     albertel 4668: sub mkdiruserfile {
                   4669:     my ($docuname,$docudom,$dir)=@_;
                   4670:     my $home=&homeserver($docuname,$docudom);
                   4671:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4672: }
                   4673: 
1.531     albertel 4674: sub renameuserfile {
                   4675:     my ($docuname,$docudom,$old,$new)=@_;
                   4676:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4677:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4678:                         &escape("$old").':'.&escape("$new"),$home);
                   4679:     if ($result eq 'ok') {
                   4680:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4681:             my $oldmeta = $old.'.meta';
                   4682:             my $newmeta = $new.'.meta';
                   4683:             my $metaresult = 
                   4684:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4685: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4686:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4687:             my $sqlresult = 
1.823     albertel 4688:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4689:                                         'portfolio_metadata',$group,
                   4690:                                         'delete');
1.798     raeburn  4691:         }
                   4692:     }
                   4693:     return $result;
1.531     albertel 4694: }
                   4695: 
1.14      www      4696: # ------------------------------------------------------------------------- Log
                   4697: 
                   4698: sub log {
                   4699:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4700:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4701: }
                   4702: 
                   4703: # ------------------------------------------------------------------ Course Log
1.352     www      4704: #
                   4705: # This routine flushes several buffers of non-mission-critical nature
                   4706: #
1.157     www      4707: 
                   4708: sub flushcourselogs {
1.352     www      4709:     &logthis('Flushing log buffers');
                   4710: #
                   4711: # course logs
                   4712: # This is a log of all transactions in a course, which can be used
                   4713: # for data mining purposes
                   4714: #
                   4715: # It also collects the courseid database, which lists last transaction
                   4716: # times and course titles for all courseids
                   4717: #
                   4718:     my %courseidbuffer=();
1.921     raeburn  4719:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4720:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4721: 		          &escape($courselogs{$crsid}),
                   4722: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4723: 	    delete $courselogs{$crsid};
                   4724:         } else {
                   4725:             &logthis('Failed to flush log buffer for '.$crsid);
                   4726:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4727:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4728:                         " exceeded maximum size, deleting.</font>");
                   4729:                delete $courselogs{$crsid};
                   4730:             }
1.352     www      4731:         }
1.920     raeburn  4732:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4733:             'description' => $coursedescrbuf{$crsid},
                   4734:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4735:             'type'        => $coursetypebuf{$crsid},
                   4736:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4737:         };
1.191     harris41 4738:     }
1.352     www      4739: #
                   4740: # Write course id database (reverse lookup) to homeserver of courses 
                   4741: # Is used in pickcourse
                   4742: #
1.840     albertel 4743:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4744:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4745:                                     $courseidbuffer{$crs_home},
                   4746:                                     $crs_home,'timeonly');
1.352     www      4747:     }
                   4748: #
                   4749: # File accesses
                   4750: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4751: #
1.449     matthew  4752:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4753:         if ($entry =~ /___count$/) {
                   4754:             my ($dom,$name);
1.807     albertel 4755:             ($dom,$name,undef)=
1.811     albertel 4756: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4757:             if (! defined($dom) || $dom eq '' || 
                   4758:                 ! defined($name) || $name eq '') {
1.620     albertel 4759:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4760: #
                   4761: # FIXME 11/29/2021
                   4762: # Typo in rev. 1.458 (2003/12/09)??
                   4763: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4764: #
                   4765: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4766: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4767: # in a nohist_accesscount.db file for the user rather than the course.
                   4768: #
                   4769: # That said there is a lot of noise in the data being stored.
                   4770: # So counts for prtspool/  and adm/ etc. are recorded.
                   4771: #
                   4772: # A review of which items ending '___count' are written to %accesshash should likely be
                   4773: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4774: #
                   4775: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4776: # accesses for things which are not published resources, regardless of course, and
                   4777: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4778: # anyone in the course for things which are not published resources.
                   4779: #
                   4780: # For an author, nohist_accesscount.db ends up having records for other items
                   4781: # mixed up with the legitimate access counts for the author's published resources.
                   4782: #
1.620     albertel 4783:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4784:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4785:             }
1.450     matthew  4786:             my $value = $accesshash{$entry};
                   4787:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4788:             my %temphash=($url => $value);
1.449     matthew  4789:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4790:             if ($result eq 'ok') {
                   4791:                 delete $accesshash{$entry};
                   4792:             }
                   4793:         } else {
1.811     albertel 4794:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4795:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4796:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4797:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4798:                 delete $accesshash{$entry};
                   4799:             }
1.185     www      4800:         }
1.191     harris41 4801:     }
1.352     www      4802: #
                   4803: # Roles
                   4804: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4805: #
1.800     albertel 4806:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4807:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4808: 	    split(/\:/,$entry);
                   4809:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4810:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4811:                 $rudom,$runame) eq 'ok') {
                   4812: 	    delete $userrolehash{$entry};
                   4813:         }
                   4814:     }
1.662     raeburn  4815: #
1.1172.2.90  raeburn  4816: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4817: #
                   4818:     my %domrolebuffer = ();
1.1000    raeburn  4819:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4820:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4821:         if ($domrolebuffer{$rudom}) {
                   4822:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4823:                       '='.&escape($domainrolehash{$entry});
                   4824:         } else {
                   4825:             $domrolebuffer{$rudom}.=&escape($entry).
                   4826:                       '='.&escape($domainrolehash{$entry});
                   4827:         }
                   4828:         delete $domainrolehash{$entry};
                   4829:     }
                   4830:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4831:         my %servers;
                   4832:         if (defined(&domain($dom,'primary'))) {
                   4833:             my $primary=&domain($dom,'primary');
                   4834:             my $hostname=&hostname($primary);
                   4835:             $servers{$primary} = $hostname;
                   4836:         } else {
                   4837:             %servers = &get_servers($dom,'library');
                   4838:         }
1.841     albertel 4839: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4840: 	    if (&reply('domroleput:'.$dom.':'.
                   4841: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4842: 	        last;
                   4843: 	    } else {
1.841     albertel 4844: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4845: 	    }
1.662     raeburn  4846:         }
                   4847:     }
1.186     www      4848:     $dumpcount++;
1.157     www      4849: }
                   4850: 
                   4851: sub courselog {
                   4852:     my $what=shift;
1.158     www      4853:     $what=time.':'.$what;
1.620     albertel 4854:     unless ($env{'request.course.id'}) { return ''; }
                   4855:     $coursedombuf{$env{'request.course.id'}}=
                   4856:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4857:     $coursenumbuf{$env{'request.course.id'}}=
                   4858:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4859:     $coursehombuf{$env{'request.course.id'}}=
                   4860:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4861:     $coursedescrbuf{$env{'request.course.id'}}=
                   4862:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4863:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4864:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4865:     $courseownerbuf{$env{'request.course.id'}}=
                   4866:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4867:     $coursetypebuf{$env{'request.course.id'}}=
                   4868:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4869:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4870: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4871:     } else {
1.620     albertel 4872: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4873:     }
1.620     albertel 4874:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4875: 	&flushcourselogs();
                   4876:     }
1.158     www      4877: }
                   4878: 
                   4879: sub courseacclog {
                   4880:     my $fnsymb=shift;
1.620     albertel 4881:     unless ($env{'request.course.id'}) { return ''; }
                   4882:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4883:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4884:         $what.=':POST';
1.583     matthew  4885:         # FIXME: Probably ought to escape things....
1.800     albertel 4886: 	foreach my $key (keys(%env)) {
                   4887:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4888:                 my $formitem = $1;
                   4889:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4890:                     $what.=':'.$formitem.'='.$env{$key};
                   4891:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4892:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4893:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4894:                     } else {
                   4895:                         $what.=':'.$formitem.'='.$env{$key};
                   4896:                     }
1.975     raeburn  4897:                 }
1.158     www      4898:             }
1.191     harris41 4899:         }
1.583     matthew  4900:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4901:         # FIXME: We should not be depending on a form parameter that someone
                   4902:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4903:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4904:             $what.= ':POST';
                   4905:             # FIXME: Probably ought to escape things....
                   4906:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4907:                                  'crsdiscuss') {
1.620     albertel 4908:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4909:             }
                   4910:         }
1.158     www      4911:     }
                   4912:     &courselog($what);
1.149     www      4913: }
                   4914: 
1.185     www      4915: sub countacc {
                   4916:     my $url=&declutter(shift);
1.458     matthew  4917:     return if (! defined($url) || $url eq '');
1.620     albertel 4918:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4919: #
                   4920: # Mark that this url was used in this course
                   4921: #
1.620     albertel 4922:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4923: #
                   4924: # Increase the access count for this resource in this child process
                   4925: #
1.281     www      4926:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4927:     $accesshash{$key}++;
1.185     www      4928: }
1.349     www      4929: 
1.361     www      4930: sub linklog {
                   4931:     my ($from,$to)=@_;
                   4932:     $from=&declutter($from);
                   4933:     $to=&declutter($to);
                   4934:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4935:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4936: }
1.1160    www      4937: 
                   4938: sub statslog {
                   4939:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4940:     if ($users<2) { return; }
                   4941:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4942:             'course'       => $env{'request.course.id'},
                   4943:             'sections'     => '"all"',
                   4944:             'num_students' => $users,
                   4945:             'part'         => $part,
                   4946:             'symb'         => $symb,
                   4947:             'mean_tries'   => $av_attempts,
                   4948:             'deg_of_diff'  => $degdiff});
                   4949:     foreach my $key (keys(%dynstore)) {
                   4950:         $accesshash{$key}=$dynstore{$key};
                   4951:     }
                   4952: }
1.361     www      4953:   
1.349     www      4954: sub userrolelog {
                   4955:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4956:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4957:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4958:        $userrolehash
                   4959:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4960:                     =$tend.':'.$tstart;
1.662     raeburn  4961:     }
1.1169    droeschl 4962:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4963:        $userrolehash
                   4964:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4965:                     =$tend.':'.$tstart;
                   4966:     }
1.1172.2.90  raeburn  4967:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4968:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4969:        $domainrolehash
                   4970:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4971:                     = $tend.':'.$tstart;
                   4972:     }
1.351     www      4973: }
                   4974: 
1.957     raeburn  4975: sub courserolelog {
                   4976:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4977:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4978:         my $cdom = $1;
                   4979:         my $cnum = $2;
                   4980:         my $sec = $3;
                   4981:         my $namespace = 'rolelog';
                   4982:         my %storehash = (
                   4983:                            role    => $trole,
                   4984:                            start   => $tstart,
                   4985:                            end     => $tend,
                   4986:                            selfenroll => $selfenroll,
                   4987:                            context    => $context,
                   4988:                         );
                   4989:         if ($trole eq 'gr') {
                   4990:             $namespace = 'groupslog';
                   4991:             $storehash{'group'} = $sec;
                   4992:         } else {
                   4993:             $storehash{'section'} = $sec;
                   4994:         }
                   4995:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4996:                    $domain,$cnum,$cdom);
                   4997:         if (($trole ne 'st') || ($sec ne '')) {
                   4998:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4999:         }
                   5000:     }
                   5001:     return;
                   5002: }
                   5003: 
1.1172.2.9  raeburn  5004: sub domainrolelog {
                   5005:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5006:     if ($area =~ m{^/($match_domain)/$}) {
                   5007:         my $cdom = $1;
                   5008:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5009:         my $namespace = 'rolelog';
                   5010:         my %storehash = (
                   5011:                            role    => $trole,
                   5012:                            start   => $tstart,
                   5013:                            end     => $tend,
                   5014:                            context => $context,
                   5015:                         );
                   5016:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5017:                    $domain,$domconfiguser,$cdom);
                   5018:     }
                   5019:     return;
                   5020: 
                   5021: }
                   5022: 
                   5023: sub coauthorrolelog {
                   5024:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5025:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5026:         my $audom = $1;
                   5027:         my $auname = $2;
                   5028:         my $namespace = 'rolelog';
                   5029:         my %storehash = (
                   5030:                            role    => $trole,
                   5031:                            start   => $tstart,
                   5032:                            end     => $tend,
                   5033:                            context => $context,
                   5034:                         );
                   5035:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5036:                    $domain,$auname,$audom);
                   5037:     }
                   5038:     return;
                   5039: }
                   5040: 
1.351     www      5041: sub get_course_adv_roles {
1.948     raeburn  5042:     my ($cid,$codes) = @_;
1.620     albertel 5043:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5044:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5045:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5046:     my %nothide=();
1.800     albertel 5047:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5048:         if ($user !~ /:/) {
                   5049: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5050:         } else {
                   5051:             $nothide{$user}=1;
                   5052:         }
1.470     www      5053:     }
1.1172.2.23  raeburn  5054:     my @possdoms = ($coursehash{'domain'});
                   5055:     if ($coursehash{'checkforpriv'}) {
                   5056:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5057:     }
1.351     www      5058:     my %returnhash=();
                   5059:     my %dumphash=
                   5060:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5061:     my $now=time;
1.997     raeburn  5062:     my %privileged;
1.1000    raeburn  5063:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5064: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5065:         if (($tstart) && ($tstart<0)) { next; }
                   5066:         if (($tend) && ($tend<$now)) { next; }
                   5067:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5068:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5069: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5070:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5071:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5072: 	if ($role eq 'cr') { next; }
1.948     raeburn  5073:         if ($codes) {
                   5074:             if ($section) { $role .= ':'.$section; }
                   5075:             if ($returnhash{$role}) {
                   5076:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5077:             } else {
                   5078:                 $returnhash{$role}=$username.':'.$domain;
                   5079:             }
1.351     www      5080:         } else {
1.988     raeburn  5081:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5082:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5083:             if ($returnhash{$key}) {
                   5084: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5085:             } else {
                   5086:                 $returnhash{$key}=$username.':'.$domain;
                   5087:             }
1.351     www      5088:         }
1.948     raeburn  5089:     }
1.400     www      5090:     return %returnhash;
                   5091: }
                   5092: 
                   5093: sub get_my_roles {
1.937     raeburn  5094:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5095:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5096:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5097:     my (%dumphash,%nothide);
1.1086    raeburn  5098:     if ($context eq 'userroles') {
1.1166    raeburn  5099:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5100:     } else {
1.1172.2.23  raeburn  5101:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5102:         if ($hidepriv) {
                   5103:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5104:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5105:                 if ($user !~ /:/) {
                   5106:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5107:                 } else {
                   5108:                     $nothide{$user} = 1;
                   5109:                 }
                   5110:             }
                   5111:         }
1.858     raeburn  5112:     }
1.400     www      5113:     my %returnhash=();
                   5114:     my $now=time;
1.999     raeburn  5115:     my %privileged;
1.800     albertel 5116:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5117:         my ($role,$tend,$tstart);
                   5118:         if ($context eq 'userroles') {
1.1149    raeburn  5119:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5120: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5121:         } else {
                   5122:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5123:         }
1.400     www      5124:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5125:         my $status = 'active';
1.939     raeburn  5126:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5127:             $status = 'previous';
                   5128:         } 
                   5129:         if (($tstart) && ($now<$tstart)) {
                   5130:             $status = 'future';
                   5131:         }
                   5132:         if (ref($types) eq 'ARRAY') {
                   5133:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5134:                 next;
                   5135:             } 
                   5136:         } else {
                   5137:             if ($status ne 'active') {
                   5138:                 next;
                   5139:             }
                   5140:         }
1.867     raeburn  5141:         my ($rolecode,$username,$domain,$section,$area);
                   5142:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5143:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5144:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5145:         } else {
                   5146:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5147:         }
1.832     raeburn  5148:         if (ref($roledoms) eq 'ARRAY') {
                   5149:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5150:                 next;
                   5151:             }
                   5152:         }
                   5153:         if (ref($roles) eq 'ARRAY') {
                   5154:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5155:                 if ($role =~ /^cr\//) {
                   5156:                     if (!grep(/^cr$/,@{$roles})) {
                   5157:                         next;
                   5158:                     }
1.1104    raeburn  5159:                 } elsif ($role =~ /^gr\//) {
                   5160:                     if (!grep(/^gr$/,@{$roles})) {
                   5161:                         next;
                   5162:                     }
1.922     raeburn  5163:                 } else {
                   5164:                     next;
                   5165:                 }
1.832     raeburn  5166:             }
1.867     raeburn  5167:         }
1.937     raeburn  5168:         if ($hidepriv) {
1.1172.2.23  raeburn  5169:             my @privroles = ('dc','su');
1.999     raeburn  5170:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5171:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5172:             } else {
1.1172.2.23  raeburn  5173:                 my $possdoms = [$domain];
                   5174:                 if (ref($roledoms) eq 'ARRAY') {
                   5175:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5176:                 }
1.1172.2.23  raeburn  5177:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5178:                     if (!$nothide{$username.':'.$domain}) {
                   5179:                         next;
                   5180:                     }
                   5181:                 }
1.937     raeburn  5182:             }
                   5183:         }
1.933     raeburn  5184:         if ($withsec) {
                   5185:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5186:                 $tstart.':'.$tend;
                   5187:         } else {
                   5188:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5189:         }
1.832     raeburn  5190:     }
1.373     www      5191:     return %returnhash;
1.399     www      5192: }
                   5193: 
1.1172.2.89  raeburn  5194: sub get_all_adhocroles {
                   5195:     my ($dom) = @_;
                   5196:     my @roles_by_num = ();
                   5197:     my %domdefaults = &get_domain_defaults($dom);
                   5198:     my (%description,%access_in_dom,%access_info);
                   5199:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5200:         my $count = 0;
                   5201:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5202:         my %ordered;
                   5203:         foreach my $role (sort(keys(%domcurrent))) {
                   5204:             my ($order,$desc,$access_in_dom);
                   5205:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5206:                 $order = $domcurrent{$role}{'order'};
                   5207:                 $desc = $domcurrent{$role}{'desc'};
                   5208:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5209:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5210:             }
                   5211:             if ($order eq '') {
                   5212:                 $order = $count;
                   5213:             }
                   5214:             $ordered{$order} = $role;
                   5215:             if ($desc ne '') {
                   5216:                 $description{$role} = $desc;
                   5217:             } else {
                   5218:                 $description{$role}= $role;
                   5219:             }
                   5220:             $count++;
                   5221:         }
                   5222:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5223:             push(@roles_by_num,$ordered{$item});
                   5224:         }
                   5225:     }
                   5226:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5227: }
                   5228: 
                   5229: sub get_my_adhocroles {
                   5230:     my ($cid,$checkreg) = @_;
                   5231:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5232:     if ($env{'request.course.id'} eq $cid) {
                   5233:         $cdom = $env{'course.'.$cid.'.domain'};
                   5234:         $cnum = $env{'course.'.$cid.'.num'};
                   5235:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5236:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5237:         $cdom = $1;
                   5238:         $cnum = $2;
                   5239:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5240:                                      $cdom,$cnum);
                   5241:     }
                   5242:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5243:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5244:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5245:         if ($rosterhash{$user} ne '') {
                   5246:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5247:             return ([],{}) if ($type eq 'auto');
                   5248:         }
                   5249:     }
                   5250:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5251:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5252:             my $then=$env{'user.login.time'};
                   5253:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5254:             if (!$update) {
                   5255:                 $update = $then;
                   5256:             }
                   5257:             my @liveroles;
                   5258:             foreach my $role ('dh','da') {
                   5259:                 if ($env{"user.role.$role./$cdom/"}) {
                   5260:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5261:                     my $limit = $update;
                   5262:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5263:                         $limit = $then;
                   5264:                     }
                   5265:                     my $activerole = 1;
                   5266:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5267:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5268:                     if ($activerole) {
                   5269:                         push(@liveroles,$role);
                   5270:                     }
                   5271:                 }
                   5272:             }
                   5273:             if (@liveroles) {
1.1172.2.89  raeburn  5274:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5275:                     my ($accessref,$accessinfo,%access_in_dom);
                   5276:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5277:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5278:                         if (@{$roles_by_num}) {
                   5279:                             my %settings;
                   5280:                             if ($env{'request.course.id'} eq $cid) {
                   5281:                                 foreach my $envkey (keys(%env)) {
                   5282:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5283:                                         $settings{$1} = $env{$envkey};
                   5284:                                     }
                   5285:                                 }
                   5286:                             } else {
                   5287:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5288:                             }
                   5289:                             my %setincrs;
                   5290:                             if ($settings{'internal.adhocaccess'}) {
                   5291:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5292:                             }
                   5293:                             my @statuses;
                   5294:                             if ($env{'environment.inststatus'}) {
                   5295:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5296:                             }
                   5297:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5298:                             if (ref($accessref) eq 'HASH') {
                   5299:                                 %access_in_dom = %{$accessref};
                   5300:                             }
                   5301:                             foreach my $role (@{$roles_by_num}) {
                   5302:                                 my ($curraccess,@okstatus,@personnel);
                   5303:                                 if ($setincrs{$role}) {
                   5304:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5305:                                     if ($curraccess eq 'status') {
                   5306:                                         @okstatus = split(/\&/,$rest);
                   5307:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5308:                                         @personnel = split(/\&/,$rest);
                   5309:                                     }
                   5310:                                 } else {
                   5311:                                     $curraccess = $access_in_dom{$role};
                   5312:                                     if (ref($accessinfo) eq 'HASH') {
                   5313:                                         if ($curraccess eq 'status') {
                   5314:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5315:                                                 @okstatus = @{$accessinfo->{$role}};
                   5316:                                             }
                   5317:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5318:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5319:                                                 @personnel = @{$accessinfo->{$role}};
                   5320:                                             }
                   5321:                                         }
                   5322:                                     }
                   5323:                                 }
                   5324:                                 if ($curraccess eq 'none') {
                   5325:                                     next;
                   5326:                                 } elsif ($curraccess eq 'all') {
                   5327:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5328:                                 } elsif ($curraccess eq 'dh') {
                   5329:                                     if (grep(/^dh$/,@liveroles)) {
                   5330:                                         push(@possroles,$role);
                   5331:                                     } else {
                   5332:                                         next;
                   5333:                                     }
                   5334:                                 } elsif ($curraccess eq 'da') {
                   5335:                                     if (grep(/^da$/,@liveroles)) {
                   5336:                                         push(@possroles,$role);
                   5337:                                     } else {
                   5338:                                         next;
                   5339:                                     }
1.1172.2.89  raeburn  5340:                                 } elsif ($curraccess eq 'status') {
                   5341:                                     if (@okstatus) {
                   5342:                                         if (!@statuses) {
                   5343:                                             if (grep(/^default$/,@okstatus)) {
                   5344:                                                 push(@possroles,$role);
                   5345:                                             }
                   5346:                                         } else {
                   5347:                                             foreach my $status (@okstatus) {
                   5348:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5349:                                                     push(@possroles,$role);
                   5350:                                                     last;
                   5351:                                                 }
                   5352:                                             }
                   5353:                                         }
                   5354:                                     }
                   5355:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5356:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5357:                                         if ($curraccess eq 'exc') {
                   5358:                                             push(@possroles,$role);
                   5359:                                         }
                   5360:                                     } elsif ($curraccess eq 'inc') {
                   5361:                                         push(@possroles,$role);
                   5362:                                     }
                   5363:                                 }
                   5364:                             }
                   5365:                         }
                   5366:                     }
                   5367:                 }
                   5368:             }
                   5369:         }
                   5370:     }
                   5371:     unless (ref($description) eq 'HASH') {
                   5372:         if (ref($roles_by_num) eq 'ARRAY') {
                   5373:             my %desc;
                   5374:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5375:             $description = \%desc;
                   5376:         } else {
                   5377:             $description = {};
                   5378:         }
                   5379:     }
                   5380:     return (\@possroles,$description);
                   5381: }
                   5382: 
1.399     www      5383: # ----------------------------------------------------- Frontpage Announcements
                   5384: #
                   5385: #
                   5386: 
                   5387: sub postannounce {
                   5388:     my ($server,$text)=@_;
1.844     albertel 5389:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5390:     unless ($text=~/\w/) { $text=''; }
                   5391:     return &reply('setannounce:'.&escape($text),$server);
                   5392: }
                   5393: 
                   5394: sub getannounce {
1.448     albertel 5395: 
1.1172.2.96  raeburn  5396:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5397: 	my $announcement='';
1.800     albertel 5398: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5399: 	close($fh);
1.399     www      5400: 	if ($announcement=~/\w/) { 
                   5401: 	    return 
                   5402:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5403:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5404: 	} else {
                   5405: 	    return '';
                   5406: 	}
                   5407:     } else {
                   5408: 	return '';
                   5409:     }
1.351     www      5410: }
1.353     www      5411: 
                   5412: # ---------------------------------------------------------- Course ID routines
                   5413: # Deal with domain's nohist_courseid.db files
                   5414: #
                   5415: 
                   5416: sub courseidput {
1.921     raeburn  5417:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5418:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5419:     my $outcome;
                   5420:     if ($caller eq 'timeonly') {
                   5421:         my $cids = '';
                   5422:         foreach my $item (keys(%$storehash)) {
                   5423:             $cids.=&escape($item).'&';
                   5424:         }
                   5425:         $cids=~s/\&$//;
                   5426:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5427:                           $coursehome);       
                   5428:     } else {
                   5429:         my $items = '';
                   5430:         foreach my $item (keys(%$storehash)) {
                   5431:             $items.= &escape($item).'='.
                   5432:                      &freeze_escape($$storehash{$item}).'&';
                   5433:         }
                   5434:         $items=~s/\&$//;
                   5435:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5436:                           $coursehome);
1.918     raeburn  5437:     }
                   5438:     if ($outcome eq 'unknown_cmd') {
                   5439:         my $what;
                   5440:         foreach my $cid (keys(%$storehash)) {
                   5441:             $what .= &escape($cid).'=';
1.921     raeburn  5442:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5443:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5444:             }
                   5445:             $what =~ s/\:$/&/;
                   5446:         }
                   5447:         $what =~ s/\&$//;  
                   5448:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5449:     } else {
                   5450:         return $outcome;
                   5451:     }
1.353     www      5452: }
                   5453: 
                   5454: sub courseiddump {
1.921     raeburn  5455:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5456:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5457:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5458:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5459:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5460:     my $as_hash = 1;
                   5461:     my %returnhash;
                   5462:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5463:     my %libserv = &all_library();
                   5464:     foreach my $tryserver (keys(%libserv)) {
                   5465:         if ( (  $hostidflag == 1 
                   5466: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5467: 	     || (!defined($hostidflag)) ) {
                   5468: 
1.918     raeburn  5469: 	    if (($domfilter eq '') ||
                   5470: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5471:                 my $rep;
                   5472:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5473:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5474:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5475:                                 &escape($descfilter), &escape($instcodefilter),
                   5476:                                 &escape($ownerfilter), &escape($coursefilter),
                   5477:                                 &escape($typefilter), &escape($regexp_ok),
                   5478:                                 $as_hash, &escape($selfenrollonly),
                   5479:                                 &escape($catfilter), $showhidden, $caller,
                   5480:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5481:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5482:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5483:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5484:                 } else {
                   5485:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5486:                              $sincefilter.':'.&escape($descfilter).':'.
                   5487:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5488:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5489:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5490:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5491:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5492:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5493:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5494:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5495:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5496:                 }
                   5497: 
1.918     raeburn  5498:                 my @pairs=split(/\&/,$rep);
                   5499:                 foreach my $item (@pairs) {
                   5500:                     my ($key,$value)=split(/\=/,$item,2);
                   5501:                     $key = &unescape($key);
                   5502:                     next if ($key =~ /^error: 2 /);
                   5503:                     my $result = &thaw_unescape($value);
                   5504:                     if (ref($result) eq 'HASH') {
                   5505:                         $returnhash{$key}=$result;
                   5506:                     } else {
1.921     raeburn  5507:                         my @responses = split(/:/,$value);
                   5508:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5509:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5510:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5511:                         }
1.1008    raeburn  5512:                     }
1.353     www      5513:                 }
                   5514:             }
                   5515:         }
                   5516:     }
                   5517:     return %returnhash;
                   5518: }
                   5519: 
1.1055    raeburn  5520: sub courselastaccess {
                   5521:     my ($cdom,$cnum,$hostidref) = @_;
                   5522:     my %returnhash;
                   5523:     if ($cdom && $cnum) {
                   5524:         my $chome = &homeserver($cnum,$cdom);
                   5525:         if ($chome ne 'no_host') {
                   5526:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5527:             &extract_lastaccess(\%returnhash,$rep);
                   5528:         }
                   5529:     } else {
                   5530:         if (!$cdom) { $cdom=''; }
                   5531:         my %libserv = &all_library();
                   5532:         foreach my $tryserver (keys(%libserv)) {
                   5533:             if (ref($hostidref) eq 'ARRAY') {
                   5534:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5535:             } 
                   5536:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5537:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5538:                 &extract_lastaccess(\%returnhash,$rep);
                   5539:             }
                   5540:         }
                   5541:     }
                   5542:     return %returnhash;
                   5543: }
                   5544: 
                   5545: sub extract_lastaccess {
                   5546:     my ($returnhash,$rep) = @_;
                   5547:     if (ref($returnhash) eq 'HASH') {
                   5548:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5549:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5550:                  $rep eq '') {
                   5551:             my @pairs=split(/\&/,$rep);
                   5552:             foreach my $item (@pairs) {
                   5553:                 my ($key,$value)=split(/\=/,$item,2);
                   5554:                 $key = &unescape($key);
                   5555:                 next if ($key =~ /^error: 2 /);
                   5556:                 $returnhash->{$key} = &thaw_unescape($value);
                   5557:             }
                   5558:         }
                   5559:     }
                   5560:     return;
                   5561: }
                   5562: 
1.658     raeburn  5563: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5564: 
                   5565: sub dcmailput {
1.685     raeburn  5566:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5567:     my $status = &Apache::lonnet::critical(
1.740     www      5568:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5569:        &escape($message),$server);
1.662     raeburn  5570:     return $status;
                   5571: }
                   5572: 
1.658     raeburn  5573: sub dcmaildump {
                   5574:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5575:     my %returnhash=();
1.846     albertel 5576: 
                   5577:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5578:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5579:                                                          &escape($enddate).':';
                   5580: 	my @esc_senders=map { &escape($_)} @$senders;
                   5581: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5582: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5583:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5584:             if (($key) && ($value)) {
                   5585:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5586:             }
                   5587:         }
                   5588:     }
                   5589:     return %returnhash;
                   5590: }
1.662     raeburn  5591: # ---------------------------------------------------------- Domain roles
                   5592: 
                   5593: sub get_domain_roles {
                   5594:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5595:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5596:         $startdate = '.';
                   5597:     }
1.1018    raeburn  5598:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5599:         $enddate = '.';
                   5600:     }
1.922     raeburn  5601:     my $rolelist;
                   5602:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5603:         $rolelist = join('&',@{$roles});
1.922     raeburn  5604:     }
1.662     raeburn  5605:     my %personnel = ();
1.841     albertel 5606: 
                   5607:     my %servers = &get_servers($dom,'library');
                   5608:     foreach my $tryserver (keys(%servers)) {
                   5609: 	%{$personnel{$tryserver}}=();
                   5610: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5611: 					    &escape($startdate).':'.
                   5612: 					    &escape($enddate).':'.
                   5613: 					    &escape($rolelist), $tryserver))) {
                   5614: 	    my ($key,$value) = split(/\=/,$line,2);
                   5615: 	    if (($key) && ($value)) {
                   5616: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5617: 	    }
                   5618: 	}
1.662     raeburn  5619:     }
                   5620:     return %personnel;
                   5621: }
1.658     raeburn  5622: 
1.1172.2.89  raeburn  5623: sub get_active_domroles {
                   5624:     my ($dom,$roles) = @_;
                   5625:     return () unless (ref($roles) eq 'ARRAY');
                   5626:     my $now = time;
                   5627:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5628:     my %domroles;
                   5629:     foreach my $server (keys(%dompersonnel)) {
                   5630:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5631:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5632:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5633:         }
                   5634:     }
                   5635:     return %domroles;
                   5636: }
                   5637: 
1.1057    www      5638: # ----------------------------------------------------------- Interval timing 
1.149     www      5639: 
1.1153    www      5640: {
                   5641: # Caches needed for speedup of navmaps
                   5642: # We don't want to cache this for very long at all (5 seconds at most)
                   5643: # 
                   5644: # The user for whom we cache
                   5645: my $cachedkey='';
                   5646: # The cached times for this user
                   5647: my %cachedtimes=();
                   5648: # When this was last done
1.1172.2.66  raeburn  5649: my $cachedtime='';
1.1153    www      5650: 
                   5651: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5652:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5653:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5654:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5655:22):         (!$ignorecache)) {
1.1154    raeburn  5656:         return;
                   5657:     }
                   5658:     $cachedtime=time;
                   5659:     $cachedkey=$uname.':'.$udom;
                   5660:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5661: }
                   5662: 
1.504     albertel 5663: sub get_first_access {
1.1172.2.146.  .1(raebu 5664:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5665:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5666:     if ($argsymb) { $symb=$argsymb; }
                   5667:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5668:     if ($argmap) { $map = $argmap; }
1.926     albertel 5669:     if ($type eq 'course') {
                   5670: 	$res='course';
                   5671:     } elsif ($type eq 'map') {
1.588     albertel 5672: 	$res=&symbread($map);
                   5673:     } else {
                   5674: 	$res=$symb;
                   5675:     }
1.1172.2.146.  .1(raebu 5676:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5677:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5678: }
                   5679: 
                   5680: sub set_first_access {
1.1162    raeburn  5681:     my ($type,$interval)=@_;
1.790     albertel 5682:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5683:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5684:     if ($type eq 'course') {
                   5685: 	$res='course';
                   5686:     } elsif ($type eq 'map') {
1.588     albertel 5687: 	$res=&symbread($map);
                   5688:     } else {
                   5689: 	$res=$symb;
                   5690:     }
1.1153    www      5691:     $cachedkey='';
1.1162    raeburn  5692:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5693:     if ($firstaccess) {
                   5694:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5695:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5696:                  "in $courseid");
                   5697:         return 'already_set';
                   5698:     } else {
1.1162    raeburn  5699:         my $start = time;
                   5700: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5701:                           $udom,$uname);
                   5702:         if ($putres eq 'ok') {
                   5703:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5704:                  $udom,$uname); 
                   5705:             &appenv(
                   5706:                      {
                   5707:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5708:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5709:                      }
                   5710:                   );
1.1172.2.97  raeburn  5711:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5712:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5713:             }
1.1172.2.102  raeburn  5714:         } elsif ($putres ne 'refused') {
                   5715:             &logthis("Result: $putres when attempting to set first access time ".
                   5716:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5717:         }
                   5718:         return $putres;
1.505     albertel 5719:     }
                   5720:     return 'already_set';
1.504     albertel 5721: }
1.1153    www      5722: }
1.1172.2.32  raeburn  5723: 
                   5724: sub checkout {
                   5725:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5726:     my $now=time;
                   5727:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5728:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5729:     my $infostr=&escape(
                   5730:                  'CHECKOUTTOKEN&'.
                   5731:                  $tuname.'&'.
                   5732:                  $tudom.'&'.
                   5733:                  $tcrsid.'&'.
                   5734:                  $symb.'&'.
1.1172.2.134  raeburn  5735:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5736:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5737:     if ($token=~/^error\:/) {
                   5738:         &logthis("<font color=\"blue\">WARNING: ".
                   5739:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5740:                  "</font>");
                   5741:         return '';
                   5742:     }
                   5743: 
                   5744:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5745:     $token=~tr/a-z/A-Z/;
                   5746: 
                   5747:     my %infohash=('resource.0.outtoken' => $token,
                   5748:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5749:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5750: 
                   5751:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5752:        return '';
                   5753:     } else {
                   5754:         &logthis("<font color=\"blue\">WARNING: ".
                   5755:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5756:                  "</font>");
                   5757:     }
                   5758: 
                   5759:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5760:                          &escape('Checkout '.$infostr.' - '.
                   5761:                                                  $token)) ne 'ok') {
                   5762:         return '';
                   5763:     } else {
                   5764:         &logthis("<font color=\"blue\">WARNING: ".
                   5765:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5766:                  "</font>");
                   5767:     }
                   5768:     return $token;
                   5769: }
                   5770: 
                   5771: # ------------------------------------------------------------ Check in an item
                   5772: 
                   5773: sub checkin {
                   5774:     my $token=shift;
                   5775:     my $now=time;
                   5776:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5777:     $lonhost=~tr/A-Z/a-z/;
                   5778:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5779:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5780:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5781:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5782:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5783: 
                   5784:     unless (($tuname) && ($tudom)) {
                   5785:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5786:         return '';
                   5787:     }
                   5788: 
                   5789:     unless (&allowed('mgr',$tcrsid)) {
                   5790:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5791:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5792:         return '';
                   5793:     }
                   5794: 
                   5795:     my %infohash=('resource.0.intoken' => $token,
                   5796:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5797:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5798: 
                   5799:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5800:        return '';
                   5801:     }
                   5802: 
                   5803:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5804:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5805:         return '';
                   5806:     }
                   5807: 
                   5808:     return ($symb,$tuname,$tudom,$tcrsid);
                   5809: }
                   5810: 
1.110     www      5811: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5812: 
                   5813: sub expirespread {
                   5814:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5815:     my $cid=$env{'request.course.id'}; 
1.110     www      5816:     if ($cid) {
                   5817:        my $now=time;
                   5818:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5819:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5820:                             $env{'course.'.$cid.'.num'}.
1.110     www      5821: 	        	    ':nohist_expirationdates:'.
                   5822:                             &escape($key).'='.$now,
1.620     albertel 5823:                             $env{'course.'.$cid.'.home'})
1.110     www      5824:     }
                   5825:     return 'ok';
1.14      www      5826: }
                   5827: 
1.109     www      5828: # ----------------------------------------------------- Devalidate Spreadsheets
                   5829: 
                   5830: sub devalidate {
1.325     www      5831:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5832:     my $cid=$env{'request.course.id'}; 
1.109     www      5833:     if ($cid) {
1.391     matthew  5834:         # delete the stored spreadsheets for
                   5835:         # - the student level sheet of this user in course's homespace
                   5836:         # - the assessment level sheet for this resource 
                   5837:         #   for this user in user's homespace
1.553     albertel 5838: 	# - current conditional state info
1.325     www      5839: 	my $key=$uname.':'.$udom.':';
1.109     www      5840:         my $status=
1.299     matthew  5841: 	    &del('nohist_calculatedsheets',
1.391     matthew  5842: 		 [$key.'studentcalc:'],
1.620     albertel 5843: 		 $env{'course.'.$cid.'.domain'},
                   5844: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5845: 		.' '.
                   5846: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5847: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5848:         unless ($status eq 'ok ok') {
                   5849:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5850:                     $uname.' at '.$udom.' for '.
1.109     www      5851: 		    $symb.': '.$status);
1.133     albertel 5852:         }
1.553     albertel 5853: 	&delenv('user.state.'.$cid);
1.109     www      5854:     }
                   5855: }
                   5856: 
1.265     albertel 5857: sub get_scalar {
                   5858:     my ($string,$end) = @_;
                   5859:     my $value;
                   5860:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5861: 	$value = $1;
                   5862:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5863: 	$value = $1;
                   5864:     }
                   5865:     return &unescape($value);
                   5866: }
                   5867: 
                   5868: sub array2str {
                   5869:   my (@array) = @_;
                   5870:   my $result=&arrayref2str(\@array);
                   5871:   $result=~s/^__ARRAY_REF__//;
                   5872:   $result=~s/__END_ARRAY_REF__$//;
                   5873:   return $result;
                   5874: }
                   5875: 
1.204     albertel 5876: sub arrayref2str {
                   5877:   my ($arrayref) = @_;
1.265     albertel 5878:   my $result='__ARRAY_REF__';
1.204     albertel 5879:   foreach my $elem (@$arrayref) {
1.265     albertel 5880:     if(ref($elem) eq 'ARRAY') {
                   5881:       $result.=&arrayref2str($elem).'&';
                   5882:     } elsif(ref($elem) eq 'HASH') {
                   5883:       $result.=&hashref2str($elem).'&';
                   5884:     } elsif(ref($elem)) {
                   5885:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5886:     } else {
                   5887:       $result.=&escape($elem).'&';
                   5888:     }
                   5889:   }
                   5890:   $result=~s/\&$//;
1.265     albertel 5891:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5892:   return $result;
                   5893: }
                   5894: 
1.168     albertel 5895: sub hash2str {
1.204     albertel 5896:   my (%hash) = @_;
                   5897:   my $result=&hashref2str(\%hash);
1.265     albertel 5898:   $result=~s/^__HASH_REF__//;
                   5899:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5900:   return $result;
                   5901: }
                   5902: 
                   5903: sub hashref2str {
                   5904:   my ($hashref)=@_;
1.265     albertel 5905:   my $result='__HASH_REF__';
1.800     albertel 5906:   foreach my $key (sort(keys(%$hashref))) {
                   5907:     if (ref($key) eq 'ARRAY') {
                   5908:       $result.=&arrayref2str($key).'=';
                   5909:     } elsif (ref($key) eq 'HASH') {
                   5910:       $result.=&hashref2str($key).'=';
                   5911:     } elsif (ref($key)) {
1.265     albertel 5912:       $result.='=';
1.800     albertel 5913:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5914:     } else {
1.1132    raeburn  5915: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5916:     }
                   5917: 
1.800     albertel 5918:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5919:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5920:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5921:       $result.=&hashref2str($hashref->{$key}).'&';
                   5922:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5923:        $result.='&';
1.800     albertel 5924:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5925:     } else {
1.800     albertel 5926:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5927:     }
                   5928:   }
1.168     albertel 5929:   $result=~s/\&$//;
1.265     albertel 5930:   $result .= '__END_HASH_REF__';
1.168     albertel 5931:   return $result;
                   5932: }
                   5933: 
                   5934: sub str2hash {
1.265     albertel 5935:     my ($string)=@_;
                   5936:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5937:     return %$hash;
                   5938: }
                   5939: 
                   5940: sub str2hashref {
1.168     albertel 5941:   my ($string) = @_;
1.265     albertel 5942: 
                   5943:   my %hash;
                   5944: 
                   5945:   if($string !~ /^__HASH_REF__/) {
                   5946:       if (! ($string eq '' || !defined($string))) {
                   5947: 	  $hash{'error'}='Not hash reference';
                   5948:       }
                   5949:       return (\%hash, $string);
                   5950:   }
                   5951: 
                   5952:   $string =~ s/^__HASH_REF__//;
                   5953: 
                   5954:   while($string !~ /^__END_HASH_REF__/) {
                   5955:       #key
                   5956:       my $key='';
                   5957:       if($string =~ /^__HASH_REF__/) {
                   5958:           ($key, $string)=&str2hashref($string);
                   5959:           if(defined($key->{'error'})) {
                   5960:               $hash{'error'}='Bad data';
                   5961:               return (\%hash, $string);
                   5962:           }
                   5963:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5964:           ($key, $string)=&str2arrayref($string);
                   5965:           if($key->[0] eq 'Array reference error') {
                   5966:               $hash{'error'}='Bad data';
                   5967:               return (\%hash, $string);
                   5968:           }
                   5969:       } else {
                   5970:           $string =~ s/^(.*?)=//;
1.267     albertel 5971: 	  $key=&unescape($1);
1.265     albertel 5972:       }
                   5973:       $string =~ s/^=//;
                   5974: 
                   5975:       #value
                   5976:       my $value='';
                   5977:       if($string =~ /^__HASH_REF__/) {
                   5978:           ($value, $string)=&str2hashref($string);
                   5979:           if(defined($value->{'error'})) {
                   5980:               $hash{'error'}='Bad data';
                   5981:               return (\%hash, $string);
                   5982:           }
                   5983:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5984:           ($value, $string)=&str2arrayref($string);
                   5985:           if($value->[0] eq 'Array reference error') {
                   5986:               $hash{'error'}='Bad data';
                   5987:               return (\%hash, $string);
                   5988:           }
                   5989:       } else {
                   5990: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5991:       }
                   5992:       $string =~ s/^&//;
                   5993: 
                   5994:       $hash{$key}=$value;
1.204     albertel 5995:   }
1.265     albertel 5996: 
                   5997:   $string =~ s/^__END_HASH_REF__//;
                   5998: 
                   5999:   return (\%hash, $string);
1.204     albertel 6000: }
                   6001: 
                   6002: sub str2array {
1.265     albertel 6003:     my ($string)=@_;
                   6004:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6005:     return @$array;
                   6006: }
                   6007: 
                   6008: sub str2arrayref {
1.204     albertel 6009:   my ($string) = @_;
1.265     albertel 6010:   my @array;
                   6011: 
                   6012:   if($string !~ /^__ARRAY_REF__/) {
                   6013:       if (! ($string eq '' || !defined($string))) {
                   6014: 	  $array[0]='Array reference error';
                   6015:       }
                   6016:       return (\@array, $string);
                   6017:   }
                   6018: 
                   6019:   $string =~ s/^__ARRAY_REF__//;
                   6020: 
                   6021:   while($string !~ /^__END_ARRAY_REF__/) {
                   6022:       my $value='';
                   6023:       if($string =~ /^__HASH_REF__/) {
                   6024:           ($value, $string)=&str2hashref($string);
                   6025:           if(defined($value->{'error'})) {
                   6026:               $array[0] ='Array reference error';
                   6027:               return (\@array, $string);
                   6028:           }
                   6029:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6030:           ($value, $string)=&str2arrayref($string);
                   6031:           if($value->[0] eq 'Array reference error') {
                   6032:               $array[0] ='Array reference error';
                   6033:               return (\@array, $string);
                   6034:           }
                   6035:       } else {
                   6036: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6037:       }
                   6038:       $string =~ s/^&//;
                   6039: 
                   6040:       push(@array, $value);
1.191     harris41 6041:   }
1.265     albertel 6042: 
                   6043:   $string =~ s/^__END_ARRAY_REF__//;
                   6044: 
                   6045:   return (\@array, $string);
1.168     albertel 6046: }
                   6047: 
1.167     albertel 6048: # -------------------------------------------------------------------Temp Store
                   6049: 
1.168     albertel 6050: sub tmpreset {
                   6051:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6052:   if (!$symb) {
                   6053:     $symb=&symbread();
1.620     albertel 6054:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6055:   }
                   6056:   $symb=escape($symb);
                   6057: 
1.620     albertel 6058:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6059:   $namespace=~s/\//\_/g;
                   6060:   $namespace=~s/\W//g;
                   6061: 
1.620     albertel 6062:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6063:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6064:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6065:       $stuname=&get_requestor_ip();
1.591     albertel 6066:   }
1.1117    foxr     6067:   my $path=LONCAPA::tempdir();
1.168     albertel 6068:   my %hash;
                   6069:   if (tie(%hash,'GDBM_File',
                   6070: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6071: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6072:     foreach my $key (keys(%hash)) {
1.180     albertel 6073:       if ($key=~ /:$symb/) {
1.168     albertel 6074: 	delete($hash{$key});
                   6075:       }
                   6076:     }
                   6077:   }
                   6078: }
                   6079: 
1.167     albertel 6080: sub tmpstore {
1.168     albertel 6081:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6082: 
                   6083:   if (!$symb) {
                   6084:     $symb=&symbread();
1.620     albertel 6085:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6086:   }
                   6087:   $symb=escape($symb);
                   6088: 
                   6089:   if (!$namespace) {
                   6090:     # I don't think we would ever want to store this for a course.
                   6091:     # it seems this will only be used if we don't have a course.
1.620     albertel 6092:     #$namespace=$env{'request.course.id'};
1.168     albertel 6093:     #if (!$namespace) {
1.620     albertel 6094:       $namespace=$env{'request.state'};
1.168     albertel 6095:     #}
                   6096:   }
                   6097:   $namespace=~s/\//\_/g;
                   6098:   $namespace=~s/\W//g;
1.620     albertel 6099:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6100:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6101:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6102:       $stuname=&get_requestor_ip();
1.591     albertel 6103:   }
1.168     albertel 6104:   my $now=time;
                   6105:   my %hash;
1.1117    foxr     6106:   my $path=LONCAPA::tempdir();
1.168     albertel 6107:   if (tie(%hash,'GDBM_File',
                   6108: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6109: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6110:     $hash{"version:$symb"}++;
                   6111:     my $version=$hash{"version:$symb"};
                   6112:     my $allkeys=''; 
                   6113:     foreach my $key (keys(%$storehash)) {
                   6114:       $allkeys.=$key.':';
1.591     albertel 6115:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6116:     }
                   6117:     $hash{"$version:$symb:timestamp"}=$now;
                   6118:     $allkeys.='timestamp';
                   6119:     $hash{"$version:keys:$symb"}=$allkeys;
                   6120:     if (untie(%hash)) {
                   6121:       return 'ok';
                   6122:     } else {
                   6123:       return "error:$!";
                   6124:     }
                   6125:   } else {
                   6126:     return "error:$!";
                   6127:   }
                   6128: }
1.167     albertel 6129: 
1.168     albertel 6130: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6131: 
1.168     albertel 6132: sub tmprestore {
                   6133:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6134: 
1.168     albertel 6135:   if (!$symb) {
                   6136:     $symb=&symbread();
1.620     albertel 6137:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6138:   }
                   6139:   $symb=escape($symb);
                   6140: 
1.620     albertel 6141:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6142: 
1.620     albertel 6143:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6144:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6145:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6146:       $stuname=&get_requestor_ip();
1.591     albertel 6147:   }
1.168     albertel 6148:   my %returnhash;
                   6149:   $namespace=~s/\//\_/g;
                   6150:   $namespace=~s/\W//g;
                   6151:   my %hash;
1.1117    foxr     6152:   my $path=LONCAPA::tempdir();
1.168     albertel 6153:   if (tie(%hash,'GDBM_File',
                   6154: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6155: 	  &GDBM_READER(),0640)) {
1.168     albertel 6156:     my $version=$hash{"version:$symb"};
                   6157:     $returnhash{'version'}=$version;
                   6158:     my $scope;
                   6159:     for ($scope=1;$scope<=$version;$scope++) {
                   6160:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6161:       my @keys=split(/:/,$vkeys);
                   6162:       my $key;
                   6163:       $returnhash{"$scope:keys"}=$vkeys;
                   6164:       foreach $key (@keys) {
1.591     albertel 6165: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6166: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6167:       }
                   6168:     }
1.168     albertel 6169:     if (!(untie(%hash))) {
                   6170:       return "error:$!";
                   6171:     }
                   6172:   } else {
                   6173:     return "error:$!";
                   6174:   }
                   6175:   return %returnhash;
1.167     albertel 6176: }
                   6177: 
1.9       www      6178: # ----------------------------------------------------------------------- Store
                   6179: 
                   6180: sub store {
1.1172.2.64  raeburn  6181:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6182:     my $home='';
                   6183: 
1.168     albertel 6184:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6185: 
1.213     www      6186:     $symb=&symbclean($symb);
1.122     albertel 6187:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6188: 
1.620     albertel 6189:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6190:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6191: 
                   6192:     &devalidate($symb,$stuname,$domain);
1.109     www      6193: 
                   6194:     $symb=escape($symb);
1.187     www      6195:     if (!$namespace) { 
1.620     albertel 6196:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6197:           return ''; 
                   6198:        } 
                   6199:     }
1.620     albertel 6200:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6201: 
1.1172.2.138  raeburn  6202:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6203:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6204: 
1.12      www      6205:     my $namevalue='';
1.800     albertel 6206:     foreach my $key (keys(%$storehash)) {
                   6207:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6208:     }
1.12      www      6209:     $namevalue=~s/\&$//;
1.187     www      6210:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6211:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6212: }
                   6213: 
1.47      www      6214: # -------------------------------------------------------------- Critical Store
                   6215: 
                   6216: sub cstore {
1.1172.2.64  raeburn  6217:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6218:     my $home='';
                   6219: 
1.168     albertel 6220:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6221: 
1.213     www      6222:     $symb=&symbclean($symb);
1.122     albertel 6223:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6224: 
1.620     albertel 6225:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6226:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6227: 
                   6228:     &devalidate($symb,$stuname,$domain);
1.109     www      6229: 
                   6230:     $symb=escape($symb);
1.187     www      6231:     if (!$namespace) { 
1.620     albertel 6232:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6233:           return ''; 
                   6234:        } 
                   6235:     }
1.620     albertel 6236:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6237: 
1.1172.2.138  raeburn  6238:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6239:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6240: 
1.47      www      6241:     my $namevalue='';
1.800     albertel 6242:     foreach my $key (keys(%$storehash)) {
                   6243:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6244:     }
1.47      www      6245:     $namevalue=~s/\&$//;
1.187     www      6246:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6247:     return critical
1.1172.2.64  raeburn  6248:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6249: }
                   6250: 
1.9       www      6251: # --------------------------------------------------------------------- Restore
                   6252: 
                   6253: sub restore {
1.124     www      6254:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6255:     my $home='';
                   6256: 
1.168     albertel 6257:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6258: 
1.122     albertel 6259:     if (!$symb) {
1.1172.2.26  raeburn  6260:         return if ($namespace eq 'courserequests');
                   6261:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6262:     } else {
1.1172.2.26  raeburn  6263:         unless ($namespace eq 'courserequests') {
                   6264:             $symb=&escape(&symbclean($symb));
                   6265:         }
1.122     albertel 6266:     }
1.188     www      6267:     if (!$namespace) { 
1.620     albertel 6268:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6269:           return ''; 
                   6270:        } 
                   6271:     }
1.620     albertel 6272:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6273:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6274:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6275:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6276: 
1.12      www      6277:     my %returnhash=();
1.800     albertel 6278:     foreach my $line (split(/\&/,$answer)) {
                   6279: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6280:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6281:     }
1.75      www      6282:     my $version;
                   6283:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6284:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6285:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6286:        }
1.75      www      6287:     }
1.13      www      6288:     return %returnhash;
1.34      www      6289: }
                   6290: 
                   6291: # ---------------------------------------------------------- Course Description
1.1118    foxr     6292: #
                   6293: #  
1.34      www      6294: 
                   6295: sub coursedescription {
1.731     albertel 6296:     my ($courseid,$args)=@_;
1.34      www      6297:     $courseid=~s/^\///;
1.49      www      6298:     $courseid=~s/\_/\//g;
1.34      www      6299:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6300:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6301:     my $normalid=$cdomain.'_'.$cnum;
                   6302:     # need to always cache even if we get errors otherwise we keep 
                   6303:     # trying and trying and trying to get the course description.
                   6304:     my %envhash=();
                   6305:     my %returnhash=();
1.731     albertel 6306:     
                   6307:     my $expiretime=600;
                   6308:     if ($env{'request.course.id'} eq $normalid) {
                   6309: 	$expiretime=120;
                   6310:     }
                   6311: 
                   6312:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6313:     if (!$args->{'freshen_cache'}
                   6314: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6315: 	foreach my $key (keys(%env)) {
                   6316: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6317: 	    my ($setting) = $1;
                   6318: 	    $returnhash{$setting} = $env{$key};
                   6319: 	}
                   6320: 	return %returnhash;
                   6321:     }
                   6322: 
1.1118    foxr     6323:     # get the data again
                   6324: 
1.731     albertel 6325:     if (!$args->{'one_time'}) {
                   6326: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6327:     }
1.811     albertel 6328: 
1.34      www      6329:     if ($chome ne 'no_host') {
1.302     albertel 6330:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6331:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6332: 	   my $username = $env{'user.name'}; # Defult username
                   6333: 	   if(defined $args->{'user'}) {
                   6334: 	       $username = $args->{'user'};
                   6335: 	   }
1.129     albertel 6336:            $returnhash{'home'}= $chome;
                   6337: 	   $returnhash{'domain'} = $cdomain;
                   6338: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6339:            if (!defined($returnhash{'type'})) {
                   6340:                $returnhash{'type'} = 'Course';
                   6341:            }
1.130     albertel 6342:            while (my ($name,$value) = each %returnhash) {
1.53      www      6343:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6344:            }
1.270     www      6345:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6346:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6347: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6348:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6349:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6350:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6351:        }
                   6352:     }
1.731     albertel 6353:     if (!$args->{'one_time'}) {
1.949     raeburn  6354: 	&appenv(\%envhash);
1.731     albertel 6355:     }
1.302     albertel 6356:     return %returnhash;
1.461     www      6357: }
                   6358: 
1.1080    raeburn  6359: sub update_released_required {
                   6360:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6361:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6362:         $cid = $env{'request.course.id'};
                   6363:         $cdom = $env{'course.'.$cid.'.domain'};
                   6364:         $cnum = $env{'course.'.$cid.'.num'};
                   6365:         $chome = $env{'course.'.$cid.'.home'};
                   6366:     }
                   6367:     if ($needsrelease) {
                   6368:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6369:         my $needsupdate;
                   6370:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6371:             $needsupdate = 1;
                   6372:         } else {
                   6373:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6374:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6375:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6376:                 $needsupdate = 1;
                   6377:             }
                   6378:         }
                   6379:         if ($needsupdate) {
                   6380:             my %needshash = (
                   6381:                              'internal.releaserequired' => $needsrelease,
                   6382:                             );
                   6383:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6384:             if ($putresult eq 'ok') {
                   6385:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6386:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6387:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6388:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6389:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6390:                 }
                   6391:             }
                   6392:         }
                   6393:     }
                   6394:     return;
                   6395: }
                   6396: 
1.461     www      6397: # -------------------------------------------------See if a user is privileged
                   6398: 
                   6399: sub privileged {
1.1172.2.23  raeburn  6400:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6401:     my $now = time;
1.1172.2.23  raeburn  6402:     my $roles;
                   6403:     if (ref($possroles) eq 'ARRAY') {
                   6404:         $roles = $possroles;
                   6405:     } else {
                   6406:         $roles = ['dc','su'];
                   6407:     }
                   6408:     if (ref($possdomains) eq 'ARRAY') {
                   6409:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6410:         foreach my $dom (@{$possdomains}) {
                   6411:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6412:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6413:                 foreach my $role (@{$roles}) {
                   6414:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6415:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6416:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6417:                             return 1 unless (($end && $end < $now) ||
                   6418:                                              ($start && $start > $now));
                   6419:                         }
                   6420:                     }
                   6421:                 }
                   6422:             }
                   6423:         }
                   6424:     } else {
                   6425:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6426:         my $now = time;
1.1170    droeschl 6427: 
1.1172.2.58  raeburn  6428:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6429:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6430:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6431:                 return 1 unless ($tend && $tend < $now)
                   6432:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6433:             }
1.1172.2.23  raeburn  6434:         }
                   6435:     }
1.461     www      6436:     return 0;
1.9       www      6437: }
1.1       albertel 6438: 
1.1172.2.23  raeburn  6439: sub privileged_by_domain {
                   6440:     my ($domains,$roles) = @_;
                   6441:     my %privileged = ();
                   6442:     my $cachetime = 60*60*24;
                   6443:     my $now = time;
                   6444:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6445:         return %privileged;
                   6446:     }
                   6447:     foreach my $dom (@{$domains}) {
                   6448:         next if (ref($privileged{$dom}) eq 'HASH');
                   6449:         my $needroles;
                   6450:         foreach my $role (@{$roles}) {
                   6451:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6452:             if (defined($cached)) {
                   6453:                 if (ref($result) eq 'HASH') {
                   6454:                     $privileged{$dom}{$role} = $result;
                   6455:                 }
                   6456:             } else {
                   6457:                 $needroles = 1;
                   6458:             }
                   6459:         }
                   6460:         if ($needroles) {
                   6461:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6462:             $privileged{$dom} = {};
                   6463:             foreach my $server (keys(%dompersonnel)) {
                   6464:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6465:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6466:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6467:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6468:                         next if ($end && $end < $now);
                   6469:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6470:                             $dompersonnel{$server}{$item};
                   6471:                     }
                   6472:                 }
                   6473:             }
                   6474:             if (ref($privileged{$dom}) eq 'HASH') {
                   6475:                 foreach my $role (@{$roles}) {
                   6476:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6477:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6478:                     } else {
                   6479:                         my %hash = ();
                   6480:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6481:                     }
                   6482:                 }
                   6483:             }
                   6484:         }
                   6485:     }
                   6486:     return %privileged;
                   6487: }
                   6488: 
1.103     harris41 6489: # -------------------------------------------------------- Get user privileges
1.11      www      6490: 
                   6491: sub rolesinit {
1.1169    droeschl 6492:     my ($domain, $username) = @_;
                   6493:     my %userroles = ('user.login.time' => time);
                   6494:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6495: 
                   6496:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6497:     # also, blocking can be triggered by an activating timer
                   6498:     # it's saved in the user's %env.
                   6499:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6500:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6501:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6502:         %timerintchk, %timerintenv);
                   6503: 
1.1162    raeburn  6504:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6505:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6506:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6507:     }
1.1169    droeschl 6508: 
1.1162    raeburn  6509:     foreach my $key (keys(%timerinterval)) {
                   6510:         my ($cid,$rest) = split(/\0/,$key);
                   6511:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6512:     }
1.1169    droeschl 6513: 
1.11      www      6514:     my %allroles=();
1.1162    raeburn  6515:     my %allgroups=();
1.11      www      6516: 
1.1172.2.58  raeburn  6517:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6518:         my $role = $rolesdump{$area};
                   6519:         $area =~ s/\_\w\w$//;
                   6520: 
                   6521:         my ($trole, $tend, $tstart, $group_privs);
                   6522: 
                   6523:         if ($role =~ /^cr/) {
                   6524:         # Custom role, defined by a user 
                   6525:         # e.g., user.role.cr/msu/smith/mynewrole
                   6526:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6527:                 $trole = $1;
                   6528:                 ($tend, $tstart) = split('_', $2);
                   6529:             } else {
                   6530:                 $trole = $role;
                   6531:             }
                   6532:         } elsif ($role =~ m|^gr/|) {
                   6533:         # Role of member in a group, defined within a course/community
                   6534:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6535:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6536:             next if $tstart eq '-1';
                   6537:             ($trole, $group_privs) = split(/\//, $trole);
                   6538:             $group_privs = &unescape($group_privs);
                   6539:         } else {
                   6540:         # Just a normal role, defined in roles.tab
                   6541:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6542:         }
                   6543: 
                   6544:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6545:                  $username);
                   6546:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6547: 
                   6548:         # role expired or not available yet?
                   6549:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6550:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6551: 
                   6552:         next if $area eq '' or $trole eq '';
                   6553: 
                   6554:         my $spec = "$trole.$area";
                   6555:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6556: 
                   6557:         if ($trole =~ /^cr\//) {
                   6558:         # Custom role, defined by a user
                   6559:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6560:         } elsif ($trole eq 'gr') {
                   6561:         # Role of a member in a group, defined within a course/community
                   6562:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6563:             next;
                   6564:         } else {
                   6565:         # Normal role, defined in roles.tab
                   6566:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6567:         }
                   6568: 
                   6569:         my $cid = $tdomain.'_'.$trest;
                   6570:         unless ($firstaccchk{$cid}) {
                   6571:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6572:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6573:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6574:                         $coursetimerstarts{$cid}{$item}; 
                   6575:                 }
                   6576:             }
                   6577:             $firstaccchk{$cid} = 1;
                   6578:         }
                   6579:         unless ($timerintchk{$cid}) {
                   6580:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6581:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6582:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6583:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6584:                 }
1.12      www      6585:             }
1.1169    droeschl 6586:             $timerintchk{$cid} = 1;
1.191     harris41 6587:         }
1.11      www      6588:     }
1.1169    droeschl 6589: 
1.1172.2.91  raeburn  6590:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6591:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6592:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6593:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6594: 
1.1162    raeburn  6595:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6596: }
                   6597: 
1.567     raeburn  6598: sub set_arearole {
1.1172.2.19  raeburn  6599:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6600:     unless ($nolog) {
1.567     raeburn  6601: # log the associated role with the area
1.1172.2.19  raeburn  6602:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6603:     }
1.743     albertel 6604:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6605: }
                   6606: 
                   6607: sub custom_roleprivs {
                   6608:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6609:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6610:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6611:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6612:         my ($rdummy,$roledef)=
                   6613:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6614:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6615:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6616:             if (defined($syspriv)) {
1.1043    raeburn  6617:                 if ($trest =~ /^$match_community$/) {
                   6618:                     $syspriv =~ s/bre\&S//; 
                   6619:                 }
1.567     raeburn  6620:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6621:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6622:             }
                   6623:             if ($tdomain ne '') {
                   6624:                 if (defined($dompriv)) {
                   6625:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6626:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6627:                 }
                   6628:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6629:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6630:                         my $rolename = $1;
                   6631:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6632:                     }
1.567     raeburn  6633:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6634:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6635:                 }
                   6636:             }
                   6637:         }
                   6638:     }
                   6639: }
                   6640: 
1.1172.2.89  raeburn  6641: sub course_adhocrole_privs {
                   6642:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6643:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6644:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6645:         my (%currprivs,%storeprivs);
                   6646:         foreach my $item (split(/:/,$coursepriv)) {
                   6647:             my ($priv,$restrict) = split(/\&/,$item);
                   6648:             $currprivs{$priv} = $restrict;
                   6649:         }
                   6650:         my (%possadd,%possremove,%full);
                   6651:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6652:             my ($priv,$restrict)=split(/\&/,$item);
                   6653:             $full{$priv} = $restrict;
                   6654:         }
                   6655:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6656:              next if ($item eq '');
                   6657:              my ($rule,$rest) = split(/=/,$item);
                   6658:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6659:              foreach my $priv (split(/:/,$rest)) {
                   6660:                  if ($priv ne '') {
                   6661:                      if ($rule eq 'off') {
                   6662:                          $possremove{$priv} = 1;
                   6663:                      } else {
                   6664:                          $possadd{$priv} = 1;
                   6665:                      }
                   6666:                  }
                   6667:              }
                   6668:          }
                   6669:          foreach my $priv (sort(keys(%full))) {
                   6670:              if (exists($currprivs{$priv})) {
                   6671:                  unless (exists($possremove{$priv})) {
                   6672:                      $storeprivs{$priv} = $currprivs{$priv};
                   6673:                  }
                   6674:              } elsif (exists($possadd{$priv})) {
                   6675:                  $storeprivs{$priv} = $full{$priv};
                   6676:              }
                   6677:          }
                   6678:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6679:      }
                   6680:      return $coursepriv;
                   6681: }
                   6682: 
1.678     raeburn  6683: sub group_roleprivs {
                   6684:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6685:     my $access = 1;
                   6686:     my $now = time;
                   6687:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6688:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6689:     if ($access) {
1.811     albertel 6690:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6691:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6692:     }
                   6693: }
1.567     raeburn  6694: 
                   6695: sub standard_roleprivs {
                   6696:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6697:     if (defined($pr{$trole.':s'})) {
                   6698:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6699:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6700:     }
                   6701:     if ($tdomain ne '') {
                   6702:         if (defined($pr{$trole.':d'})) {
                   6703:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6704:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6705:         }
                   6706:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6707:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6708:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6709:         }
                   6710:     }
                   6711: }
                   6712: 
                   6713: sub set_userprivs {
1.1064    raeburn  6714:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6715:     my $author=0;
                   6716:     my $adv=0;
1.1172.2.91  raeburn  6717:     my $rar=0;
1.678     raeburn  6718:     my %grouproles = ();
                   6719:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6720:         my @groupkeys; 
1.1000    raeburn  6721:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6722:             push(@groupkeys,$role);
                   6723:         }
                   6724:         if (ref($groups_roles) eq 'HASH') {
                   6725:             foreach my $key (keys(%{$groups_roles})) {
                   6726:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6727:                     push(@groupkeys,$key);
                   6728:                 }
                   6729:             }
                   6730:         }
                   6731:         if (@groupkeys > 0) {
                   6732:             foreach my $role (@groupkeys) {
                   6733:                 my ($trole,$area,$sec,$extendedarea);
                   6734:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6735:                     $trole = $1;
                   6736:                     $area = $2;
                   6737:                     $sec = $3;
                   6738:                     $extendedarea = $area.$sec;
                   6739:                     if (exists($$allgroups{$area})) {
                   6740:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6741:                             my $spec = $trole.'.'.$extendedarea;
                   6742:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6743:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6744:                         }
1.678     raeburn  6745:                     }
                   6746:                 }
                   6747:             }
                   6748:         }
                   6749:     }
1.800     albertel 6750:     foreach my $group (keys(%grouproles)) {
                   6751:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6752:     }
1.800     albertel 6753:     foreach my $role (keys(%{$allroles})) {
                   6754:         my %thesepriv;
1.941     raeburn  6755:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6756:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6757:             if ($item ne '') {
                   6758:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6759:                 if ($restrictions eq '') {
                   6760:                     $thesepriv{$privilege}='F';
                   6761:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6762:                     $thesepriv{$privilege}.=$restrictions;
                   6763:                 }
                   6764:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6765:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6766:             }
                   6767:         }
                   6768:         my $thesestr='';
1.1104    raeburn  6769:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6770: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6771: 	}
                   6772:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6773:     }
1.1172.2.91  raeburn  6774:     return ($author,$adv,$rar);
1.567     raeburn  6775: }
                   6776: 
1.994     raeburn  6777: sub role_status {
1.1104    raeburn  6778:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6779:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6780:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6781:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6782:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6783:             $$where = '/'.$two;
1.994     raeburn  6784:             $$trolecode=$$role.'.'.$$where;
                   6785:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6786:             $$tstatus='is';
1.1104    raeburn  6787:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6788:                 $$tstatus='future';
1.1034    raeburn  6789:                 if ($$tstart<$now) {
                   6790:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6791:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6792:                             my (%allroles,%allgroups,$group_privs,
                   6793:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6794:                             my %userroles = (
                   6795:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6796:                             );
1.1064    raeburn  6797:                             @rolecodes = ('cm'); 
1.1002    raeburn  6798:                             my $spec=$$role.'.'.$$where;
                   6799:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6800:                             if ($$role =~ /^cr\//) {
                   6801:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6802:                                 push(@rolecodes,'cr');
1.1002    raeburn  6803:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6804:                                 push(@rolecodes,$$role);
1.1002    raeburn  6805:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6806:                                                     $env{'user.name'});
1.1064    raeburn  6807:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6808:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6809:                                 $group_privs = &unescape($group_privs);
                   6810:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6811:                                 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  6812:                                 &get_groups_roles($tdomain,$trest,
                   6813:                                                   \%course_roles,\@rolecodes,
                   6814:                                                   \%groups_roles);
1.1002    raeburn  6815:                             } else {
1.1064    raeburn  6816:                                 push(@rolecodes,$$role);
1.1002    raeburn  6817:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6818:                             }
1.1172.2.91  raeburn  6819:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6820:                                                                    \%groups_roles);
1.1064    raeburn  6821:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6822:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6823:                         }
                   6824:                     }
1.1034    raeburn  6825:                     $$tstatus = 'is';
1.1002    raeburn  6826:                 }
1.994     raeburn  6827:             }
                   6828:             if ($$tend) {
1.1104    raeburn  6829:                 if ($$tend<$update) {
1.994     raeburn  6830:                     $$tstatus='expired';
                   6831:                 } elsif ($$tend<$now) {
                   6832:                     $$tstatus='will_not';
                   6833:                 }
                   6834:             }
                   6835:         }
                   6836:     }
                   6837: }
                   6838: 
1.1104    raeburn  6839: sub get_groups_roles {
                   6840:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6841:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6842:                   (ref($rolecodes) eq 'ARRAY') && 
                   6843:                   (ref($groups_roles) eq 'HASH')); 
                   6844:     if (keys(%{$cdom_courseroles}) > 0) {
                   6845:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6846:         if ($cdom ne '' && $cnum ne '') {
                   6847:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6848:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6849:                     my $crsrole = $1;
                   6850:                     my $crssec = $2;
                   6851:                     if ($crsrole =~ /^cr/) {
                   6852:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6853:                             push(@{$rolecodes},'cr');
                   6854:                         }
                   6855:                     } else {
                   6856:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6857:                             push(@{$rolecodes},$crsrole);
                   6858:                         }
                   6859:                     }
                   6860:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6861:                     if ($crssec ne '') {
                   6862:                         $rolekey .= "/$crssec";
                   6863:                     }
                   6864:                     $rolekey .= './';
                   6865:                     $groups_roles->{$rolekey} = $rolecodes;
                   6866:                 }
                   6867:             }
                   6868:         }
                   6869:     }
                   6870:     return;
                   6871: }
                   6872: 
                   6873: sub delete_env_groupprivs {
                   6874:     my ($where,$courseroles,$possroles) = @_;
                   6875:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6876:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6877:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6878:         %{$courseroles->{$udom}} =
                   6879:             &get_my_roles('','','userroles',['active'],
                   6880:                           $possroles,[$udom],1);
                   6881:     }
                   6882:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6883:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6884:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6885:             my $area = '/'.$cdom.'/'.$cnum;
                   6886:             my $privkey = "user.priv.$crsrole.$area";
                   6887:             if ($crssec ne '') {
                   6888:                 $privkey .= '/'.$crssec;
                   6889:             }
                   6890:             $privkey .= ".$area/$group";
                   6891:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6892:         }
                   6893:     }
                   6894:     return;
                   6895: }
                   6896: 
1.994     raeburn  6897: sub check_adhoc_privs {
1.1172.2.86  raeburn  6898:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6899:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6900:     if ($sec) {
                   6901:         $cckey .= '/'.$sec;
                   6902:     }
1.1172.2.9  raeburn  6903:     my $setprivs;
1.994     raeburn  6904:     if ($env{$cckey}) {
                   6905:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6906:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6907:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6908:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6909:             $setprivs = 1;
1.994     raeburn  6910:         }
                   6911:     } else {
1.1172.2.87  raeburn  6912:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6913:         $setprivs = 1;
1.994     raeburn  6914:     }
1.1172.2.9  raeburn  6915:     return $setprivs;
1.994     raeburn  6916: }
                   6917: 
                   6918: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6919: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6920:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6921:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6922:     if ($sec ne '') {
                   6923:         $area .= '/'.$sec;
                   6924:     }
1.994     raeburn  6925:     my $spec = $role.'.'.$area;
                   6926:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6927:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6928:     my %rolehash = ();
1.1172.2.89  raeburn  6929:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6930:         my $rolename = $1;
1.1172.2.84  raeburn  6931:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6932:         my %domdef = &get_domain_defaults($dcdom);
                   6933:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6934:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6935:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6936:             }
                   6937:         }
1.1172.2.84  raeburn  6938:     } else {
                   6939:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6940:     }
1.1172.2.91  raeburn  6941:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6942:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6943:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6944:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6945:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6946:         &appenv( {'request.role'        => $spec,
                   6947:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6948:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6949:                  }
                   6950:                );
                   6951:         my $tadv=0;
                   6952:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6953:         &appenv({'request.role.adv'    => $tadv});
                   6954:     }
1.994     raeburn  6955: }
                   6956: 
1.12      www      6957: # --------------------------------------------------------------- get interface
                   6958: 
                   6959: sub get {
1.131     albertel 6960:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6961:    my $items='';
1.800     albertel 6962:    foreach my $item (@$storearr) {
                   6963:        $items.=&escape($item).'&';
1.191     harris41 6964:    }
1.12      www      6965:    $items=~s/\&$//;
1.620     albertel 6966:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6967:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6968:    my $uhome=&homeserver($uname,$udomain);
                   6969: 
1.133     albertel 6970:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6971:    my @pairs=split(/\&/,$rep);
1.273     albertel 6972:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6973:      return @pairs;
                   6974:    }
1.15      www      6975:    my %returnhash=();
1.42      www      6976:    my $i=0;
1.800     albertel 6977:    foreach my $item (@$storearr) {
                   6978:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6979:       $i++;
1.191     harris41 6980:    }
1.15      www      6981:    return %returnhash;
1.27      www      6982: }
                   6983: 
                   6984: # --------------------------------------------------------------- del interface
                   6985: 
                   6986: sub del {
1.133     albertel 6987:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6988:    my $items='';
1.800     albertel 6989:    foreach my $item (@$storearr) {
                   6990:        $items.=&escape($item).'&';
1.191     harris41 6991:    }
1.984     neumanie 6992: 
1.27      www      6993:    $items=~s/\&$//;
1.620     albertel 6994:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6995:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6996:    my $uhome=&homeserver($uname,$udomain);
                   6997:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6998: }
                   6999: 
                   7000: # -------------------------------------------------------------- dump interface
                   7001: 
1.1172.2.22  raeburn  7002: sub unserialize {
                   7003:     my ($rep, $escapedkeys) = @_;
                   7004: 
                   7005:     return {} if $rep =~ /^error/;
                   7006: 
                   7007:     my %returnhash=();
                   7008:     foreach my $item (split(/\&/,$rep)) {
                   7009:         my ($key, $value) = split(/=/, $item, 2);
                   7010:         $key = unescape($key) unless $escapedkeys;
                   7011:         next if $key =~ /^error: 2 /;
                   7012:         $returnhash{$key} = &thaw_unescape($value);
                   7013:     }
                   7014:     return \%returnhash;
                   7015: }
                   7016: 
                   7017: # see Lond::dump_with_regexp
                   7018: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7019: sub dump {
1.1172.2.146.  .1(raebu 7020:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7021:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7022:     if (!$uname) { $uname=$env{'user.name'}; }
                   7023:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7024: 
1.1172.2.55  raeburn  7025:     if ($regexp) {
                   7026:         $regexp=&escape($regexp);
                   7027:     } else {
                   7028:         $regexp='.';
                   7029:     }
1.1172.2.22  raeburn  7030:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7031:         # user is hosted on this machine
1.1172.2.55  raeburn  7032:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7033:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7034:         return %{&unserialize($reply, $escapedkeys)};
                   7035:     }
1.1172.2.146.  .1(raebu 7036:22):     my $rep;
                   7037:22):     if ($encrypt) {
                   7038:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7039:22):     } else {
                   7040:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7041:22):     }
1.755     albertel 7042:     my @pairs=split(/\&/,$rep);
                   7043:     my %returnhash=();
1.1098    foxr     7044:     if (!($rep =~ /^error/ )) {
                   7045: 	foreach my $item (@pairs) {
                   7046: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7047:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7048: 	    next if ($key =~ /^error: 2 /);
                   7049: 	    $returnhash{$key}=&thaw_unescape($value);
                   7050: 	}
1.755     albertel 7051:     }
                   7052:     return %returnhash;
1.407     www      7053: }
                   7054: 
1.1098    foxr     7055: 
1.717     albertel 7056: # --------------------------------------------------------- dumpstore interface
                   7057: 
                   7058: sub dumpstore {
                   7059:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7060:    # same as dump but keys must be escaped. They may contain colon separated
                   7061:    # lists of values that may themself contain colons (e.g. symbs).
                   7062:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7063: }
                   7064: 
1.407     www      7065: # -------------------------------------------------------------- keys interface
                   7066: 
                   7067: sub getkeys {
                   7068:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7070:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7071:    my $uhome=&homeserver($uname,$udomain);
                   7072:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7073:    my @keyarray=();
1.800     albertel 7074:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7075:       next if ($key =~ /^error: 2 /);
1.800     albertel 7076:       push(@keyarray,&unescape($key));
1.407     www      7077:    }
                   7078:    return @keyarray;
1.318     matthew  7079: }
                   7080: 
1.319     matthew  7081: # --------------------------------------------------------------- currentdump
                   7082: sub currentdump {
1.328     matthew  7083:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7084:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7085:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7086:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7087:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7088:    my $rep;
                   7089: 
                   7090:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7091:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7092:                    $courseid)));
                   7093:    } else {
                   7094:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7095:    }
                   7096: 
1.318     matthew  7097:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7098:    #
1.318     matthew  7099:    my %returnhash=();
1.319     matthew  7100:    #
                   7101:    if ($rep eq "unknown_cmd") { 
                   7102:        # an old lond will not know currentdump
                   7103:        # Do a dump and make it look like a currentdump
1.822     albertel 7104:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7105:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7106:        my %hash = @tmp;
                   7107:        @tmp=();
1.424     matthew  7108:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7109:    } else {
                   7110:        my @pairs=split(/\&/,$rep);
1.800     albertel 7111:        foreach my $pair (@pairs) {
                   7112:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7113:            my ($symb,$param) = split(/:/,$key);
                   7114:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7115:                                                         &thaw_unescape($value);
1.319     matthew  7116:        }
1.191     harris41 7117:    }
1.12      www      7118:    return %returnhash;
1.424     matthew  7119: }
                   7120: 
                   7121: sub convert_dump_to_currentdump{
                   7122:     my %hash = %{shift()};
                   7123:     my %returnhash;
                   7124:     # Code ripped from lond, essentially.  The only difference
                   7125:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7126:     # we might run in to problems with parameter names =~ /^v\./
                   7127:     while (my ($key,$value) = each(%hash)) {
                   7128:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7129: 	$symb  = &unescape($symb);
                   7130: 	$param = &unescape($param);
1.424     matthew  7131:         next if ($v eq 'version' || $symb eq 'keys');
                   7132:         next if (exists($returnhash{$symb}) &&
                   7133:                  exists($returnhash{$symb}->{$param}) &&
                   7134:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7135:         $returnhash{$symb}->{$param}=$value;
                   7136:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7137:     }
                   7138:     #
                   7139:     # Remove all of the keys in the hashes which keep track of
                   7140:     # the version of the parameter.
                   7141:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7142:         # use a foreach because we are going to delete from the hash.
                   7143:         foreach my $key (keys(%$param_hash)) {
                   7144:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7145:         }
                   7146:     }
                   7147:     return \%returnhash;
1.12      www      7148: }
                   7149: 
1.627     albertel 7150: # ------------------------------------------------------ critical inc interface
                   7151: 
                   7152: sub cinc {
                   7153:     return &inc(@_,'critical');
                   7154: }
                   7155: 
1.449     matthew  7156: # --------------------------------------------------------------- inc interface
                   7157: 
                   7158: sub inc {
1.627     albertel 7159:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7160:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7161:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7162:     my $uhome=&homeserver($uname,$udomain);
                   7163:     my $items='';
                   7164:     if (! ref($store)) {
                   7165:         # got a single value, so use that instead
                   7166:         $items = &escape($store).'=&';
                   7167:     } elsif (ref($store) eq 'SCALAR') {
                   7168:         $items = &escape($$store).'=&';        
                   7169:     } elsif (ref($store) eq 'ARRAY') {
                   7170:         $items = join('=&',map {&escape($_);} @{$store});
                   7171:     } elsif (ref($store) eq 'HASH') {
                   7172:         while (my($key,$value) = each(%{$store})) {
                   7173:             $items.= &escape($key).'='.&escape($value).'&';
                   7174:         }
                   7175:     }
                   7176:     $items=~s/\&$//;
1.627     albertel 7177:     if ($critical) {
                   7178: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7179:     } else {
                   7180: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7181:     }
1.449     matthew  7182: }
                   7183: 
1.12      www      7184: # --------------------------------------------------------------- put interface
                   7185: 
                   7186: sub put {
1.1172.2.146.  .1(raebu 7187:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7188:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7189:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7190:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7191:    my $items='';
1.800     albertel 7192:    foreach my $item (keys(%$storehash)) {
                   7193:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7194:    }
1.12      www      7195:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7196:22):    if ($encrypt) {
                   7197:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7198:22):    } else {
                   7199:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7200:22):    }
1.47      www      7201: }
                   7202: 
1.631     albertel 7203: # ------------------------------------------------------------ newput interface
                   7204: 
                   7205: sub newput {
                   7206:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7207:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7208:    if (!$uname) { $uname=$env{'user.name'}; }
                   7209:    my $uhome=&homeserver($uname,$udomain);
                   7210:    my $items='';
                   7211:    foreach my $key (keys(%$storehash)) {
                   7212:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7213:    }
                   7214:    $items=~s/\&$//;
                   7215:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7216: }
                   7217: 
                   7218: # ---------------------------------------------------------  putstore interface
                   7219: 
1.524     raeburn  7220: sub putstore {
1.1172.2.59  raeburn  7221:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7222:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7223:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7224:    my $uhome=&homeserver($uname,$udomain);
                   7225:    my $items='';
1.715     albertel 7226:    foreach my $key (keys(%$storehash)) {
                   7227:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7228:    }
1.715     albertel 7229:    $items=~s/\&$//;
1.716     albertel 7230:    my $esc_symb=&escape($symb);
                   7231:    my $esc_v=&escape($version);
1.715     albertel 7232:    my $reply =
1.716     albertel 7233:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7234: 	      $uhome);
1.1172.2.59  raeburn  7235:    if (($tolog) && ($reply eq 'ok')) {
                   7236:        my $namevalue='';
                   7237:        foreach my $key (keys(%{$storehash})) {
                   7238:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7239:        }
1.1172.2.134  raeburn  7240:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7241:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7242:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7243:                      '&version='.$esc_v.
                   7244:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7245:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7246:    }
1.715     albertel 7247:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7248:        # gfall back to way things use to be done
1.715     albertel 7249:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7250: 			    $uname);
1.524     raeburn  7251:    }
1.715     albertel 7252:    return $reply;
                   7253: }
                   7254: 
                   7255: sub old_putstore {
1.716     albertel 7256:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7257:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7258:     if (!$uname) { $uname=$env{'user.name'}; }
                   7259:     my $uhome=&homeserver($uname,$udomain);
                   7260:     my %newstorehash;
1.800     albertel 7261:     foreach my $item (keys(%$storehash)) {
                   7262: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7263: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7264:     }
                   7265:     my $items='';
                   7266:     my %allitems = ();
1.800     albertel 7267:     foreach my $item (keys(%newstorehash)) {
                   7268: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7269: 	    my $key = $1.':keys:'.$2;
                   7270: 	    $allitems{$key} .= $3.':';
                   7271: 	}
1.800     albertel 7272: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7273:     }
1.800     albertel 7274:     foreach my $item (keys(%allitems)) {
                   7275: 	$allitems{$item} =~ s/\:$//;
                   7276: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7277:     }
                   7278:     $items=~s/\&$//;
                   7279:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7280: }
                   7281: 
1.47      www      7282: # ------------------------------------------------------ critical put interface
                   7283: 
                   7284: sub cput {
1.134     albertel 7285:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7286:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7287:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7288:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7289:    my $items='';
1.800     albertel 7290:    foreach my $item (keys(%$storehash)) {
                   7291:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7292:    }
1.47      www      7293:    $items=~s/\&$//;
1.134     albertel 7294:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7295: }
                   7296: 
                   7297: # -------------------------------------------------------------- eget interface
                   7298: 
                   7299: sub eget {
1.133     albertel 7300:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7301:    my $items='';
1.800     albertel 7302:    foreach my $item (@$storearr) {
                   7303:        $items.=&escape($item).'&';
1.191     harris41 7304:    }
1.12      www      7305:    $items=~s/\&$//;
1.620     albertel 7306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7307:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7308:    my $uhome=&homeserver($uname,$udomain);
                   7309:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7310:    my @pairs=split(/\&/,$rep);
                   7311:    my %returnhash=();
1.42      www      7312:    my $i=0;
1.800     albertel 7313:    foreach my $item (@$storearr) {
                   7314:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7315:       $i++;
1.191     harris41 7316:    }
1.12      www      7317:    return %returnhash;
                   7318: }
                   7319: 
1.667     albertel 7320: # ------------------------------------------------------------ tmpput interface
                   7321: sub tmpput {
1.802     raeburn  7322:     my ($storehash,$server,$context)=@_;
1.667     albertel 7323:     my $items='';
1.800     albertel 7324:     foreach my $item (keys(%$storehash)) {
                   7325: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7326:     }
                   7327:     $items=~s/\&$//;
1.802     raeburn  7328:     if (defined($context)) {
                   7329:         $items .= ':'.&escape($context);
                   7330:     }
1.667     albertel 7331:     return &reply("tmpput:$items",$server);
                   7332: }
                   7333: 
                   7334: # ------------------------------------------------------------ tmpget interface
                   7335: sub tmpget {
1.688     albertel 7336:     my ($token,$server)=@_;
                   7337:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7338:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7339:     my %returnhash;
1.1172.2.85  raeburn  7340:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7341:         return %returnhash;
                   7342:     }
1.667     albertel 7343:     foreach my $item (split(/\&/,$rep)) {
                   7344: 	my ($key,$value)=split(/=/,$item);
                   7345: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7346:     }
                   7347:     return %returnhash;
                   7348: }
                   7349: 
1.1113    raeburn  7350: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7351: sub tmpdel {
                   7352:     my ($token,$server)=@_;
                   7353:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7354:     return &reply("tmpdel:$token",$server);
                   7355: }
                   7356: 
1.1172.2.13  raeburn  7357: # ------------------------------------------------------------ get_timebased_id
                   7358: 
                   7359: sub get_timebased_id {
                   7360:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7361:         $maxtries) = @_;
                   7362:     my ($newid,$error,$dellock);
                   7363:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7364:         return ('','ok','invalid call to get suffix');
                   7365:     }
                   7366: 
                   7367: # set defaults for any optional args for which values were not supplied
                   7368:     if ($who eq '') {
                   7369:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7370:     }
                   7371:     if (!$locktries) {
                   7372:         $locktries = 3;
                   7373:     }
                   7374:     if (!$maxtries) {
                   7375:         $maxtries = 10;
                   7376:     }
                   7377: 
                   7378:     if (($cdom eq '') || ($cnum eq '')) {
                   7379:         if ($env{'request.course.id'}) {
                   7380:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7381:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7382:         }
                   7383:         if (($cdom eq '') || ($cnum eq '')) {
                   7384:             return ('','ok','call to get suffix not in course context');
                   7385:         }
                   7386:     }
                   7387: 
                   7388: # construct locking item
                   7389:     my $lockhash = {
                   7390:                       $prefix."\0".'locked_'.$keyid => $who,
                   7391:                    };
                   7392:     my $tries = 0;
                   7393: 
                   7394: # attempt to get lock on nohist_$namespace file
                   7395:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7396:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7397:         $tries ++;
                   7398:         sleep 1;
                   7399:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7400:     }
                   7401: 
                   7402: # attempt to get unique identifier, based on current timestamp
                   7403:     if ($gotlock eq 'ok') {
                   7404:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7405:         my $id = time;
                   7406:         $newid = $id;
1.1172.2.56  raeburn  7407:         if ($idtype eq 'addcode') {
                   7408:             $newid .= &sixnum_code();
                   7409:         }
1.1172.2.13  raeburn  7410:         my $idtries = 0;
                   7411:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7412:             if ($idtype eq 'concat') {
                   7413:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7414:             } elsif ($idtype eq 'addcode') {
                   7415:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7416:             } else {
                   7417:                 $newid ++;
                   7418:             }
                   7419:             $idtries ++;
                   7420:         }
                   7421:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7422:             my %new_item =  (
                   7423:                               $prefix."\0".$newid => $who,
                   7424:                             );
                   7425:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7426:                                                  $cdom,$cnum);
                   7427:             if ($putresult ne 'ok') {
                   7428:                 undef($newid);
                   7429:                 $error = 'error saving new item: '.$putresult;
                   7430:             }
                   7431:         } else {
1.1172.2.56  raeburn  7432:              undef($newid);
1.1172.2.13  raeburn  7433:              $error = ('error: no unique suffix available for the new item ');
                   7434:         }
                   7435: #  remove lock
                   7436:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7437:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7438:     } else {
                   7439:         $error = "error: could not obtain lockfile\n";
                   7440:         $dellock = 'ok';
1.1172.2.58  raeburn  7441:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7442:             $dellock = 'nolock';
                   7443:         }
1.1172.2.13  raeburn  7444:     }
                   7445:     return ($newid,$dellock,$error);
                   7446: }
                   7447: 
1.1172.2.56  raeburn  7448: sub sixnum_code {
                   7449:     my $code;
                   7450:     for (0..6) {
                   7451:         $code .= int( rand(9) );
                   7452:     }
                   7453:     return $code;
                   7454: }
                   7455: 
1.765     albertel 7456: # -------------------------------------------------- portfolio access checking
                   7457: 
                   7458: sub portfolio_access {
1.1172.2.77  raeburn  7459:     my ($requrl,$clientip) = @_;
1.765     albertel 7460:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7461:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7462:     if ($result) {
                   7463:         my %setters;
                   7464:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7465:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7466:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7467:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7468:                 return 'B';
                   7469:             }
                   7470:         } else {
1.1172.2.142  raeburn  7471:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7472:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7473:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7474:                 return 'B';
                   7475:             }
                   7476:         }
                   7477:     }
1.765     albertel 7478:     if ($result eq 'ok') {
1.766     albertel 7479:        return 'F';
1.765     albertel 7480:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7481:        return 'A';
1.765     albertel 7482:     }
1.766     albertel 7483:     return '';
1.765     albertel 7484: }
                   7485: 
                   7486: sub get_portfolio_access {
1.1172.2.77  raeburn  7487:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7488: 
                   7489:     if (!ref($access_hash)) {
                   7490: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7491: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7492: 						   $file_name);
                   7493: 	$access_hash = $access_controls{$file_name};
                   7494:     }
                   7495: 
1.1172.2.77  raeburn  7496:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7497:     my $now = time;
                   7498:     if (ref($access_hash) eq 'HASH') {
                   7499:         foreach my $key (keys(%{$access_hash})) {
                   7500:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7501:             if ($start > $now) {
                   7502:                 next;
                   7503:             }
                   7504:             if ($end && $end<$now) {
                   7505:                 next;
                   7506:             }
                   7507:             if ($scope eq 'public') {
                   7508:                 $public = $key;
                   7509:                 last;
                   7510:             } elsif ($scope eq 'guest') {
                   7511:                 $guest = $key;
                   7512:             } elsif ($scope eq 'domains') {
                   7513:                 push(@domains,$key);
                   7514:             } elsif ($scope eq 'users') {
                   7515:                 push(@users,$key);
                   7516:             } elsif ($scope eq 'course') {
                   7517:                 push(@courses,$key);
                   7518:             } elsif ($scope eq 'group') {
                   7519:                 push(@groups,$key);
1.1172.2.77  raeburn  7520:             } elsif ($scope eq 'ip') {
                   7521:                 push(@ips,$key);
1.765     albertel 7522:             }
                   7523:         }
                   7524:         if ($public) {
                   7525:             return 'ok';
1.1172.2.77  raeburn  7526:         } elsif (@ips > 0) {
                   7527:             my $allowed;
                   7528:             foreach my $ipkey (@ips) {
                   7529:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7530:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7531:                         $allowed = 1;
                   7532:                         last;
                   7533:                     }
                   7534:                 }
                   7535:             }
                   7536:             if ($allowed) {
                   7537:                 return 'ok';
                   7538:             }
1.765     albertel 7539:         }
                   7540:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7541:             if ($guest) {
                   7542:                 return $guest;
                   7543:             }
                   7544:         } else {
                   7545:             if (@domains > 0) {
                   7546:                 foreach my $domkey (@domains) {
                   7547:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7548:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7549:                             return 'ok';
                   7550:                         }
                   7551:                     }
                   7552:                 }
                   7553:             }
                   7554:             if (@users > 0) {
                   7555:                 foreach my $userkey (@users) {
1.865     raeburn  7556:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7557:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7558:                             if (ref($item) eq 'HASH') {
                   7559:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7560:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7561:                                     return 'ok';
                   7562:                                 }
                   7563:                             }
                   7564:                         }
                   7565:                     } 
1.765     albertel 7566:                 }
                   7567:             }
                   7568:             my %roleshash;
                   7569:             my @courses_and_groups = @courses;
                   7570:             push(@courses_and_groups,@groups); 
                   7571:             if (@courses_and_groups > 0) {
                   7572:                 my (%allgroups,%allroles); 
                   7573:                 my ($start,$end,$role,$sec,$group);
                   7574:                 foreach my $envkey (%env) {
1.1060    raeburn  7575:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7576:                         my $cid = $2.'_'.$3; 
                   7577:                         if ($1 eq 'gr') {
                   7578:                             $group = $4;
                   7579:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7580:                         } else {
                   7581:                             if ($4 eq '') {
                   7582:                                 $sec = 'none';
                   7583:                             } else {
                   7584:                                 $sec = $4;
                   7585:                             }
                   7586:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7587:                         }
1.811     albertel 7588:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7589:                         my $cid = $2.'_'.$3;
                   7590:                         if ($4 eq '') {
                   7591:                             $sec = 'none';
                   7592:                         } else {
                   7593:                             $sec = $4;
                   7594:                         }
                   7595:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7596:                     }
                   7597:                 }
                   7598:                 if (keys(%allroles) == 0) {
                   7599:                     return;
                   7600:                 }
                   7601:                 foreach my $key (@courses_and_groups) {
                   7602:                     my %content = %{$$access_hash{$key}};
                   7603:                     my $cnum = $content{'number'};
                   7604:                     my $cdom = $content{'domain'};
                   7605:                     my $cid = $cdom.'_'.$cnum;
                   7606:                     if (!exists($allroles{$cid})) {
                   7607:                         next;
                   7608:                     }    
                   7609:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7610:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7611:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7612:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7613:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7614:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7615:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7616:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7617:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7618:                                         if (grep/^all$/,@sections) {
                   7619:                                             return 'ok';
                   7620:                                         } else {
                   7621:                                             if (grep/^$sec$/,@sections) {
                   7622:                                                 return 'ok';
                   7623:                                             }
                   7624:                                         }
                   7625:                                     }
                   7626:                                 }
                   7627:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7628:                                     if (grep/^none$/,@groups) {
                   7629:                                         return 'ok';
                   7630:                                     }
                   7631:                                 } else {
                   7632:                                     if (grep/^all$/,@groups) {
                   7633:                                         return 'ok';
                   7634:                                     } 
                   7635:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7636:                                         if (grep/^$group$/,@groups) {
                   7637:                                             return 'ok';
                   7638:                                         }
                   7639:                                     }
                   7640:                                 } 
                   7641:                             }
                   7642:                         }
                   7643:                     }
                   7644:                 }
                   7645:             }
                   7646:             if ($guest) {
                   7647:                 return $guest;
                   7648:             }
                   7649:         }
                   7650:     }
                   7651:     return;
                   7652: }
                   7653: 
                   7654: sub course_group_datechecker {
                   7655:     my ($dates,$now,$status) = @_;
                   7656:     my ($start,$end) = split(/\./,$dates);
                   7657:     if (!$start && !$end) {
                   7658:         return 'ok';
                   7659:     }
                   7660:     if (grep/^active$/,@{$status}) {
                   7661:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7662:             return 'ok';
                   7663:         }
                   7664:     }
                   7665:     if (grep/^previous$/,@{$status}) {
                   7666:         if ($end > $now ) {
                   7667:             return 'ok';
                   7668:         }
                   7669:     }
                   7670:     if (grep/^future$/,@{$status}) {
                   7671:         if ($start > $now) {
                   7672:             return 'ok';
                   7673:         }
                   7674:     }
                   7675:     return; 
                   7676: }
                   7677: 
                   7678: sub parse_portfolio_url {
                   7679:     my ($url) = @_;
                   7680: 
                   7681:     my ($type,$udom,$unum,$group,$file_name);
                   7682:     
1.823     albertel 7683:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7684: 	$type = 1;
                   7685:         $udom = $1;
                   7686:         $unum = $2;
                   7687:         $file_name = $3;
1.823     albertel 7688:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7689: 	$type = 2;
                   7690:         $udom = $1;
                   7691:         $unum = $2;
                   7692:         $group = $3;
                   7693:         $file_name = $3.'/'.$4;
                   7694:     }
                   7695:     if (wantarray) {
                   7696: 	return ($type,$udom,$unum,$file_name,$group);
                   7697:     }
                   7698:     return $type;
                   7699: }
                   7700: 
                   7701: sub is_portfolio_url {
                   7702:     my ($url) = @_;
                   7703:     return scalar(&parse_portfolio_url($url));
                   7704: }
                   7705: 
1.798     raeburn  7706: sub is_portfolio_file {
                   7707:     my ($file) = @_;
1.820     raeburn  7708:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7709:         return 1;
                   7710:     }
                   7711:     return;
                   7712: }
                   7713: 
1.976     raeburn  7714: sub usertools_access {
1.1084    raeburn  7715:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7716:     my ($access,%tools);
                   7717:     if ($context eq '') {
                   7718:         $context = 'tools';
                   7719:     }
                   7720:     if ($context eq 'requestcourses') {
                   7721:         %tools = (
                   7722:                       official   => 1,
                   7723:                       unofficial => 1,
1.1006    raeburn  7724:                       community  => 1,
1.1172.2.37  raeburn  7725:                       textbook   => 1,
1.985     raeburn  7726:                  );
1.1172.2.9  raeburn  7727:     } elsif ($context eq 'requestauthor') {
                   7728:         %tools = (
                   7729:                       requestauthor => 1,
                   7730:                  );
1.985     raeburn  7731:     } else {
                   7732:         %tools = (
                   7733:                       aboutme   => 1,
                   7734:                       blog      => 1,
1.1172.2.6  raeburn  7735:                       webdav    => 1,
1.985     raeburn  7736:                       portfolio => 1,
                   7737:                  );
                   7738:     }
1.976     raeburn  7739:     return if (!defined($tools{$tool}));
                   7740: 
1.1172.2.35  raeburn  7741:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7742:         $udom = $env{'user.domain'};
                   7743:         $uname = $env{'user.name'};
                   7744:     }
                   7745: 
1.978     raeburn  7746:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7747:         if ($action ne 'reload') {
1.985     raeburn  7748:             if ($context eq 'requestcourses') {
                   7749:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7750:             } elsif ($context eq 'requestauthor') {
                   7751:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7752:             } else {
                   7753:                 return $env{'environment.availabletools.'.$tool};
                   7754:             }
                   7755:         }
1.976     raeburn  7756:     }
                   7757: 
1.1172.2.9  raeburn  7758:     my ($toolstatus,$inststatus,$envkey);
                   7759:     if ($context eq 'requestauthor') {
                   7760:         $envkey = $context;
                   7761:     } else {
                   7762:         $envkey = $context.'.'.$tool;
                   7763:     }
1.976     raeburn  7764: 
1.985     raeburn  7765:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7766:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7767:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7768:         $inststatus = $env{'environment.inststatus'};
                   7769:     } else {
1.1084    raeburn  7770:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7771:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7772:             $inststatus = $userenvref->{'inststatus'};
                   7773:         } else {
1.1172.2.9  raeburn  7774:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7775:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7776:             $inststatus = $userenv{'inststatus'};
                   7777:         }
1.976     raeburn  7778:     }
                   7779: 
                   7780:     if ($toolstatus ne '') {
                   7781:         if ($toolstatus) {
                   7782:             $access = 1;
                   7783:         } else {
                   7784:             $access = 0;
                   7785:         }
                   7786:         return $access;
                   7787:     }
                   7788: 
1.1084    raeburn  7789:     my ($is_adv,%domdef);
                   7790:     if (ref($is_advref) eq 'HASH') {
                   7791:         $is_adv = $is_advref->{'is_adv'};
                   7792:     } else {
                   7793:         $is_adv = &is_advanced_user($udom,$uname);
                   7794:     }
                   7795:     if (ref($domdefref) eq 'HASH') {
                   7796:         %domdef = %{$domdefref};
                   7797:     } else {
                   7798:         %domdef = &get_domain_defaults($udom);
                   7799:     }
1.976     raeburn  7800:     if (ref($domdef{$tool}) eq 'HASH') {
                   7801:         if ($is_adv) {
                   7802:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7803:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7804:                     $access = 1;
                   7805:                 } else {
                   7806:                     $access = 0;
                   7807:                 }
                   7808:                 return $access;
                   7809:             }
                   7810:         }
                   7811:         if ($inststatus ne '') {
                   7812:             my ($hasaccess,$hasnoaccess);
                   7813:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7814:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7815:                     if ($domdef{$tool}{$affiliation}) {
                   7816:                         $hasaccess = 1;
                   7817:                     } else {
                   7818:                         $hasnoaccess = 1;
                   7819:                     }
                   7820:                 }
                   7821:             }
                   7822:             if ($hasaccess || $hasnoaccess) {
                   7823:                 if ($hasaccess) {
                   7824:                     $access = 1;
                   7825:                 } elsif ($hasnoaccess) {
                   7826:                     $access = 0; 
                   7827:                 }
                   7828:                 return $access;
                   7829:             }
                   7830:         } else {
                   7831:             if ($domdef{$tool}{'default'} ne '') {
                   7832:                 if ($domdef{$tool}{'default'}) {
                   7833:                     $access = 1;
                   7834:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7835:                     $access = 0;
                   7836:                 }
                   7837:                 return $access;
                   7838:             }
                   7839:         }
                   7840:     } else {
1.1172.2.6  raeburn  7841:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7842:             $access = 1;
                   7843:         } else {
                   7844:             $access = 0;
                   7845:         }
1.976     raeburn  7846:         return $access;
                   7847:     }
                   7848: }
                   7849: 
1.1050    raeburn  7850: sub is_course_owner {
                   7851:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7852:     if (($udom eq '') || ($uname eq '')) {
                   7853:         $udom = $env{'user.domain'};
                   7854:         $uname = $env{'user.name'};
                   7855:     }
                   7856:     unless (($udom eq '') || ($uname eq '')) {
                   7857:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7858:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7859:                 return 1;
                   7860:             } else {
                   7861:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7862:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7863:                     return 1;
                   7864:                 }
                   7865:             }
                   7866:         }
                   7867:     }
                   7868:     return;
                   7869: }
                   7870: 
1.976     raeburn  7871: sub is_advanced_user {
                   7872:     my ($udom,$uname) = @_;
1.1085    raeburn  7873:     if ($udom ne '' && $uname ne '') {
                   7874:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7875:             if (wantarray) {
                   7876:                 return ($env{'user.adv'},$env{'user.author'});
                   7877:             } else {
                   7878:                 return $env{'user.adv'};
                   7879:             }
1.1085    raeburn  7880:         }
                   7881:     }
1.976     raeburn  7882:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7883:     my %allroles;
1.1128    raeburn  7884:     my ($is_adv,$is_author);
1.976     raeburn  7885:     foreach my $role (keys(%roleshash)) {
                   7886:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7887:         my $area = '/'.$tdomain.'/'.$trest;
                   7888:         if ($sec ne '') {
                   7889:             $area .= '/'.$sec;
                   7890:         }
                   7891:         if (($area ne '') && ($trole ne '')) {
                   7892:             my $spec=$trole.'.'.$area;
                   7893:             if ($trole =~ /^cr\//) {
                   7894:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7895:             } elsif ($trole ne 'gr') {
                   7896:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7897:             }
1.1128    raeburn  7898:             if ($trole eq 'au') {
                   7899:                 $is_author = 1;
                   7900:             }
1.976     raeburn  7901:         }
                   7902:     }
                   7903:     foreach my $role (keys(%allroles)) {
                   7904:         last if ($is_adv);
                   7905:         foreach my $item (split(/:/,$allroles{$role})) {
                   7906:             if ($item ne '') {
                   7907:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7908:                 if ($privilege eq 'adv') {
                   7909:                     $is_adv = 1;
                   7910:                     last;
                   7911:                 }
                   7912:             }
                   7913:         }
                   7914:     }
1.1128    raeburn  7915:     if (wantarray) {
                   7916:         return ($is_adv,$is_author);
                   7917:     }
1.976     raeburn  7918:     return $is_adv;
                   7919: }
1.798     raeburn  7920: 
1.1035    raeburn  7921: sub check_can_request {
1.1036    raeburn  7922:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7923:     my $canreq = 0;
                   7924:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7925:     my @options = ('approval','validate','autolimit');
                   7926:     my $optregex = join('|',@options);
                   7927:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7928:         foreach my $type (@{$types}) {
                   7929:             if (&usertools_access($env{'user.name'},
                   7930:                                   $env{'user.domain'},
                   7931:                                   $type,undef,'requestcourses')) {
                   7932:                 $canreq ++;
1.1036    raeburn  7933:                 if (ref($request_domains) eq 'HASH') {
                   7934:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7935:                 }
1.1035    raeburn  7936:                 if ($dom eq $env{'user.domain'}) {
                   7937:                     $can_request->{$type} = 1;
                   7938:                 }
                   7939:             }
                   7940:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7941:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7942:                 if (@curr > 0) {
1.1036    raeburn  7943:                     foreach my $item (@curr) {
                   7944:                         if (ref($request_domains) eq 'HASH') {
                   7945:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7946:                             if ($otherdom ne '') {
                   7947:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7948:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7949:                                         push(@{$request_domains->{$type}},$otherdom);
                   7950:                                     }
                   7951:                                 } else {
                   7952:                                     push(@{$request_domains->{$type}},$otherdom);
                   7953:                                 }
                   7954:                             }
                   7955:                         }
                   7956:                     }
                   7957:                     unless($dom eq $env{'user.domain'}) {
                   7958:                         $canreq ++;
1.1035    raeburn  7959:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7960:                             $can_request->{$type} = 1;
                   7961:                         }
                   7962:                     }
                   7963:                 }
                   7964:             }
                   7965:         }
                   7966:     }
                   7967:     return $canreq;
                   7968: }
                   7969: 
1.341     www      7970: # ---------------------------------------------- Custom access rule evaluation
                   7971: 
                   7972: sub customaccess {
                   7973:     my ($priv,$uri)=@_;
1.807     albertel 7974:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7975:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7976:     $udom = &LONCAPA::clean_domain($udom);
                   7977:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7978:     my $access=0;
1.800     albertel 7979:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7980: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7981: 	if ($type eq 'user') {
                   7982: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7983: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7984: 		if ($tdom) {
                   7985: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7986: 		}
1.896     albertel 7987: 		if ($tuname) {
                   7988: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7989: 		}
                   7990: 		$access=($effect eq 'allow');
                   7991: 		last;
                   7992: 	    }
                   7993: 	} else {
                   7994: 	    if ($role) {
                   7995: 		if ($role ne $urole) { next; }
                   7996: 	    }
                   7997: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7998: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7999: 		if ($tdom) {
                   8000: 		    if ($tdom ne $udom) { next; }
                   8001: 		}
                   8002: 		if ($tcrs) {
                   8003: 		    if ($tcrs ne $ucrs) { next; }
                   8004: 		}
                   8005: 		if ($tsec) {
                   8006: 		    if ($tsec ne $usec) { next; }
                   8007: 		}
                   8008: 		$access=($effect eq 'allow');
                   8009: 		last;
                   8010: 	    }
                   8011: 	    if ($realm eq '' && $role eq '') {
                   8012: 		$access=($effect eq 'allow');
                   8013: 	    }
1.402     bowersj2 8014: 	}
1.341     www      8015:     }
                   8016:     return $access;
                   8017: }
                   8018: 
1.103     harris41 8019: # ------------------------------------------------- Check for a user privilege
1.12      www      8020: 
                   8021: sub allowed {
1.1172.2.146.  .1(raebu 8022:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8023:     my $ver_orguri=$uri;
1.439     www      8024:     $uri=&deversion($uri);
1.152     www      8025:     my $orguri=$uri;
1.52      www      8026:     $uri=&declutter($uri);
1.809     raeburn  8027: 
1.810     raeburn  8028:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8029:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8030:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8031:             return $1;
                   8032:         } else {
                   8033:             return;
                   8034:         }
                   8035:     }
                   8036: 
1.620     albertel 8037:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8038: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8039:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8040: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8041: 	&& ($priv eq 'bre')) {
1.14      www      8042: 	return 'F';
1.159     www      8043:     }
                   8044: 
1.545     banghart 8045: # Free bre access to user's own portfolio contents
1.714     raeburn  8046:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8047:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8048: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8049:         my %setters;
1.1172.2.142  raeburn  8050:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8051:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8052:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8053:             return 'B';
                   8054:         } else {
                   8055:             return 'F';
                   8056:         }
1.545     banghart 8057:     }
                   8058: 
1.762     raeburn  8059: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8060:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8061:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8062:         if (exists($env{'request.course.id'})) {
                   8063:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8064:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8065:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8066:                 my $courseprivid=$env{'request.course.id'};
                   8067:                 $courseprivid=~s/\_/\//;
                   8068:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8069:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8070:                     return $1; 
1.762     raeburn  8071:                 } else {
                   8072:                     if ($env{'request.course.sec'}) {
                   8073:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8074:                     }
                   8075:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8076:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8077:                         return $2;
                   8078:                     }
1.714     raeburn  8079:                 }
                   8080:             }
                   8081:         }
                   8082:     }
                   8083: 
1.159     www      8084: # Free bre to public access
                   8085: 
                   8086:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8087:22):         my $copyright;
                   8088:22):         unless ($uri =~ /ext\.tool/) {
                   8089:22):             $copyright=&metadata($uri,'copyright');
                   8090:22):         }
1.620     albertel 8091: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8092:            return 'F'; 
                   8093:         }
1.238     www      8094:         if ($copyright eq 'priv') {
                   8095:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8096: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8097: 		return '';
                   8098:             }
                   8099:         }
                   8100:         if ($copyright eq 'domain') {
                   8101:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8102: 	    unless (($env{'user.domain'} eq $1) ||
                   8103:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8104: 		return '';
                   8105:             }
1.262     matthew  8106:         }
1.620     albertel 8107:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8108:             # Library role, so allow browsing of resources in this domain.
                   8109:             return 'F';
1.238     www      8110:         }
1.341     www      8111:         if ($copyright eq 'custom') {
                   8112: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8113:         }
1.14      www      8114:     }
1.264     matthew  8115:     # Domain coordinator is trying to create a course
1.620     albertel 8116:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8117:         # uri is the requested domain in this case.
                   8118:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8119:         # a role of dc for the domain in question.
1.620     albertel 8120:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8121:     }
1.29      www      8122: 
1.52      www      8123:     my $thisallowed='';
                   8124:     my $statecond=0;
                   8125:     my $courseprivid='';
                   8126: 
1.1039    raeburn  8127:     my $ownaccess;
1.1043    raeburn  8128:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8129:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8130:         if ($uri eq '') {
                   8131:             $ownaccess = 1;
                   8132:         } else {
                   8133:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8134:                 my $udom = $env{'user.domain'};
                   8135:                 my $uname = $env{'user.name'};
                   8136:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8137:                     $ownaccess = 1;
1.1040    raeburn  8138:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8139:                     unless ($uri =~ m{\.\./}) {
                   8140:                         $ownaccess = 1;
                   8141:                     }
                   8142:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8143:                     my $now = time;
                   8144:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8145:                         my $adom = $1;
                   8146:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8147:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8148:                                 my ($start,$end) = split(/\./,$env{$key});
                   8149:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8150:                                     $ownaccess = 1;
                   8151:                                     last;
                   8152:                                 }
                   8153:                             }
                   8154:                         }
                   8155:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8156:                         my $adom = $1;
                   8157:                         my $aname = $2;
1.1042    raeburn  8158:                         foreach my $role ('ca','aa') { 
                   8159:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8160:                                 my ($start,$end) =
1.1172.2.142  raeburn  8161:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8162:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8163:                                     $ownaccess = 1;
                   8164:                                     last;
                   8165:                                 }
1.1039    raeburn  8166:                             }
                   8167:                         }
                   8168:                     }
                   8169:                 }
                   8170:             }
                   8171:         }
                   8172:     }
                   8173: 
1.52      www      8174: # Course
                   8175: 
1.620     albertel 8176:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8177:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8178:             $thisallowed.=$1;
                   8179:         }
1.52      www      8180:     }
1.29      www      8181: 
1.52      www      8182: # Domain
                   8183: 
1.620     albertel 8184:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8185:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8186:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8187:             $thisallowed.=$1;
                   8188:         }
1.12      www      8189:     }
1.52      www      8190: 
1.1141    raeburn  8191: # User who is not author or co-author might still be able to edit
                   8192: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8193:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8194:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8195:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8196:             $thisallowed.=$1;
                   8197:         }
                   8198:     }
                   8199: 
1.52      www      8200: # Course: uri itself is a course
1.66      www      8201:     my $courseuri=$uri;
                   8202:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8203:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8204: 
1.620     albertel 8205:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8206:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8207:         if ($priv eq 'mip') {
                   8208:             my $rem = $1;
                   8209:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8210:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8211:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8212:                 if ($cdom ne '') {
                   8213:                     my %passwdconf = &get_passwdconf($cdom);
                   8214:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8215:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8216:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8217:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8218:                                 unless (@inststatuses) {
                   8219:                                     @inststatuses = ('default');
                   8220:                                 }
                   8221:                                 foreach my $status (@inststatuses) {
                   8222:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8223:                                         $thisallowed.=$rem;
                   8224:                                     }
                   8225:                                 }
                   8226:                             }
                   8227:                         }
                   8228:                     }
                   8229:                 }
                   8230:             }
                   8231:         } else {
                   8232:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8233:                 $thisallowed.=$1;
                   8234:             }
1.1039    raeburn  8235:         }
1.12      www      8236:     }
1.29      www      8237: 
1.665     albertel 8238: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8239: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8240:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8241: 	$thisallowed='';
1.671     raeburn  8242:         my ($match)=&is_on_map($uri);
                   8243:         if ($match) {
                   8244:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8245:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8246:                 my $value = $1;
1.1172.2.146.  .1(raebu 8247:22):                 my $deeplinkblock;
                   8248:22):                 unless ($nodeeplinkcheck) {
                   8249:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8250:22):                 }
                   8251:22):                 if ($deeplinkblock) {
                   8252:22):                     $thisallowed='D';
                   8253:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8254:                     $thisallowed.=$value;
1.1162    raeburn  8255:                 } else {
1.1172.2.126  raeburn  8256:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8257:                     if (@blockers > 0) {
                   8258:                         $thisallowed = 'B';
                   8259:                     } else {
                   8260:                         $thisallowed.=$value;
                   8261:                     }
1.1162    raeburn  8262:                 }
1.671     raeburn  8263:             }
                   8264:         } else {
1.705     albertel 8265:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8266:             if ($refuri) {
                   8267:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8268:                     $thisallowed='F';
1.671     raeburn  8269:                 } else {
                   8270:                     $refuri=&declutter($refuri);
                   8271:                     my ($match) = &is_on_map($refuri);
                   8272:                     if ($match) {
1.1172.2.146.  .1(raebu 8273:22):                         my $deeplinkblock;
                   8274:22):                         unless ($nodeeplinkcheck) {
                   8275:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8276:22):                         }
                   8277:22):                         if ($deeplinkblock) {
                   8278:22):                             $thisallowed='D';
                   8279:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8280:                             $thisallowed='F';
1.1172.2.65  raeburn  8281:                         } else {
1.1172.2.127  raeburn  8282:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8283:                             if (@blockers > 0) {
                   8284:                                 $thisallowed = 'B';
                   8285:                             } else {
                   8286:                                 $thisallowed='F';
                   8287:                             }
1.1162    raeburn  8288:                         }
1.671     raeburn  8289:                     }
1.669     raeburn  8290:                 }
1.671     raeburn  8291:             }
                   8292:         }
1.314     www      8293:     }
1.492     albertel 8294: 
1.766     albertel 8295:     if ($priv eq 'bre'
                   8296: 	&& $thisallowed ne 'F' 
                   8297: 	&& $thisallowed ne '2'
                   8298: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8299: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8300:     }
                   8301:     
1.52      www      8302: # Full access at system, domain or course-wide level? Exit.
1.29      www      8303:     if ($thisallowed=~/F/) {
                   8304: 	return 'F';
                   8305:     }
                   8306: 
1.52      www      8307: # If this is generating or modifying users, exit with special codes
1.29      www      8308: 
1.643     www      8309:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8310: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8311: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8312: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8313: 	    unless ($auname) { return $thisallowed; }
                   8314: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8315: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8316: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8317: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8318: 	}
1.52      www      8319: 	return $thisallowed;
                   8320:     }
                   8321: #
1.103     harris41 8322: # Gathered so far: system, domain and course wide privileges
1.52      www      8323: #
                   8324: # Course: See if uri or referer is an individual resource that is part of 
                   8325: # the course
                   8326: 
1.620     albertel 8327:     if ($env{'request.course.id'}) {
1.232     www      8328: 
1.1172.2.115  raeburn  8329: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8330: 
                   8331:         if ($priv eq 'mip') {
                   8332:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8333:                 return $thisallowed;
                   8334:             } else {
                   8335:                 return '';
                   8336:             }
                   8337:         }
                   8338: 
1.620     albertel 8339:        $courseprivid=$env{'request.course.id'};
                   8340:        if ($env{'request.course.sec'}) {
                   8341:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8342:        }
                   8343:        $courseprivid=~s/\_/\//;
                   8344:        my $checkreferer=1;
1.232     www      8345:        my ($match,$cond)=&is_on_map($uri);
                   8346:        if ($match) {
                   8347:            $statecond=$cond;
1.620     albertel 8348:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8349:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8350:                my $value = $1;
                   8351:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8352:22):                    my $deeplinkblock;
                   8353:22):                    unless ($nodeeplinkcheck) {
                   8354:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8355:22):                    }
                   8356:22):                    if ($deeplinkblock) {
                   8357:22):                        $thisallowed = 'D';
                   8358:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8359:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8360:                    } else {
1.1172.2.126  raeburn  8361:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8362:                        if (@blockers > 0) {
                   8363:                            $thisallowed = 'B';
                   8364:                        } else {
                   8365:                            $thisallowed.=$value;
                   8366:                        }
1.1162    raeburn  8367:                    }
                   8368:                } else {
                   8369:                    $thisallowed.=$value;
                   8370:                }
1.52      www      8371:                $checkreferer=0;
                   8372:            }
1.29      www      8373:        }
1.1172.2.126  raeburn  8374: 
1.148     www      8375:        if ($checkreferer) {
1.620     albertel 8376: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8377:             unless ($refuri) {
1.800     albertel 8378:                 foreach my $key (keys(%env)) {
                   8379: 		    if ($key=~/^httpref\..*\*/) {
                   8380: 			my $pattern=$key;
1.156     www      8381:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8382:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8383:                         $pattern=~s/\//\\\//g;
1.152     www      8384:                         if ($orguri=~/$pattern/) {
1.800     albertel 8385: 			    $refuri=$env{$key};
1.148     www      8386:                         }
                   8387:                     }
1.191     harris41 8388:                 }
1.148     www      8389:             }
1.232     www      8390: 
1.148     www      8391:          if ($refuri) { 
1.152     www      8392: 	  $refuri=&declutter($refuri);
1.232     www      8393:           my ($match,$cond)=&is_on_map($refuri);
                   8394:             if ($match) {
                   8395:               my $refstatecond=$cond;
1.620     albertel 8396:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8397:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8398:                   my $value = $1;
                   8399:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8400:22):                       my $deeplinkblock;
                   8401:22):                       unless ($nodeeplinkcheck) {
                   8402:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8403:22):                       }
                   8404:22):                       if ($deeplinkblock) {
                   8405:22):                           $thisallowed = 'D';
                   8406:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8407:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8408:                       } else {
1.1172.2.127  raeburn  8409:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8410:                           if (@blockers > 0) {
                   8411:                               $thisallowed = 'B';
                   8412:                           } else {
                   8413:                               $thisallowed.=$value;
                   8414:                           }
1.1162    raeburn  8415:                       }
                   8416:                   } else {
                   8417:                       $thisallowed.=$value;
                   8418:                   }
1.53      www      8419:                   $uri=$refuri;
                   8420:                   $statecond=$refstatecond;
1.52      www      8421:               }
                   8422:           }
1.148     www      8423:         }
1.29      www      8424:        }
1.52      www      8425:    }
1.29      www      8426: 
1.52      www      8427: #
1.103     harris41 8428: # Gathered now: all privileges that could apply, and condition number
1.52      www      8429: # 
                   8430: #
                   8431: # Full or no access?
                   8432: #
1.29      www      8433: 
1.52      www      8434:     if ($thisallowed=~/F/) {
                   8435: 	return 'F';
                   8436:     }
1.29      www      8437: 
1.52      www      8438:     unless ($thisallowed) {
                   8439:         return '';
                   8440:     }
1.29      www      8441: 
1.52      www      8442: # Restrictions exist, deal with them
                   8443: #
                   8444: #   C:according to course preferences
                   8445: #   R:according to resource settings
                   8446: #   L:unless locked
                   8447: #   X:according to user session state
                   8448: #
                   8449: 
                   8450: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8451: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8452: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8453: # courses, and 2 minutes for current course, in which user has st or ta role
                   8454: # which is neither expired nor a future role (unless current course).
1.52      www      8455: 
1.1172.2.142  raeburn  8456:     my ($needlockcheck,$now,$crsonly);
1.52      www      8457:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8458:         $now = time;
                   8459:         if ($priv eq 'bre') {
                   8460:             if ($uri ne '') {
                   8461:                 if ($orguri =~ m{^/+res/}) {
                   8462:                     if ($uri =~ m{^lib/templates/}) {
                   8463:                         if ($env{'request.course.id'}) {
                   8464:                             $crsonly = 1;
                   8465:                             $needlockcheck = 1;
                   8466:                         }
                   8467:                     } else {
                   8468:                         $needlockcheck = 1;
                   8469:                     }
                   8470:                 } elsif ($env{'request.course.id'}) {
                   8471:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8472:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8473:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8474:                         $crsonly = 1;
                   8475:                     }
                   8476:                     $needlockcheck = 1;
                   8477:                 }
                   8478:             }
                   8479:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8480:             $needlockcheck = 1;
                   8481:         }
                   8482:     }
                   8483:     if ($needlockcheck) {
                   8484:         foreach my $envkey (keys(%env)) {
1.54      www      8485:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8486:                my $courseid=$2;
                   8487:                my $roleid=$1.'.'.$2;
1.92      www      8488:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8489:                unless ($env{'request.role'} eq $roleid) {
                   8490:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8491:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8492:                }
1.54      www      8493:                my $expiretime=600;
1.620     albertel 8494:                if ($env{'request.role'} eq $roleid) {
1.54      www      8495: 		  $expiretime=120;
                   8496:                }
                   8497: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8498:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8499:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8500: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8501:                }
1.620     albertel 8502:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8503:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8504: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8505:                        &log($env{'user.domain'},$env{'user.name'},
                   8506:                             $env{'user.home'},
1.57      www      8507:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8508:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8509:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8510: 		       return '';
                   8511:                    }
                   8512:                }
1.620     albertel 8513:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8514:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8515: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8516:                        &log($env{'user.domain'},$env{'user.name'},
                   8517:                             $env{'user.home'},
1.57      www      8518:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8519:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8520:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8521: 		       return '';
                   8522:                    }
                   8523:                }
                   8524: 	   }
1.29      www      8525:        }
1.52      www      8526:     }
1.1172.2.126  raeburn  8527: 
1.52      www      8528: #
                   8529: # Rest of the restrictions depend on selected course
                   8530: #
                   8531: 
1.620     albertel 8532:     unless ($env{'request.course.id'}) {
1.766     albertel 8533: 	if ($thisallowed eq 'A') {
                   8534: 	    return 'A';
1.814     raeburn  8535:         } elsif ($thisallowed eq 'B') {
                   8536:             return 'B';
1.766     albertel 8537: 	} else {
                   8538: 	    return '1';
                   8539: 	}
1.52      www      8540:     }
1.29      www      8541: 
1.52      www      8542: #
                   8543: # Now user is definitely in a course
                   8544: #
1.53      www      8545: 
                   8546: 
                   8547: # Course preferences
                   8548: 
                   8549:    if ($thisallowed=~/C/) {
1.620     albertel 8550:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8551:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8552:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8553: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8554: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8555: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8556: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8557: 			$env{'request.course.id'});
                   8558: 	   }
1.237     www      8559:            return '';
                   8560:        }
                   8561: 
1.620     albertel 8562:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8563: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8564: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8565: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8566: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8567: 			$env{'request.course.id'});
                   8568: 	   }
1.54      www      8569:            return '';
                   8570:        }
1.53      www      8571:    }
                   8572: 
                   8573: # Resource preferences
                   8574: 
                   8575:    if ($thisallowed=~/R/) {
1.620     albertel 8576:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8577:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8578: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8579: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8580: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8581: 	   }
                   8582: 	   return '';
1.54      www      8583:        }
1.53      www      8584:    }
1.30      www      8585: 
1.1172.2.146.  .1(raebu 8586:22): # Restricted for deeplinked session?
                   8587:22): 
                   8588:22):     if ($env{'request.deeplink.login'}) {
                   8589:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8590:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8591:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8592:22):                 return '';
                   8593:22):             }
                   8594:22):         }
                   8595:22):     }
                   8596:22): 
1.246     www      8597: # Restricted by state or randomout?
1.30      www      8598: 
1.52      www      8599:    if ($thisallowed=~/X/) {
1.620     albertel 8600:       if ($env{'acc.randomout'}) {
1.579     albertel 8601: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8602:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8603:             return ''; 
                   8604:          }
1.247     www      8605:       }
                   8606:       if (&condval($statecond)) {
1.52      www      8607: 	 return '2';
                   8608:       } else {
                   8609:          return '';
                   8610:       }
                   8611:    }
1.30      www      8612: 
1.766     albertel 8613:     if ($thisallowed eq 'A') {
                   8614: 	return 'A';
1.814     raeburn  8615:     } elsif ($thisallowed eq 'B') {
                   8616:         return 'B';
1.1172.2.146.  .1(raebu 8617:22):     } elsif ($thisallowed eq 'D') {
                   8618:22):         return 'D';
1.766     albertel 8619:     }
1.52      www      8620:    return 'F';
1.232     www      8621: }
1.1162    raeburn  8622: 
1.1172.2.13  raeburn  8623: # ------------------------------------------- Check construction space access
                   8624: 
                   8625: sub constructaccess {
                   8626:     my ($url,$setpriv)=@_;
                   8627: 
                   8628: # We do not allow editing of previous versions of files
                   8629:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8630: 
                   8631: # Get username and domain from URL
                   8632:     my ($ownername,$ownerdomain,$ownerhome);
                   8633: 
                   8634:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8635:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8636: 
                   8637: # The URL does not really point to any authorspace, forget it
                   8638:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8639: 
                   8640: # Now we need to see if the user has access to the authorspace of
                   8641: # $ownername at $ownerdomain
                   8642: 
                   8643:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8644: # Real author for this?
                   8645:        $ownerhome = $env{'user.home'};
                   8646:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8647:           return ($ownername,$ownerdomain,$ownerhome);
                   8648:        }
                   8649:     } else {
                   8650: # Co-author for this?
                   8651:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8652:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8653:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8654:             return ($ownername,$ownerdomain,$ownerhome);
                   8655:         }
                   8656:     }
                   8657: 
                   8658: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8659: # we might as well leave
                   8660:    unless ($setpriv) { return ''; }
                   8661: 
                   8662: # Backdoor access?
                   8663:     my $allowed=&allowed('eco',$ownerdomain);
                   8664: # Nope
                   8665:     unless ($allowed) { return ''; }
                   8666: # Looks like we may have access, but could be locked by the owner of the construction space
                   8667:     if ($allowed eq 'U') {
                   8668:         my %blocked=&get('environment',['domcoord.author'],
                   8669:                          $ownerdomain,$ownername);
                   8670: # Is blocked by owner
                   8671:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8672:     }
                   8673:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8674: # Grant temporary access
                   8675:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8676:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8677:         if (!$update) { $update = $then; }
                   8678:         my $refresh=$env{'user.refresh.time'};
                   8679:         if (!$refresh) { $refresh = $update; }
                   8680:         my $now = time;
                   8681:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8682:                            $now,'ca','constructaccess');
                   8683:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8684:         return($ownername,$ownerdomain,$ownerhome);
                   8685:     }
                   8686: # No business here
                   8687:     return '';
                   8688: }
                   8689: 
1.1172.2.66  raeburn  8690: # ----------------------------------------------------------- Content Blocking
                   8691: 
                   8692: {
                   8693: # Caches for faster Course Contents display where content blocking
                   8694: # is in operation (i.e., interval param set) for timed quiz.
                   8695: #
                   8696: # User for whom data are being temporarily cached.
                   8697: my $cacheduser='';
1.1172.2.126  raeburn  8698: # Course for which data are being temporarily cached.
                   8699: my $cachedcid='';
1.1172.2.66  raeburn  8700: # Cached blockers for this user (a hash of blocking items).
                   8701: my %cachedblockers=();
                   8702: # When the data were last cached.
                   8703: my $cachedlast='';
                   8704: 
                   8705: sub load_all_blockers {
1.1172.2.128  raeburn  8706:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8707:     if (($uname ne '') && ($udom ne '')) {
                   8708:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8709:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8710:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8711:             return;
                   8712:         }
                   8713:     }
                   8714:     $cachedlast=time;
                   8715:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8716:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8717:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8718:     return;
1.1172.2.66  raeburn  8719: }
                   8720: 
1.1162    raeburn  8721: sub get_comm_blocks {
                   8722:     my ($cdom,$cnum) = @_;
                   8723:     if ($cdom eq '' || $cnum eq '') {
                   8724:         return unless ($env{'request.course.id'});
                   8725:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8726:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8727:     }
                   8728:     my %commblocks;
                   8729:     my $hashid=$cdom.'_'.$cnum;
                   8730:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8731:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8732:         %commblocks = %{$blocksref};
                   8733:     } else {
                   8734:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8735:         my $cachetime = 600;
                   8736:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8737:     }
                   8738:     return %commblocks;
                   8739: }
                   8740: 
1.1172.2.66  raeburn  8741: sub get_commblock_resources {
                   8742:     my ($blocks) = @_;
                   8743:     my %blockers = ();
                   8744:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8745:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8746:     if ($env{'request.course.sec'}) {
                   8747:         $courseurl .= '/'.$env{'request.course.sec'};
                   8748:     }
                   8749:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8750:     my %commblocks;
                   8751:     if (ref($blocks) eq 'HASH') {
                   8752:         %commblocks = %{$blocks};
                   8753:     } else {
                   8754:         %commblocks = &get_comm_blocks();
                   8755:     }
1.1172.2.66  raeburn  8756:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8757:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8758:     return %blockers unless (ref($navmap));
                   8759:     my $now = time;
1.1162    raeburn  8760:     foreach my $block (keys(%commblocks)) {
                   8761:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8762:             my ($start,$end) = ($1,$2);
                   8763:             if ($start <= $now && $end >= $now) {
                   8764:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8765:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8766:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8767:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8768:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8769:                             }
                   8770:                         }
                   8771:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8772:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8773:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8774:                             }
                   8775:                         }
                   8776:                     }
                   8777:                 }
                   8778:             }
                   8779:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8780:             my $item = $1;
                   8781:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8782:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8783:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8784:                     my $type = 'map';
                   8785:                     if ($item eq 'course') {
                   8786:                         $type = 'course';
                   8787:                         @interval=&EXT("resource.0.interval");
                   8788:                     } else {
                   8789:                         if ($item =~ /___\d+___/) {
                   8790:                             $type = 'resource';
                   8791:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8792:                         } else {
1.1172.2.142  raeburn  8793:                             $mapname = &deversion($item);
                   8794:                             if (ref($navmap)) {
                   8795:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8796:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8797:                             }
                   8798:                         }
1.1172.2.66  raeburn  8799:                     }
1.1172.2.146.  .1(raebu 8800:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8801:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8802:                         my $first_access;
                   8803:                         if ($type eq 'resource') {
                   8804:                             $first_access=&get_first_access($interval[1],$item);
                   8805:                         } elsif ($type eq 'map') {
                   8806:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8807:                         } else {
                   8808:                             $first_access=&get_first_access($interval[1]);
                   8809:                         }
                   8810:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8811:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8812:                             if ($timesup > $now) {
                   8813:                                 my $activeblock;
1.1172.2.142  raeburn  8814:                                 if ($type eq 'resource') {
                   8815:                                     if (ref($navmap)) {
                   8816:                                         my $res = $navmap->getBySymb($item);
                   8817:                                         if ($res->answerable()) {
                   8818:                                             $activeblock = 1;
                   8819:                                         }
                   8820:                                     }
                   8821:                                 } elsif ($type eq 'map') {
                   8822:                                     my $mapsymb = &symbread($mapname,1);
                   8823:                                     if (($mapsymb) && (ref($navmap))) {
                   8824:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8825:                                         if (ref($mapres)) {
                   8826:                                             my $first = $mapres->map_start();
                   8827:                                             my $finish = $mapres->map_finish();
                   8828:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8829:                                             if (ref($it)) {
                   8830:                                                 my $res;
                   8831:                                                 while ($res = $it->next(undef,1)) {
                   8832:                                                     next unless (ref($res));
                   8833:                                                     my $symb = $res->symb();
                   8834:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8835:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8836:                                                     if ($interval[1] eq 'map') {
                   8837:                                                         if ($res->answerable()) {
                   8838:                                                             $activeblock = 1;
                   8839:                                                             last;
                   8840:                                                         }
                   8841:                                                     }
                   8842:                                                 }
                   8843:                                             }
                   8844:                                         }
1.1172.2.66  raeburn  8845:                                     }
                   8846:                                 }
                   8847:                                 if ($activeblock) {
                   8848:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8849:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8850:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8851:                                          }
                   8852:                                     }
                   8853:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8854:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8855:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8856:                                         }
1.1162    raeburn  8857:                                     }
                   8858:                                 }
                   8859:                             }
                   8860:                         }
                   8861:                     }
                   8862:                 }
                   8863:             }
                   8864:         }
                   8865:     }
1.1172.2.66  raeburn  8866:     return %blockers;
1.1162    raeburn  8867: }
                   8868: 
1.1172.2.66  raeburn  8869: sub has_comm_blocking {
1.1172.2.128  raeburn  8870:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8871:     my @blockers;
                   8872:     return unless ($env{'request.course.id'});
                   8873:     return unless ($priv eq 'bre');
                   8874:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8875:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8876:     if ($env{'request.course.sec'}) {
                   8877:         $courseurl .= '/'.$env{'request.course.sec'};
                   8878:     }
                   8879:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8880:     my %blockinfo;
                   8881:     if (ref($blocks) eq 'HASH') {
                   8882:         %blockinfo = &get_commblock_resources($blocks);
                   8883:     } else {
                   8884:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8885:         %blockinfo = %cachedblockers;
                   8886:     }
                   8887:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8888:     my (%possibles,@symbs);
                   8889:     if (!$symb) {
1.1172.2.128  raeburn  8890:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8891:     }
1.1172.2.66  raeburn  8892:     if ($symb) {
                   8893:         @symbs = ($symb);
                   8894:     } elsif (keys(%possibles)) {
                   8895:         @symbs = keys(%possibles);
                   8896:     }
                   8897:     my $noblock;
                   8898:     foreach my $symb (@symbs) {
                   8899:         last if ($noblock);
                   8900:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8901:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8902:             if ($block =~ /^firstaccess____(.+)$/) {
                   8903:                 my $item = $1;
1.1172.2.126  raeburn  8904:                 unless ($blocked) {
                   8905:                     if (($item eq $map) || ($item eq $symb)) {
                   8906:                         $noblock = 1;
                   8907:                         last;
                   8908:                     }
1.1172.2.66  raeburn  8909:                 }
1.1162    raeburn  8910:             }
1.1172.2.128  raeburn  8911:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8912:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8913:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8914:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8915:                             push(@blockers,$block);
                   8916:                         }
                   8917:                     }
                   8918:                 }
1.1172.2.128  raeburn  8919:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8920:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8921:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8922:                             push(@blockers,$block);
                   8923:                         }
1.1172.2.66  raeburn  8924:                     }
                   8925:                 }
1.1162    raeburn  8926:             }
                   8927:         }
                   8928:     }
1.1172.2.126  raeburn  8929:     unless ($noblock) {
                   8930:         return @blockers;
                   8931:     }
                   8932:     return;
1.1172.2.66  raeburn  8933: }
1.1162    raeburn  8934: }
                   8935: 
1.1172.2.146.  .1(raebu 8936:22): sub deeplink_check {
                   8937:22):     my ($priv,$symb,$uri) = @_;
                   8938:22):     return unless ($env{'request.course.id'});
                   8939:22):     return unless ($priv eq 'bre');
                   8940:22):     return if ($env{'request.state'} eq 'construct');
                   8941:22):     return if ($env{'request.role.adv'});
                   8942:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8943:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8944:22):     my (%possibles,@symbs);
                   8945:22):     if (!$symb) {
                   8946:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8947:22):     }
                   8948:22):     if ($symb) {
                   8949:22):         @symbs = ($symb);
                   8950:22):     } elsif (keys(%possibles)) {
                   8951:22):         @symbs = keys(%possibles);
                   8952:22):     }
                   8953:22): 
                   8954:22):     my ($deeplink_symb,$allow);
                   8955:22):     if ($env{'request.deeplink.login'}) {
                   8956:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8957:22):     }
                   8958:22):     foreach my $symb (@symbs) {
                   8959:22):         last if ($allow);
                   8960:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8961:22):         if ($deeplink eq '') {
                   8962:22):             $allow = 1;
                   8963:22):         } else {
                   8964:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8965:22):             if ($state ne 'only') {
                   8966:22):                 $allow = 1;
                   8967:22):             } else {
                   8968:22):                 my $check_deeplink_entry;
                   8969:22):                 if ($protect ne 'none') {
                   8970:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8971:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8972:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8973:22):                             $check_deeplink_entry = 1
                   8974:22):                         }
                   8975:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   8976:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   8977:22):                             $check_deeplink_entry = 1;
                   8978:22):                         }
                   8979:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8980:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8981:22):                             $check_deeplink_entry = 1;
                   8982:22):                         }
                   8983:22):                     }
                   8984:22):                 }
                   8985:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   8986:22):                     if ($scope eq 'res') {
                   8987:22):                         if ($symb eq $deeplink_symb) {
                   8988:22):                             $allow = 1;
                   8989:22):                         }
                   8990:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   8991:22):                         my ($map_from_symb,$map_from_login);
                   8992:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   8993:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   8994:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   8995:22):                         } else {
                   8996:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   8997:22):                         }
                   8998:22):                         if (($map_from_symb) && ($map_from_login)) {
                   8999:22):                             if ($map_from_symb eq $map_from_login) {
                   9000:22):                                 $allow = 1;
                   9001:22):                             } elsif ($scope eq 'rec') {
                   9002:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9003:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9004:22):                                     $allow = 1;
                   9005:22):                                 }
                   9006:22):                             }
                   9007:22):                         }
                   9008:22):                     }
                   9009:22):                 }
                   9010:22):             }
                   9011:22):         }
                   9012:22):     }
                   9013:22):     return if ($allow);
                   9014:22):     return 1;
                   9015:22): }
                   9016:22): 
1.1172.2.66  raeburn  9017: # -------------------------------- Deversion and split uri into path an filename
                   9018: 
1.1133    foxr     9019: #
1.1172.2.66  raeburn  9020: #   Removes the version from a URI and
1.1133    foxr     9021: #   splits it in to its filename and path to the filename.
                   9022: #   Seems like File::Basename could have done this more clearly.
                   9023: #   Parameters:
                   9024: #      $uri   - input URI
                   9025: #   Returns:
                   9026: #     Two element list consisting of 
                   9027: #     $pathname  - the URI up to and excluding the trailing /
                   9028: #     $filename  - The part of the URI following the last /
                   9029: #  NOTE:
                   9030: #    Another realization of this is simply:
                   9031: #    use File::Basename;
                   9032: #    ...
                   9033: #    $uri = shift;
                   9034: #    $filename = basename($uri);
                   9035: #    $path     = dirname($uri);
                   9036: #    return ($filename, $path);
                   9037: #
                   9038: #     The implementation below is probably faster however.
                   9039: #
1.710     albertel 9040: sub split_uri_for_cond {
                   9041:     my $uri=&deversion(&declutter(shift));
                   9042:     my @uriparts=split(/\//,$uri);
                   9043:     my $filename=pop(@uriparts);
                   9044:     my $pathname=join('/',@uriparts);
                   9045:     return ($pathname,$filename);
                   9046: }
1.232     www      9047: # --------------------------------------------------- Is a resource on the map?
                   9048: 
                   9049: sub is_on_map {
1.710     albertel 9050:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9051:     #Trying to find the conditional for the file
1.620     albertel 9052:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9053: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9054:     if ($match) {
1.289     bowersj2 9055: 	return (1,$1);
                   9056:     } else {
1.434     www      9057: 	return (0,0);
1.289     bowersj2 9058:     }
1.12      www      9059: }
                   9060: 
1.427     www      9061: # --------------------------------------------------------- Get symb from alias
                   9062: 
                   9063: sub get_symb_from_alias {
                   9064:     my $symb=shift;
                   9065:     my ($map,$resid,$url)=&decode_symb($symb);
                   9066: # Already is a symb
                   9067:     if ($url) { return $symb; }
                   9068: # Must be an alias
                   9069:     my $aliassymb='';
                   9070:     my %bighash;
1.620     albertel 9071:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9072:                             &GDBM_READER(),0640)) {
                   9073:         my $rid=$bighash{'mapalias_'.$symb};
                   9074: 	if ($rid) {
                   9075: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9076: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9077: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9078: 	}
                   9079:         untie %bighash;
                   9080:     }
                   9081:     return $aliassymb;
                   9082: }
                   9083: 
1.12      www      9084: # ----------------------------------------------------------------- Define Role
                   9085: 
                   9086: sub definerole {
                   9087:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9088:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9089:     foreach my $role (split(':',$sysrole)) {
                   9090: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9091:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9092:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9093: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9094:                return "refused:s:$crole&$cqual"; 
                   9095:             }
                   9096:         }
1.191     harris41 9097:     }
1.800     albertel 9098:     foreach my $role (split(':',$domrole)) {
                   9099: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9100:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9101:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9102: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9103:                return "refused:d:$crole&$cqual"; 
                   9104:             }
                   9105:         }
1.191     harris41 9106:     }
1.800     albertel 9107:     foreach my $role (split(':',$courole)) {
                   9108: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9109:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9110:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9111: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9112:                return "refused:c:$crole&$cqual"; 
                   9113:             }
                   9114:         }
1.191     harris41 9115:     }
1.1172.2.84  raeburn  9116:     my $uhome;
                   9117:     if (($uname ne '') && ($udom ne '')) {
                   9118:         $uhome = &homeserver($uname,$udom);
                   9119:         return $uhome if ($uhome eq 'no_host');
                   9120:     } else {
                   9121:         $uname = $env{'user.name'};
                   9122:         $udom = $env{'user.domain'};
                   9123:         $uhome = $env{'user.home'};
                   9124:     }
1.620     albertel 9125:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9126:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9127:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9128:     return reply($command,$uhome);
1.12      www      9129:   } else {
                   9130:     return 'refused';
                   9131:   }
1.105     harris41 9132: }
                   9133: 
                   9134: # ---------------- Make a metadata query against the network of library servers
                   9135: 
                   9136: sub metadata_query {
1.1172.2.33  raeburn  9137:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9138:     my %rhash;
1.845     albertel 9139:     my %libserv = &all_library();
1.244     matthew  9140:     my @server_list = (defined($server_array) ? @$server_array
                   9141:                                               : keys(%libserv) );
                   9142:     for my $server (@server_list) {
1.1172.2.33  raeburn  9143:         my $domains = '';
                   9144:         if (ref($domains_hash) eq 'HASH') {
                   9145:             $domains = $domains_hash->{$server};    
                   9146:         }
1.118     harris41 9147: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9148: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9149: 	    $rhash{$server}=$reply;
                   9150: 	}
                   9151: 	else {
                   9152: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9153: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9154: 			     $server);
                   9155: 	    $rhash{$server}=$reply;
                   9156: 	}
1.112     harris41 9157:     }
1.118     harris41 9158:     return \%rhash;
1.240     www      9159: }
                   9160: 
                   9161: # ----------------------------------------- Send log queries and wait for reply
                   9162: 
                   9163: sub log_query {
                   9164:     my ($uname,$udom,$query,%filters)=@_;
                   9165:     my $uhome=&homeserver($uname,$udom);
                   9166:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9167:     my $uhost=&hostname($uhome);
1.800     albertel 9168:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9169:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9170:                        $uhome);
1.479     albertel 9171:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9172:     return get_query_reply($queryid);
                   9173: }
                   9174: 
1.818     raeburn  9175: # -------------------------- Update MySQL table for portfolio file
                   9176: 
                   9177: sub update_portfolio_table {
1.821     raeburn  9178:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9179:     if ($group ne '') {
                   9180:         $file_name =~s /^\Q$group\E//;
                   9181:     }
1.818     raeburn  9182:     my $homeserver = &homeserver($uname,$udom);
                   9183:     my $queryid=
1.821     raeburn  9184:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9185:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9186:     my $reply = &get_query_reply($queryid);
                   9187:     return $reply;
                   9188: }
                   9189: 
1.899     raeburn  9190: # -------------------------- Update MySQL allusers table
                   9191: 
                   9192: sub update_allusers_table {
                   9193:     my ($uname,$udom,$names) = @_;
                   9194:     my $homeserver = &homeserver($uname,$udom);
                   9195:     my $queryid=
                   9196:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9197:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9198:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9199:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9200:                'generation='.&escape($names->{'generation'}).'%%'.
                   9201:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9202:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9203:     return;
1.899     raeburn  9204: }
                   9205: 
1.508     raeburn  9206: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9207: 
                   9208: sub fetch_enrollment_query {
1.511     raeburn  9209:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9210:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9211:     my $maxtries = 1;
1.508     raeburn  9212:     if ($context eq 'automated') {
                   9213:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9214:         $sleep = 2;
                   9215:         $loopmax = 100;
1.547     raeburn  9216:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9217:     } else {
                   9218:         $homeserver = &homeserver($cnum,$dom);
                   9219:     }
1.838     albertel 9220:     my $host=&hostname($homeserver);
1.506     raeburn  9221:     my $cmd = '';
1.1000    raeburn  9222:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9223:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9224:     }
                   9225:     $cmd =~ s/%%$//;
                   9226:     $cmd = &escape($cmd);
                   9227:     my $query = 'fetchenrollment';
1.620     albertel 9228:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9229:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9230:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9231:         return 'error: '.$queryid;
                   9232:     }
1.1172.2.93  raeburn  9233:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9234:     my $tries = 1;
                   9235:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9236:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9237:         $tries ++;
                   9238:     }
1.526     raeburn  9239:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9240:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9241:     } else {
1.901     albertel 9242:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9243:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9244:             foreach my $line (@responses) {
                   9245:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9246:                 $$replyref{$key} = $value;
                   9247:             }
                   9248:         } else {
1.1117    foxr     9249:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9250:             foreach my $line (@responses) {
                   9251:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9252:                 $$replyref{$key} = $value;
                   9253:                 if ($value > 0) {
1.800     albertel 9254:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9255:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9256:                         my $destname = $pathname.'/'.$filename;
                   9257:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9258:                         if ($xml_classlist =~ /^error/) {
                   9259:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9260:                         } else {
1.1172.2.96  raeburn  9261:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9262:                                 print FILE &unescape($xml_classlist);
                   9263:                                 close(FILE);
1.526     raeburn  9264:                             } else {
                   9265:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9266:                             }
                   9267:                         }
                   9268:                     }
                   9269:                 }
                   9270:             }
                   9271:         }
                   9272:         return 'ok';
                   9273:     }
                   9274:     return 'error';
                   9275: }
                   9276: 
1.242     www      9277: sub get_query_reply {
1.1172.2.79  raeburn  9278:     my ($queryid,$sleep,$loopmax) = @_;
                   9279:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9280:         $sleep = 0.2;
                   9281:     }
                   9282:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9283:         $loopmax = 100;
                   9284:     }
1.1117    foxr     9285:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9286:     my $reply='';
1.1172.2.79  raeburn  9287:     for (1..$loopmax) {
                   9288: 	sleep($sleep);
1.240     www      9289:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9290: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9291: 		$reply = join('',<$fh>);
                   9292: 		close($fh);
1.240     www      9293: 	   } else { return 'error: reply_file_error'; }
1.242     www      9294:            return &unescape($reply);
                   9295: 	}
1.240     www      9296:     }
1.242     www      9297:     return 'timeout:'.$queryid;
1.240     www      9298: }
                   9299: 
                   9300: sub courselog_query {
1.241     www      9301: #
                   9302: # possible filters:
                   9303: # url: url or symb
                   9304: # username
                   9305: # domain
                   9306: # action: view, submit, grade
                   9307: # start: timestamp
                   9308: # end: timestamp
                   9309: #
1.240     www      9310:     my (%filters)=@_;
1.620     albertel 9311:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9312:     if ($filters{'url'}) {
                   9313: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9314:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9315:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9316:     }
1.620     albertel 9317:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9318:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9319:     return &log_query($cname,$cdom,'courselog',%filters);
                   9320: }
                   9321: 
                   9322: sub userlog_query {
1.858     raeburn  9323: #
                   9324: # possible filters:
                   9325: # action: log check role
                   9326: # start: timestamp
                   9327: # end: timestamp
                   9328: #
1.240     www      9329:     my ($uname,$udom,%filters)=@_;
                   9330:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9331: }
                   9332: 
1.506     raeburn  9333: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9334: 
                   9335: sub auto_run {
1.508     raeburn  9336:     my ($cnum,$cdom) = @_;
1.876     raeburn  9337:     my $response = 0;
                   9338:     my $settings;
                   9339:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9340:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9341:         $settings = $domconfig{'autoenroll'};
                   9342:         if ($settings->{'run'} eq '1') {
                   9343:             $response = 1;
                   9344:         }
                   9345:     } else {
1.934     raeburn  9346:         my $homeserver;
                   9347:         if (&is_course($cdom,$cnum)) {
                   9348:             $homeserver = &homeserver($cnum,$cdom);
                   9349:         } else {
                   9350:             $homeserver = &domain($cdom,'primary');
                   9351:         }
                   9352:         if ($homeserver ne 'no_host') {
                   9353:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9354:         }
1.876     raeburn  9355:     }
1.506     raeburn  9356:     return $response;
                   9357: }
1.776     albertel 9358: 
1.506     raeburn  9359: sub auto_get_sections {
1.508     raeburn  9360:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9361:     my $homeserver;
                   9362:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9363:         $homeserver = &homeserver($cnum,$cdom);
                   9364:     }
                   9365:     if (!defined($homeserver)) { 
                   9366:         if ($cdom =~ /^$match_domain$/) {
                   9367:             $homeserver = &domain($cdom,'primary');
                   9368:         }
                   9369:     }
                   9370:     my @secs;
                   9371:     if (defined($homeserver)) {
                   9372:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9373:         unless ($response eq 'refused') {
                   9374:             @secs = split(/:/,$response);
                   9375:         }
1.506     raeburn  9376:     }
                   9377:     return @secs;
                   9378: }
1.776     albertel 9379: 
1.506     raeburn  9380: sub auto_new_course {
1.1099    raeburn  9381:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9382:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9383:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9384:     return $response;
                   9385: }
1.776     albertel 9386: 
1.506     raeburn  9387: sub auto_validate_courseID {
1.508     raeburn  9388:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9389:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9390:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9391:     return $response;
                   9392: }
1.776     albertel 9393: 
1.1007    raeburn  9394: sub auto_validate_instcode {
1.1020    raeburn  9395:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9396:     my ($homeserver,$response);
                   9397:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9398:         $homeserver = &homeserver($cnum,$cdom);
                   9399:     }
                   9400:     if (!defined($homeserver)) {
                   9401:         if ($cdom =~ /^$match_domain$/) {
                   9402:             $homeserver = &domain($cdom,'primary');
                   9403:         }
                   9404:     }
1.1065    raeburn  9405:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9406:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9407:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9408:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9409: }
                   9410: 
1.1172.2.141  raeburn  9411: sub auto_validate_inst_crosslist {
                   9412:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9413:     my ($homeserver,$response);
                   9414:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9415:         $homeserver = &homeserver($cnum,$cdom);
                   9416:     }
                   9417:     if (!defined($homeserver)) {
                   9418:         if ($cdom =~ /^$match_domain$/) {
                   9419:             $homeserver = &domain($cdom,'primary');
                   9420:         }
                   9421:     }
                   9422:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9423:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9424:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9425:                          &escape($coowner),$homeserver);
                   9426:     }
                   9427:     return $response;
                   9428: }
                   9429: 
1.506     raeburn  9430: sub auto_create_password {
1.873     raeburn  9431:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9432:     my ($homeserver,$response);
1.506     raeburn  9433:     my $create_passwd = 0;
                   9434:     my $authchk = '';
1.873     raeburn  9435:     if ($udom =~ /^$match_domain$/) {
                   9436:         $homeserver = &domain($udom,'primary');
                   9437:     }
                   9438:     if ($homeserver eq '') {
                   9439:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9440:             $homeserver = &homeserver($cnum,$cdom);
                   9441:         }
                   9442:     }
                   9443:     if ($homeserver eq '') {
                   9444:         $authchk = 'nodomain';
1.506     raeburn  9445:     } else {
1.873     raeburn  9446:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9447:         if ($response eq 'refused') {
                   9448:             $authchk = 'refused';
                   9449:         } else {
1.901     albertel 9450:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9451:         }
1.506     raeburn  9452:     }
                   9453:     return ($authparam,$create_passwd,$authchk);
                   9454: }
                   9455: 
1.706     raeburn  9456: sub auto_photo_permission {
                   9457:     my ($cnum,$cdom,$students) = @_;
                   9458:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9459:     my ($outcome,$perm_reqd,$conditions) = 
                   9460: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9461:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9462: 	return (undef,undef);
                   9463:     }
1.706     raeburn  9464:     return ($outcome,$perm_reqd,$conditions);
                   9465: }
                   9466: 
                   9467: sub auto_checkphotos {
                   9468:     my ($uname,$udom,$pid) = @_;
                   9469:     my $homeserver = &homeserver($uname,$udom);
                   9470:     my ($result,$resulttype);
                   9471:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9472: 				   &escape($uname).':'.&escape($pid),
                   9473: 				   $homeserver));
1.709     albertel 9474:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9475: 	return (undef,undef);
                   9476:     }
1.706     raeburn  9477:     if ($outcome) {
                   9478:         ($result,$resulttype) = split(/:/,$outcome);
                   9479:     } 
                   9480:     return ($result,$resulttype);
                   9481: }
                   9482: 
                   9483: sub auto_photochoice {
                   9484:     my ($cnum,$cdom) = @_;
                   9485:     my $homeserver = &homeserver($cnum,$cdom);
                   9486:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9487: 						       &escape($cdom),
                   9488: 						       $homeserver)));
1.709     albertel 9489:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9490: 	return (undef,undef);
                   9491:     }
1.706     raeburn  9492:     return ($update,$comment);
                   9493: }
                   9494: 
                   9495: sub auto_photoupdate {
                   9496:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9497:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9498:     my $host=&hostname($homeserver);
1.706     raeburn  9499:     my $cmd = '';
                   9500:     my $maxtries = 1;
1.800     albertel 9501:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9502:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9503:     }
                   9504:     $cmd =~ s/%%$//;
                   9505:     $cmd = &escape($cmd);
                   9506:     my $query = 'institutionalphotos';
                   9507:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9508:     unless ($queryid=~/^\Q$host\E\_/) {
                   9509:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9510:         return 'error: '.$queryid;
                   9511:     }
                   9512:     my $reply = &get_query_reply($queryid);
                   9513:     my $tries = 1;
                   9514:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9515:         $reply = &get_query_reply($queryid);
                   9516:         $tries ++;
                   9517:     }
                   9518:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9519:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9520:     } else {
                   9521:         my @responses = split(/:/,$reply);
                   9522:         my $outcome = shift(@responses); 
                   9523:         foreach my $item (@responses) {
                   9524:             my ($key,$value) = split(/=/,$item);
                   9525:             $$photo{$key} = $value;
                   9526:         }
                   9527:         return $outcome;
                   9528:     }
                   9529:     return 'error';
                   9530: }
                   9531: 
1.521     raeburn  9532: sub auto_instcode_format {
1.793     albertel 9533:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9534: 	$cat_order) = @_;
1.521     raeburn  9535:     my $courses = '';
1.772     raeburn  9536:     my @homeservers;
1.521     raeburn  9537:     if ($caller eq 'global') {
1.841     albertel 9538: 	my %servers = &get_servers($codedom,'library');
                   9539: 	foreach my $tryserver (keys(%servers)) {
                   9540: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9541: 		push(@homeservers,$tryserver);
                   9542: 	    }
1.584     raeburn  9543:         }
1.1022    raeburn  9544:     } elsif ($caller eq 'requests') {
                   9545:         if ($codedom =~ /^$match_domain$/) {
                   9546:             my $chome = &domain($codedom,'primary');
                   9547:             unless ($chome eq 'no_host') {
                   9548:                 push(@homeservers,$chome);
                   9549:             }
                   9550:         }
1.521     raeburn  9551:     } else {
1.772     raeburn  9552:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9553:     }
1.793     albertel 9554:     foreach my $code (keys(%{$instcodes})) {
                   9555:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9556:     }
                   9557:     chop($courses);
1.772     raeburn  9558:     my $ok_response = 0;
                   9559:     my $response;
                   9560:     while (@homeservers > 0 && $ok_response == 0) {
                   9561:         my $server = shift(@homeservers); 
                   9562:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9563:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9564:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9565: 		split(/:/,$response);
1.772     raeburn  9566:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9567:             push(@{$codetitles},&str2array($codetitles_str));
                   9568:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9569:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9570:             $ok_response = 1;
                   9571:         }
                   9572:     }
                   9573:     if ($ok_response) {
1.521     raeburn  9574:         return 'ok';
1.772     raeburn  9575:     } else {
                   9576:         return $response;
1.521     raeburn  9577:     }
                   9578: }
                   9579: 
1.792     raeburn  9580: sub auto_instcode_defaults {
                   9581:     my ($domain,$returnhash,$code_order) = @_;
                   9582:     my @homeservers;
1.841     albertel 9583: 
                   9584:     my %servers = &get_servers($domain,'library');
                   9585:     foreach my $tryserver (keys(%servers)) {
                   9586: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9587: 	    push(@homeservers,$tryserver);
                   9588: 	}
1.792     raeburn  9589:     }
1.841     albertel 9590: 
1.792     raeburn  9591:     my $response;
1.841     albertel 9592:     foreach my $server (@homeservers) {
1.792     raeburn  9593:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9594:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9595: 	
                   9596: 	foreach my $pair (split(/\&/,$response)) {
                   9597: 	    my ($name,$value)=split(/\=/,$pair);
                   9598: 	    if ($name eq 'code_order') {
                   9599: 		@{$code_order} = split(/\&/,&unescape($value));
                   9600: 	    } else {
                   9601: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9602: 	    }
                   9603: 	}
                   9604: 	return 'ok';
1.792     raeburn  9605:     }
1.841     albertel 9606: 
                   9607:     return $response;
1.1003    raeburn  9608: }
                   9609: 
                   9610: sub auto_possible_instcodes {
1.1007    raeburn  9611:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9612:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9613:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9614:         return;
                   9615:     }
1.1003    raeburn  9616:     my (@homeservers,$uhome);
                   9617:     if (defined(&domain($domain,'primary'))) {
                   9618:         $uhome=&domain($domain,'primary');
                   9619:         push(@homeservers,&domain($domain,'primary'));
                   9620:     } else {
                   9621:         my %servers = &get_servers($domain,'library');
                   9622:         foreach my $tryserver (keys(%servers)) {
                   9623:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9624:                 push(@homeservers,$tryserver);
                   9625:             }
                   9626:         }
                   9627:     }
                   9628:     my $response;
                   9629:     foreach my $server (@homeservers) {
                   9630:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9631:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9632:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9633:             split(':',$response);
                   9634:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9635:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9636:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9637:             my ($name,$value)=split('=',$item);
                   9638:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9639:         }
                   9640:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9641:             my ($name,$value)=split('=',$item);
                   9642:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9643:         }
                   9644:         return 'ok';
                   9645:     }
                   9646:     return $response;
                   9647: }
1.792     raeburn  9648: 
1.1010    raeburn  9649: sub auto_courserequest_checks {
                   9650:     my ($dom) = @_;
1.1020    raeburn  9651:     my ($homeserver,%validations);
                   9652:     if ($dom =~ /^$match_domain$/) {
                   9653:         $homeserver = &domain($dom,'primary');
                   9654:     }
                   9655:     unless ($homeserver eq 'no_host') {
                   9656:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9657:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9658:             my @items = split(/&/,$response);
                   9659:             foreach my $item (@items) {
                   9660:                 my ($key,$value) = split('=',$item);
                   9661:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9662:             }
                   9663:         }
                   9664:     }
1.1010    raeburn  9665:     return %validations; 
                   9666: }
                   9667: 
1.1020    raeburn  9668: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9669:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9670:     my ($homeserver,$response);
                   9671:     if ($dom =~ /^$match_domain$/) {
                   9672:         $homeserver = &domain($dom,'primary');
                   9673:     }
1.1172.2.43  raeburn  9674:     unless ($homeserver eq 'no_host') {
                   9675:         my $customdata;
                   9676:         if (ref($custominfo) eq 'HASH') {
                   9677:             $customdata = &freeze_escape($custominfo);
                   9678:         }
1.1020    raeburn  9679:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9680:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9681:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9682:                                     $customdata,$homeserver));
1.1020    raeburn  9683:     }
                   9684:     return $response;
                   9685: }
                   9686: 
1.777     albertel 9687: sub auto_validate_class_sec {
1.918     raeburn  9688:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9689:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9690:     my $ownerlist;
                   9691:     if (ref($owners) eq 'ARRAY') {
                   9692:         $ownerlist = join(',',@{$owners});
                   9693:     } else {
                   9694:         $ownerlist = $owners;
                   9695:     }
1.773     raeburn  9696:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9697:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9698:     return $response;
                   9699: }
                   9700: 
1.1172.2.141  raeburn  9701: sub auto_instsec_reformat {
                   9702:     my ($cdom,$action,$instsecref) = @_;
                   9703:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9704:     my @homeservers;
                   9705:     if (defined(&domain($cdom,'primary'))) {
                   9706:         push(@homeservers,&domain($cdom,'primary'));
                   9707:     } else {
                   9708:         my %servers = &get_servers($cdom,'library');
                   9709:         foreach my $tryserver (keys(%servers)) {
                   9710:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9711:                 push(@homeservers,$tryserver);
                   9712:             }
                   9713:         }
                   9714:     }
                   9715:     my $response;
                   9716:     my %reformatted = %{$instsecref};
                   9717:     foreach my $server (@homeservers) {
                   9718:         if (ref($instsecref) eq 'HASH') {
                   9719:             my $info = &freeze_escape($instsecref);
                   9720:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9721:                                 $action.':'.$info,$server);
                   9722:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9723:             my @items = split(/&/,$response);
                   9724:             foreach my $item (@items) {
                   9725:                 my ($key,$value) = split(/=/,$item);
                   9726:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9727:             }
                   9728:         }
                   9729:     }
                   9730:     return %reformatted;
                   9731: }
                   9732: 
1.1172.2.94  raeburn  9733: sub auto_validate_instclasses {
                   9734:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9735:     my ($homeserver,%validations);
                   9736:     $homeserver = &homeserver($cnum,$cdom);
                   9737:     unless ($homeserver eq 'no_host') {
                   9738:         my $ownerlist;
                   9739:         if (ref($owners) eq 'ARRAY') {
                   9740:             $ownerlist = join(',',@{$owners});
                   9741:         } else {
                   9742:             $ownerlist = $owners;
                   9743:         }
                   9744:         if (ref($classesref) eq 'HASH') {
                   9745:             my $classes = &freeze_escape($classesref);
                   9746:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9747:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9748:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9749:                 my @items = split(/&/,$response);
                   9750:                 foreach my $item (@items) {
                   9751:                     my ($key,$value) = split('=',$item);
                   9752:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9753:                 }
                   9754:             }
                   9755:         }
                   9756:     }
                   9757:     return %validations;
                   9758: }
                   9759: 
1.1172.2.38  raeburn  9760: sub auto_crsreq_update {
                   9761:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9762:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9763:     my ($homeserver,%crsreqresponse);
                   9764:     if ($cdom =~ /^$match_domain$/) {
                   9765:         $homeserver = &domain($cdom,'primary');
                   9766:     }
                   9767:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9768:         my $info;
                   9769:         if (ref($inbound) eq 'HASH') {
                   9770:             $info = &freeze_escape($inbound);
                   9771:         }
                   9772:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9773:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9774:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9775:                             &escape($title).':'.&escape($code).':'.
                   9776:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9777:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9778:             my @items = split(/&/,$response);
                   9779:             foreach my $item (@items) {
                   9780:                 my ($key,$value) = split('=',$item);
                   9781:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9782:             }
                   9783:         }
                   9784:     }
                   9785:     return \%crsreqresponse;
                   9786: }
                   9787: 
1.1172.2.78  raeburn  9788: sub auto_export_grades {
                   9789:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9790:     my ($homeserver,%exportresponse);
                   9791:     if ($cdom =~ /^$match_domain$/) {
                   9792:         $homeserver = &domain($cdom,'primary');
                   9793:     }
                   9794:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9795:         my $info;
                   9796:         if (ref($inforef) eq 'HASH') {
                   9797:             $info = &freeze_escape($inforef);
                   9798:         }
                   9799:         if (ref($gradesref) eq 'HASH') {
                   9800:             my $grades = &freeze_escape($gradesref);
                   9801:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9802:                                 $info.':'.$grades,$homeserver);
                   9803:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9804:                 my @items = split(/&/,$response);
                   9805:                 foreach my $item (@items) {
                   9806:                     my ($key,$value) = split('=',$item);
                   9807:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9808:                 }
                   9809:             }
                   9810:         }
                   9811:     }
                   9812:     return \%exportresponse;
                   9813: }
                   9814: 
1.1172.2.68  raeburn  9815: sub check_instcode_cloning {
                   9816:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9817:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9818:         return;
                   9819:     }
                   9820:     my $canclone;
                   9821:     if (@{$code_order} > 0) {
                   9822:         my $instcoderegexp ='^';
                   9823:         my @clonecodes = split(/\&/,$cloner);
                   9824:         foreach my $item (@{$code_order}) {
                   9825:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9826:                 foreach my $pair (@clonecodes) {
                   9827:                     my ($key,$val) = split(/\=/,$pair,2);
                   9828:                     $val = &unescape($val);
                   9829:                     if ($key eq $item) {
                   9830:                         $instcoderegexp .= '('.$val.')';
                   9831:                         last;
                   9832:                     }
                   9833:                 }
                   9834:             } else {
                   9835:                 $instcoderegexp .= $codedefaults->{$item};
                   9836:             }
                   9837:         }
                   9838:         $instcoderegexp .= '$';
                   9839:         my (@from,@to);
                   9840:         eval {
                   9841:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9842:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9843:         };
                   9844:         if ((@from > 0) && (@to > 0)) {
                   9845:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9846:             if (!@diffs) {
                   9847:                 $canclone = 1;
                   9848:             }
                   9849:         }
                   9850:     }
                   9851:     return $canclone;
                   9852: }
                   9853: 
                   9854: sub default_instcode_cloning {
                   9855:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9856:     my (%codedefaults,@code_order,$canclone);
                   9857:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9858:         %codedefaults = %{$codedefaultsref};
                   9859:         @code_order = @{$codeorderref};
                   9860:     } elsif ($clonedom) {
                   9861:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9862:     }
                   9863:     if (($domdefclone) && (@code_order)) {
                   9864:         my @clonecodes = split(/\+/,$domdefclone);
                   9865:         my $instcoderegexp ='^';
                   9866:         foreach my $item (@code_order) {
                   9867:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9868:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9869:             } else {
                   9870:                 $instcoderegexp .= $codedefaults{$item};
                   9871:             }
                   9872:         }
                   9873:         $instcoderegexp .= '$';
                   9874:         my (@from,@to);
                   9875:         eval {
                   9876:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9877:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9878:         };
                   9879:         if ((@from > 0) && (@to > 0)) {
                   9880:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9881:             if (!@diffs) {
                   9882:                 $canclone = 1;
                   9883:             }
                   9884:         }
                   9885:     }
                   9886:     return $canclone;
                   9887: }
                   9888: 
1.679     raeburn  9889: # ------------------------------------------------------- Course Group routines
                   9890: 
                   9891: sub get_coursegroups {
1.809     raeburn  9892:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9893:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9894: }
                   9895: 
1.679     raeburn  9896: sub modify_coursegroup {
                   9897:     my ($cdom,$cnum,$groupsettings) = @_;
                   9898:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9899: }
                   9900: 
1.809     raeburn  9901: sub toggle_coursegroup_status {
                   9902:     my ($cdom,$cnum,$group,$action) = @_;
                   9903:     my ($from_namespace,$to_namespace);
                   9904:     if ($action eq 'delete') {
                   9905:         $from_namespace = 'coursegroups';
                   9906:         $to_namespace = 'deleted_groups';
                   9907:     } else {
                   9908:         $from_namespace = 'deleted_groups';
                   9909:         $to_namespace = 'coursegroups';
                   9910:     }
                   9911:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9912:     if (my $tmp = &error(%curr_group)) {
                   9913:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9914:         return ('read error',$tmp);
                   9915:     } else {
                   9916:         my %savedsettings = %curr_group; 
1.809     raeburn  9917:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9918:         my $deloutcome;
                   9919:         if ($result eq 'ok') {
1.809     raeburn  9920:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9921:         } else {
                   9922:             return ('write error',$result);
                   9923:         }
                   9924:         if ($deloutcome eq 'ok') {
                   9925:             return 'ok';
                   9926:         } else {
                   9927:             return ('delete error',$deloutcome);
                   9928:         }
                   9929:     }
                   9930: }
                   9931: 
1.679     raeburn  9932: sub modify_group_roles {
1.957     raeburn  9933:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9934:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9935:     my $role = 'gr/'.&escape($userprivs);
                   9936:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9937:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9938:     if ($result eq 'ok') {
                   9939:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9940:     }
1.679     raeburn  9941:     return $result;
                   9942: }
                   9943: 
                   9944: sub modify_coursegroup_membership {
                   9945:     my ($cdom,$cnum,$membership) = @_;
                   9946:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9947:     return $result;
                   9948: }
                   9949: 
1.682     raeburn  9950: sub get_active_groups {
                   9951:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9952:     my $now = time;
                   9953:     my %groups = ();
                   9954:     foreach my $key (keys(%env)) {
1.811     albertel 9955:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9956:             my ($start,$end) = split(/\./,$env{$key});
                   9957:             if (($end!=0) && ($end<$now)) { next; }
                   9958:             if (($start!=0) && ($start>$now)) { next; }
                   9959:             if ($1 eq $cdom && $2 eq $cnum) {
                   9960:                 $groups{$3} = $env{$key} ;
                   9961:             }
                   9962:         }
                   9963:     }
                   9964:     return %groups;
                   9965: }
                   9966: 
1.683     raeburn  9967: sub get_group_membership {
                   9968:     my ($cdom,$cnum,$group) = @_;
                   9969:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9970: }
                   9971: 
                   9972: sub get_users_groups {
                   9973:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9974:     my @usersgroups;
1.683     raeburn  9975:     my $cachetime=1800;
                   9976: 
                   9977:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9978:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9979:     if (defined($cached)) {
1.734     albertel 9980:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9981:     } else {  
                   9982:         $grouplist = '';
1.816     raeburn  9983:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9984:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9985:         my $access_end = $env{'course.'.$courseid.
                   9986:                               '.default_enrollment_end_date'};
                   9987:         my $now = time;
                   9988:         foreach my $key (keys(%roleshash)) {
                   9989:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9990:                 my $group = $1;
                   9991:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9992:                     my $start = $2;
                   9993:                     my $end = $1;
                   9994:                     if ($start == -1) { next; } # deleted from group
                   9995:                     if (($start!=0) && ($start>$now)) { next; }
                   9996:                     if (($end!=0) && ($end<$now)) {
                   9997:                         if ($access_end && $access_end < $now) {
                   9998:                             if ($access_end - $end < 86400) {
                   9999:                                 push(@usersgroups,$group);
1.733     raeburn  10000:                             }
                   10001:                         }
1.817     raeburn  10002:                         next;
1.733     raeburn  10003:                     }
1.817     raeburn  10004:                     push(@usersgroups,$group);
1.683     raeburn  10005:                 }
                   10006:             }
                   10007:         }
1.817     raeburn  10008:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10009:         $grouplist = join(':',@usersgroups);
                   10010:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10011:     }
1.733     raeburn  10012:     return @usersgroups;
1.683     raeburn  10013: }
                   10014: 
                   10015: sub devalidate_getgroups_cache {
                   10016:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10017:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10018: 
1.683     raeburn  10019:     my $hashid="$udom:$uname:$courseid";
                   10020:     &devalidate_cache_new('getgroups',$hashid);
                   10021: }
                   10022: 
1.12      www      10023: # ------------------------------------------------------------------ Plain Text
                   10024: 
                   10025: sub plaintext {
1.988     raeburn  10026:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10027:     if ($short =~ m{^cr/}) {
1.758     albertel 10028: 	return (split('/',$short))[-1];
                   10029:     }
1.742     raeburn  10030:     if (!defined($cid)) {
                   10031:         $cid = $env{'request.course.id'};
                   10032:     }
                   10033:     my %rolenames = (
1.1008    raeburn  10034:                       Course    => 'std',
                   10035:                       Community => 'alt1',
1.742     raeburn  10036:                     );
1.1037    raeburn  10037:     if ($cid ne '') {
                   10038:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10039:             unless ($forcedefault) {
                   10040:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10041:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10042:                 return &Apache::lonlocal::mt($roletext);
                   10043:             }
                   10044:         }
                   10045:     }
                   10046:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10047:         (defined($rolenames{$type})) && 
                   10048:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10049:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10050:     } elsif ($cid ne '') {
                   10051:         my $crstype = $env{'course.'.$cid.'.type'};
                   10052:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10053:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10054:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10055:         }
1.742     raeburn  10056:     }
1.1037    raeburn  10057:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10058: }
                   10059: 
                   10060: # ----------------------------------------------------------------- Assign Role
                   10061: 
                   10062: sub assignrole {
1.957     raeburn  10063:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10064:         $context)=@_;
1.21      www      10065:     my $mrole;
                   10066:     if ($role =~ /^cr\//) {
1.393     www      10067:         my $cwosec=$url;
1.811     albertel 10068:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10069: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10070:            my $refused = 1;
                   10071:            if ($context eq 'requestcourses') {
                   10072:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10073:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10074:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10075:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10076:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10077:                            if ($crsenv{'internal.courseowner'} eq
                   10078:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10079:                                $refused = '';
                   10080:                            }
                   10081:                        }
                   10082:                    }
                   10083:                }
                   10084:            }
                   10085:            if ($refused) {
                   10086:                &logthis('Refused custom assignrole: '.
                   10087:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10088:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10089:                return 'refused';
                   10090:            }
1.104     www      10091:         }
1.21      www      10092:         $mrole='cr';
1.678     raeburn  10093:     } elsif ($role =~ /^gr\//) {
                   10094:         my $cwogrp=$url;
1.811     albertel 10095:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10096:         unless (&allowed('mdg',$cwogrp)) {
                   10097:             &logthis('Refused group assignrole: '.
                   10098:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10099:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10100:             return 'refused';
                   10101:         }
                   10102:         $mrole='gr';
1.21      www      10103:     } else {
1.82      www      10104:         my $cwosec=$url;
1.811     albertel 10105:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10106:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10107:             my $refused;
                   10108:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10109:                 if (!(&allowed('c'.$role,$url))) {
                   10110:                     $refused = 1;
                   10111:                 }
                   10112:             } else {
                   10113:                 $refused = 1;
                   10114:             }
1.947     raeburn  10115:             if ($refused) {
1.1045    raeburn  10116:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10117:                 if (!$selfenroll && $context eq 'course') {
                   10118:                     my %crsenv;
                   10119:                     if ($role eq 'cc' || $role eq 'co') {
                   10120:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10121:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10122:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10123:                                 if ($crsenv{'internal.courseowner'} eq 
                   10124:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10125:                                     $refused = '';
                   10126:                                 }
                   10127:                             }
                   10128:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10129:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10130:                                 if ($crsenv{'internal.courseowner'} eq 
                   10131:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10132:                                     $refused = '';
                   10133:                                 }
                   10134:                             }
                   10135:                         }
                   10136:                     }
                   10137:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10138:                     $refused = '';
1.1017    raeburn  10139:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10140:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10141:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10142:                         my $wrongcc;
                   10143:                         if ($cnum =~ /^$match_community$/) {
                   10144:                             $wrongcc = 1 if ($role eq 'cc');
                   10145:                         } else {
                   10146:                             $wrongcc = 1 if ($role eq 'co');
                   10147:                         }
                   10148:                         unless ($wrongcc) {
                   10149:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10150:                             if ($crsenv{'internal.courseowner'} eq 
                   10151:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10152:                                 $refused = '';
                   10153:                             }
1.1017    raeburn  10154:                         }
                   10155:                     }
1.1172.2.9  raeburn  10156:                 } elsif ($context eq 'requestauthor') {
                   10157:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10158:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10159:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10160:                             $refused = '';
                   10161:                         } else {
                   10162:                             my %domdefaults = &get_domain_defaults($udom);
                   10163:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10164:                                 my $checkbystatus;
                   10165:                                 if ($env{'user.adv'}) {
                   10166:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10167:                                     if ($disposition eq 'automatic') {
                   10168:                                         $refused = '';
                   10169:                                     } elsif ($disposition eq '') {
                   10170:                                         $checkbystatus = 1;
                   10171:                                     }
                   10172:                                 } else {
                   10173:                                     $checkbystatus = 1;
                   10174:                                 }
                   10175:                                 if ($checkbystatus) {
                   10176:                                     if ($env{'environment.inststatus'}) {
                   10177:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10178:                                         foreach my $type (@inststatuses) {
                   10179:                                             if (($type ne '') &&
                   10180:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10181:                                                 $refused = '';
                   10182:                                             }
                   10183:                                         }
                   10184:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10185:                                         $refused = '';
                   10186:                                     }
                   10187:                                 }
                   10188:                             }
                   10189:                         }
                   10190:                     }
1.1017    raeburn  10191:                 }
                   10192:                 if ($refused) {
1.947     raeburn  10193:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10194:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10195: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10196:                     return 'refused';
                   10197:                 }
1.932     raeburn  10198:             }
1.1131    raeburn  10199:         } elsif ($role eq 'au') {
                   10200:             if ($url ne '/'.$udom.'/') {
                   10201:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10202:                          ' to assign author role for '.$uname.':'.$udom.
                   10203:                          ' in domain: '.$url.' refused (wrong domain).');
                   10204:                 return 'refused';
                   10205:             }
1.104     www      10206:         }
1.21      www      10207:         $mrole=$role;
                   10208:     }
1.620     albertel 10209:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10210:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10211:     if ($end) { $command.='_'.$end; }
1.21      www      10212:     if ($start) {
                   10213: 	if ($end) { 
1.81      www      10214:            $command.='_'.$start; 
1.21      www      10215:         } else {
1.81      www      10216:            $command.='_0_'.$start;
1.21      www      10217:         }
                   10218:     }
1.739     raeburn  10219:     my $origstart = $start;
                   10220:     my $origend = $end;
1.957     raeburn  10221:     my $delflag;
1.357     www      10222: # actually delete
                   10223:     if ($deleteflag) {
1.373     www      10224: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10225: # modify command to delete the role
1.620     albertel 10226:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10227:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10228: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10229: # set start and finish to negative values for userrolelog
                   10230:            $start=-1;
                   10231:            $end=-1;
1.957     raeburn  10232:            $delflag = 1;
1.357     www      10233:         }
                   10234:     }
                   10235: # send command
1.349     www      10236:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10237: # log new user role if status is ok
1.349     www      10238:     if ($answer eq 'ok') {
1.663     raeburn  10239: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10240:         if (($role eq 'cc') || ($role eq 'in') ||
                   10241:             ($role eq 'ep') || ($role eq 'ad') ||
                   10242:             ($role eq 'ta') || ($role eq 'st') ||
                   10243:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10244:             ($role eq 'co')) {
1.1172.2.13  raeburn  10245: # for course roles, perform group memberships changes triggered by role change.
                   10246:             unless ($role =~ /^gr/) {
                   10247:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10248:                                                  $origstart,$selfenroll,$context);
                   10249:             }
1.1172.2.9  raeburn  10250:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10251:                            $selfenroll,$context);
                   10252:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10253:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10254:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10255:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10256:                            $context);
                   10257:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10258:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10259:                              $context);
                   10260:         }
1.1053    raeburn  10261:         if ($role eq 'cc') {
                   10262:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10263:         }
1.349     www      10264:     }
                   10265:     return $answer;
1.169     harris41 10266: }
                   10267: 
1.1053    raeburn  10268: sub autoupdate_coowners {
                   10269:     my ($url,$end,$start,$uname,$udom) = @_;
                   10270:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10271:     if (($cdom ne '') && ($cnum ne '')) {
                   10272:         my $now = time;
                   10273:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10274:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10275:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10276:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10277:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10278:             if ($instcode ne '') {
1.1056    raeburn  10279:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10280:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10281:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10282:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10283:                         unless ($result eq 'valid') {
                   10284:                             if ($xlists ne '') {
                   10285:                                 foreach my $xlist (split(',',$xlists)) {
                   10286:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10287:                                     $result =
                   10288:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10289:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10290:                                     last if ($result eq 'valid');
                   10291:                                 }
                   10292:                             }
                   10293:                         }
1.1056    raeburn  10294:                         if ($result eq 'valid') {
                   10295:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10296:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10297:                                     push(@newcoowners,$coowner);
                   10298:                                 }
                   10299:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10300:                                     push(@newcoowners,$uname.':'.$udom);
                   10301:                                 }
                   10302:                                 @newcoowners = sort(@newcoowners);
                   10303:                             } else {
                   10304:                                 push(@newcoowners,$uname.':'.$udom);
                   10305:                             }
1.1172.2.141  raeburn  10306:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10307:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10308:                                 unless ($coowner eq $uname.':'.$udom) {
                   10309:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10310:                                 }
                   10311:                             }
1.1172.2.141  raeburn  10312:                             unless (@newcoowners > 0) {
                   10313:                                 $delcoowners = 1;
                   10314:                                 $coowners = '';
                   10315:                             }
1.1053    raeburn  10316:                         }
                   10317:                         if (@newcoowners || $delcoowners) {
                   10318:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10319:                                             $delcoowners,@newcoowners);
                   10320:                         }
                   10321:                     }
                   10322:                 }
                   10323:             }
                   10324:         }
                   10325:     }
                   10326: }
                   10327: 
                   10328: sub store_coowners {
                   10329:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10330:     my $cid = $cdom.'_'.$cnum;
                   10331:     my ($coowners,$delresult,$putresult);
                   10332:     if (@newcoowners) {
                   10333:         $coowners = join(',',@newcoowners);
                   10334:         my %coownershash = (
                   10335:                             'internal.co-owners' => $coowners,
                   10336:                            );
                   10337:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10338:         if ($putresult eq 'ok') {
                   10339:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10340:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10341:             }
                   10342:         }
                   10343:     }
                   10344:     if ($delcoowners) {
                   10345:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10346:         if ($delresult eq 'ok') {
                   10347:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10348:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10349:             }
                   10350:         }
                   10351:     }
                   10352:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10353:         my %crsinfo =
                   10354:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10355:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10356:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10357:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10358:         }
                   10359:     }
                   10360: }
                   10361: 
1.169     harris41 10362: # -------------------------------------------------- Modify user authentication
1.197     www      10363: # Overrides without validation
                   10364: 
1.169     harris41 10365: sub modifyuserauth {
                   10366:     my ($udom,$uname,$umode,$upass)=@_;
                   10367:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10368:     my $allowed;
                   10369:     if (&allowed('mau',$udom)) {
                   10370:         $allowed = 1;
                   10371:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10372:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10373:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10374:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10375:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10376:         if (($cdom ne '') && ($cnum ne '')) {
                   10377:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10378:             if ($is_owner) {
                   10379:                 $allowed = 1;
                   10380:             }
                   10381:         }
                   10382:     }
                   10383:     unless ($allowed) { return 'refused'; }
1.197     www      10384:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10385:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10386:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10387:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10388: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10389:     my $ip = &get_requestor_ip();
1.620     albertel 10390:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10391:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10392:          '(Remote '.$ip.'): '.$reply);
1.197     www      10393:     &log($udom,,$uname,$uhome,
1.620     albertel 10394:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10395:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10396:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10397:     unless ($reply eq 'ok') {
1.197     www      10398:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10399: 	return 'error: '.$reply;
                   10400:     }   
1.170     harris41 10401:     return 'ok';
1.80      www      10402: }
                   10403: 
1.81      www      10404: # --------------------------------------------------------------- Modify a user
1.80      www      10405: 
1.81      www      10406: sub modifyuser {
1.206     matthew  10407:     my ($udom,    $uname, $uid,
                   10408:         $umode,   $upass, $first,
                   10409:         $middle,  $last,  $gene,
1.1058    raeburn  10410:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10411:     $udom= &LONCAPA::clean_domain($udom);
                   10412:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10413:     my $showcandelete = 'none';
                   10414:     if (ref($candelete) eq 'ARRAY') {
                   10415:         if (@{$candelete} > 0) {
                   10416:             $showcandelete = join(', ',@{$candelete});
                   10417:         }
                   10418:     }
1.81      www      10419:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10420:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10421: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10422:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10423:                                      ' desiredhome not specified'). 
1.620     albertel 10424:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10425:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10426:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10427:     my $newuser;
                   10428:     if ($uhome eq 'no_host') {
                   10429:         $newuser = 1;
                   10430:     }
1.80      www      10431: # ----------------------------------------------------------------- Create User
1.406     albertel 10432:     if (($uhome eq 'no_host') && 
                   10433: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10434:         my $unhome='';
1.844     albertel 10435:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10436:             $unhome = $desiredhome;
1.620     albertel 10437: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10438: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10439:         } else { # load balancing routine for determining $unhome
1.81      www      10440:             my $loadm=10000000;
1.841     albertel 10441: 	    my %servers = &get_servers($udom,'library');
                   10442: 	    foreach my $tryserver (keys(%servers)) {
                   10443: 		my $answer=reply('load',$tryserver);
                   10444: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10445: 		    $loadm=$answer;
                   10446: 		    $unhome=$tryserver;
                   10447: 		}
1.80      www      10448: 	    }
                   10449:         }
                   10450:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10451: 	    return 'error: unable to find a home server for '.$uname.
                   10452:                    ' in domain '.$udom;
1.80      www      10453:         }
                   10454:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10455:                          &escape($upass),$unhome);
                   10456: 	unless ($reply eq 'ok') {
                   10457:             return 'error: '.$reply;
                   10458:         }   
1.230     stredwic 10459:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10460:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10461: 	    return 'error: unable verify users home machine.';
1.80      www      10462:         }
1.209     matthew  10463:     }   # End of creation of new user
1.80      www      10464: # ---------------------------------------------------------------------- Add ID
                   10465:     if ($uid) {
                   10466:        $uid=~tr/A-Z/a-z/;
                   10467:        my %uidhash=&idrget($udom,$uname);
1.196     www      10468:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10469:          && (!$forceid)) {
1.80      www      10470: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10471: 	      return 'error: user id "'.$uid.'" does not match '.
                   10472:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10473:           }
                   10474:        } else {
                   10475: 	  &idput($udom,($uname => $uid));
                   10476:        }
                   10477:     }
                   10478: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10479:     my @tmp=&get('environment',
1.899     raeburn  10480: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10481:                     'permanentemail','inststatus'],
1.134     albertel 10482: 		   $udom,$uname);
1.1075    raeburn  10483:     my (%names,%oldnames);
1.313     matthew  10484:     if ($tmp[0] =~ m/^error:.*/) { 
                   10485:         %names=(); 
                   10486:     } else {
                   10487:         %names = @tmp;
1.1075    raeburn  10488:         %oldnames = %names;
1.313     matthew  10489:     }
1.388     www      10490: #
1.1058    raeburn  10491: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10492: # of users did not contain them), do not overwrite existing values
                   10493: # unless field is in $candelete array ref.  
                   10494: #
                   10495: 
                   10496:     my @fields = ('firstname','middlename','lastname','generation',
                   10497:                   'permanentemail','id');
                   10498:     my %newvalues;
                   10499:     if (ref($candelete) eq 'ARRAY') {
                   10500:         foreach my $field (@fields) {
                   10501:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10502:                 if ($field eq 'firstname') {
                   10503:                     $names{$field} = $first;
                   10504:                 } elsif ($field eq 'middlename') {
                   10505:                     $names{$field} = $middle;
                   10506:                 } elsif ($field eq 'lastname') {
                   10507:                     $names{$field} = $last;
                   10508:                 } elsif ($field eq 'generation') { 
                   10509:                     $names{$field} = $gene;
                   10510:                 } elsif ($field eq 'permanentemail') {
                   10511:                     $names{$field} = $email;
                   10512:                 } elsif ($field eq 'id') {
                   10513:                     $names{$field}  = $uid;
                   10514:                 }
                   10515:             }
                   10516:         }
                   10517:     }
1.388     www      10518:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10519:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10520:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10521:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10522:     if ($email) {
                   10523:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10524:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10525:     }
1.899     raeburn  10526:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10527:     if (defined($inststatus)) {
                   10528:         $names{'inststatus'} = '';
                   10529:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10530:         if (ref($usertypes) eq 'HASH') {
                   10531:             my @okstatuses; 
                   10532:             foreach my $item (split(/:/,$inststatus)) {
                   10533:                 if (defined($usertypes->{$item})) {
                   10534:                     push(@okstatuses,$item);  
                   10535:                 }
                   10536:             }
                   10537:             if (@okstatuses) {
                   10538:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10539:             }
                   10540:         }
                   10541:     }
1.1075    raeburn  10542:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10543:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10544:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10545:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10546:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10547:     } else {
                   10548:         $logmsg .= ' during self creation';
                   10549:     }
1.1075    raeburn  10550:     my $changed;
                   10551:     if ($newuser) {
                   10552:         $changed = 1;
                   10553:     } else {
                   10554:         foreach my $field (@fields) {
                   10555:             if ($names{$field} ne $oldnames{$field}) {
                   10556:                 $changed = 1;
                   10557:                 last;
                   10558:             }
                   10559:         }
                   10560:     }
                   10561:     unless ($changed) {
                   10562:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10563:         &logthis($logmsg);
                   10564:         return 'ok';
                   10565:     }
                   10566:     my $reply = &put('environment', \%names, $udom,$uname);
                   10567:     if ($reply ne 'ok') { 
                   10568:         return 'error: '.$reply;
                   10569:     }
1.1087    raeburn  10570:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10571:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10572:     }
1.1075    raeburn  10573:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10574:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10575:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10576:     &logthis($logmsg);
1.134     albertel 10577:     return 'ok';
1.80      www      10578: }
                   10579: 
1.81      www      10580: # -------------------------------------------------------------- Modify student
1.80      www      10581: 
1.81      www      10582: sub modifystudent {
                   10583:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10584:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10585:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10586:     if (!$cid) {
1.620     albertel 10587: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10588: 	    return 'not_in_class';
                   10589: 	}
1.80      www      10590:     }
                   10591: # --------------------------------------------------------------- Make the user
1.81      www      10592:     my $reply=&modifyuser
1.209     matthew  10593: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10594:          $desiredhome,$email,$inststatus);
1.80      www      10595:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10596:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10597:     # student's environment
1.297     matthew  10598:     $uid = undef if (!$forceid);
1.455     albertel 10599:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10600: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10601:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10602:     return $reply;
                   10603: }
                   10604: 
                   10605: sub modify_student_enrollment {
1.1172.2.23  raeburn  10606:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10607:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10608:     my ($cdom,$cnum,$chome);
                   10609:     if (!$cid) {
1.620     albertel 10610: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10611: 	    return 'not_in_class';
                   10612: 	}
1.620     albertel 10613: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10614: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10615:     } else {
                   10616: 	($cdom,$cnum)=split(/_/,$cid);
                   10617:     }
1.620     albertel 10618:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10619:     if (!$chome) {
1.457     raeburn  10620: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10621:     }
1.455     albertel 10622:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10623:     # Make sure the user exists
1.81      www      10624:     my $uhome=&homeserver($uname,$udom);
                   10625:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10626: 	return 'error: no such user';
                   10627:     }
1.297     matthew  10628:     # Get student data if we were not given enough information
                   10629:     if (!defined($first)  || $first  eq '' || 
                   10630:         !defined($last)   || $last   eq '' || 
                   10631:         !defined($uid)    || $uid    eq '' || 
                   10632:         !defined($middle) || $middle eq '' || 
                   10633:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10634:         # They did not supply us with enough data to enroll the student, so
                   10635:         # we need to pick up more information.
1.297     matthew  10636:         my %tmp = &get('environment',
1.294     matthew  10637:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10638:                        ,$udom,$uname);
                   10639: 
1.800     albertel 10640:         #foreach my $key (keys(%tmp)) {
                   10641:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10642:         #}
1.294     matthew  10643:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10644:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10645:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10646:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10647:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10648:     }
1.556     albertel 10649:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10650:     my $user = "$uname:$udom";
                   10651:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10652:     my $reply=cput('classlist',
1.1148    raeburn  10653: 		   {$user => 
1.1172.2.76  raeburn  10654: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10655: 		   $cdom,$cnum);
1.1148    raeburn  10656:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10657:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10658:     } else { 
1.81      www      10659: 	return 'error: '.$reply;
                   10660:     }
1.297     matthew  10661:     # Add student role to user
1.83      www      10662:     my $uurl='/'.$cid;
1.81      www      10663:     $uurl=~s/\_/\//g;
                   10664:     if ($usec) {
                   10665: 	$uurl.='/'.$usec;
                   10666:     }
1.1148    raeburn  10667:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10668:                              $selfenroll,$context);
                   10669:     if ($result ne 'ok') {
                   10670:         if ($old_entry{$user} ne '') {
                   10671:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10672:         } else {
                   10673:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10674:         }
                   10675:     }
                   10676:     return $result; 
1.21      www      10677: }
                   10678: 
1.556     albertel 10679: sub format_name {
                   10680:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10681:     my $name;
                   10682:     if ($first ne 'lastname') {
                   10683: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10684:     } else {
                   10685: 	if ($lastname=~/\S/) {
                   10686: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10687: 	    $name=~s/\s+,/,/;
                   10688: 	} else {
                   10689: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10690: 	}
                   10691:     }
                   10692:     $name=~s/^\s+//;
                   10693:     $name=~s/\s+$//;
                   10694:     $name=~s/\s+/ /g;
                   10695:     return $name;
                   10696: }
                   10697: 
1.84      www      10698: # ------------------------------------------------- Write to course preferences
                   10699: 
                   10700: sub writecoursepref {
                   10701:     my ($courseid,%prefs)=@_;
                   10702:     $courseid=~s/^\///;
                   10703:     $courseid=~s/\_/\//g;
                   10704:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10705:     my $chome=homeserver($cnum,$cdomain);
                   10706:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10707: 	return 'error: no such course';
                   10708:     }
                   10709:     my $cstring='';
1.800     albertel 10710:     foreach my $pref (keys(%prefs)) {
                   10711: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10712:     }
1.84      www      10713:     $cstring=~s/\&$//;
                   10714:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10715: }
                   10716: 
                   10717: # ---------------------------------------------------------- Make/modify course
                   10718: 
                   10719: sub createcourse {
1.741     raeburn  10720:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10721:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10722:     $url=&declutter($url);
                   10723:     my $cid='';
1.1028    raeburn  10724:     if ($context eq 'requestcourses') {
                   10725:         my $can_create = 0;
                   10726:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10727:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10728:22):             my $reload;
                   10729:22):             if (($callercontext eq 'auto') &&
                   10730:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10731:22):                 $reload = 'reload';
                   10732:22):             }
                   10733:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10734:                                   $context)) {
                   10735:                 $can_create = 1;
                   10736:             }
                   10737:         } else {
                   10738:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10739:                                            $category);
                   10740:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10741:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10742:                 if (@curr > 0) {
                   10743:                     my @options = qw(approval validate autolimit);
                   10744:                     my $optregex = join('|',@options);
                   10745:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10746:                         $can_create = 1;
                   10747:                     }
                   10748:                 }
                   10749:             }
                   10750:         }
                   10751:         if ($can_create) {
                   10752:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10753:                 unless (&allowed('ccc',$udom)) {
                   10754:                     return 'refused'; 
                   10755:                 }
1.1017    raeburn  10756:             }
                   10757:         } else {
                   10758:             return 'refused';
                   10759:         }
1.1028    raeburn  10760:     } elsif (!&allowed('ccc',$udom)) {
                   10761:         return 'refused';
1.84      www      10762:     }
1.1011    raeburn  10763: # --------------------------------------------------------------- Get Unique ID
                   10764:     my $uname;
                   10765:     if ($cnum =~ /^$match_courseid$/) {
                   10766:         my $chome=&homeserver($cnum,$udom,'true');
                   10767:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10768:             $uname = $cnum;
                   10769:         } else {
1.1038    raeburn  10770:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10771:         }
                   10772:     } else {
1.1038    raeburn  10773:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10774:     }
                   10775:     return $uname if ($uname =~ /^error/);
                   10776: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10777:     if (!defined($course_server)) {
                   10778:         if (defined(&domain($udom,'primary'))) {
                   10779:             $course_server = &domain($udom,'primary');
                   10780:         } else {
                   10781:             $course_server = $env{'user.home'}; 
                   10782:         }
                   10783:     }
                   10784:     my %host_servers =
                   10785:         &Apache::lonnet::get_servers($udom,'library');
                   10786:     unless ($host_servers{$course_server}) {
                   10787:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10788:     }
1.84      www      10789: # ------------------------------------------------------------- Make the course
                   10790:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10791:                       $course_server);
1.84      www      10792:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10793:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10794:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10795: 	return 'error: no such course';
                   10796:     }
1.271     www      10797: # ----------------------------------------------------------------- Course made
1.516     raeburn  10798: # log existence
1.1029    raeburn  10799:     my $now = time;
1.918     raeburn  10800:     my $newcourse = {
                   10801:                     $udom.'_'.$uname => {
1.921     raeburn  10802:                                      description => $description,
                   10803:                                      inst_code   => $inst_code,
                   10804:                                      owner       => $course_owner,
                   10805:                                      type        => $crstype,
1.1029    raeburn  10806:                                      creator     => $env{'user.name'}.':'.
                   10807:                                                     $env{'user.domain'},
                   10808:                                      created     => $now,
                   10809:                                      context     => $context,
1.918     raeburn  10810:                                                 },
                   10811:                     };
1.921     raeburn  10812:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10813: # set toplevel url
1.271     www      10814:     my $topurl=$url;
                   10815:     unless ($nonstandard) {
                   10816: # ------------------------------------------ For standard courses, make top url
                   10817:         my $mapurl=&clutter($url);
1.278     www      10818:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10819:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10820: <map>
                   10821: <resource id="1" type="start"></resource>
                   10822: <resource id="2" src="$mapurl"></resource>
                   10823: <resource id="3" type="finish"></resource>
                   10824: <link index="1" from="1" to="2"></link>
                   10825: <link index="2" from="2" to="3"></link>
                   10826: </map>
                   10827: ENDINITMAP
                   10828:         $topurl=&declutter(
1.638     albertel 10829:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10830:                           );
                   10831:     }
                   10832: # ----------------------------------------------------------- Write preferences
1.84      www      10833:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10834:                      ('description'              => $description,
                   10835:                       'url'                      => $topurl,
                   10836:                       'internal.creator'         => $env{'user.name'}.':'.
                   10837:                                                     $env{'user.domain'},
                   10838:                       'internal.created'         => $now,
                   10839:                       'internal.creationcontext' => $context)
                   10840:                     );
1.84      www      10841:     return '/'.$udom.'/'.$uname;
                   10842: }
                   10843: 
1.1011    raeburn  10844: # ------------------------------------------------------------------- Create ID
                   10845: sub generate_coursenum {
1.1038    raeburn  10846:     my ($udom,$crstype) = @_;
1.1011    raeburn  10847:     my $domdesc = &domain($udom);
                   10848:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10849:     my $first;
                   10850:     if ($crstype eq 'Community') {
                   10851:         $first = '0';
                   10852:     } else {
                   10853:         $first = int(1+rand(9)); 
                   10854:     } 
                   10855:     my $uname=$first.
1.1011    raeburn  10856:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10857:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10858:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10859: # ----------------------------------------------- Make sure that does not exist
                   10860:     my $uhome=&homeserver($uname,$udom,'true');
                   10861:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10862:         if ($crstype eq 'Community') {
                   10863:             $first = '0';
                   10864:         } else {
                   10865:             $first = int(1+rand(9));
                   10866:         }
                   10867:         $uname=$first.
1.1011    raeburn  10868:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10869:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10870:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10871:         $uhome=&homeserver($uname,$udom,'true');
                   10872:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10873:             return 'error: unable to generate unique course-ID';
                   10874:         }
                   10875:     }
                   10876:     return $uname;
                   10877: }
                   10878: 
1.813     albertel 10879: sub is_course {
1.1167    droeschl 10880:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10881:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10882:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10883:     my $uhome=&homeserver($cnum,$cdom);
                   10884:     my $iscourse;
                   10885:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10886:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10887:     } else {
                   10888:         my $hashid = $cdom.':'.$cnum;
                   10889:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10890:         unless (defined($cached)) {
                   10891:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10892:                                         $cnum,undef,undef,'.');
                   10893:             $iscourse = 0;
                   10894:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10895:                 $iscourse = 1;
                   10896:             }
                   10897:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10898:         }
                   10899:     }
                   10900:     return unless($iscourse);
1.1167    droeschl 10901:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10902: }
                   10903: 
1.1015    raeburn  10904: sub store_userdata {
                   10905:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10906:     my $result;
1.1016    raeburn  10907:     if ($datakey ne '') {
1.1013    raeburn  10908:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10909:             if ($udom eq '' || $uname eq '') {
                   10910:                 $udom = $env{'user.domain'};
                   10911:                 $uname = $env{'user.name'};
                   10912:             }
                   10913:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10914:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10915:                 $result = 'error: no_host';
                   10916:             } else {
1.1172.2.138  raeburn  10917:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10918:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10919: 
                   10920:                 my $namevalue='';
                   10921:                 foreach my $key (keys(%{$storehash})) {
                   10922:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10923:                 }
                   10924:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10925:                 unless ($namespace eq 'courserequests') {
                   10926:                     $datakey = &escape($datakey);
                   10927:                 }
1.1105    raeburn  10928:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10929:                                   $namevalue,$uhome);
1.1013    raeburn  10930:             }
                   10931:         } else {
                   10932:             $result = 'error: data to store was not a hash reference'; 
                   10933:         }
                   10934:     } else {
                   10935:         $result= 'error: invalid requestkey'; 
                   10936:     }
                   10937:     return $result;
                   10938: }
                   10939: 
1.21      www      10940: # ---------------------------------------------------------- Assign Custom Role
                   10941: 
                   10942: sub assigncustomrole {
1.957     raeburn  10943:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10944:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10945:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10946: }
                   10947: 
                   10948: # ----------------------------------------------------------------- Revoke Role
                   10949: 
                   10950: sub revokerole {
1.957     raeburn  10951:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10952:     my $now=time;
1.965     raeburn  10953:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10954: }
                   10955: 
                   10956: # ---------------------------------------------------------- Revoke Custom Role
                   10957: 
                   10958: sub revokecustomrole {
1.957     raeburn  10959:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10960:     my $now=time;
1.357     www      10961:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10962:            $deleteflag,$selfenroll,$context);
1.17      www      10963: }
                   10964: 
1.533     banghart 10965: # ------------------------------------------------------------ Disk usage
1.535     albertel 10966: sub diskusage {
1.955     raeburn  10967:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10968:     $directorypath =~ s/\/$//;
                   10969:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10970:                        .&escape($getpropath).':'.&escape($uname).':'
                   10971:                        .&escape($udom),homeserver($uname,$udom));
                   10972:     if ($listing eq 'unknown_cmd') {
                   10973:         if ($getpropath) {
                   10974:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10975:         }
                   10976:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10977:     }
1.514     albertel 10978:     return $listing;
1.512     banghart 10979: }
                   10980: 
1.566     banghart 10981: sub is_locked {
1.1096    raeburn  10982:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10983:     my @check;
                   10984:     my $is_locked;
1.1093    raeburn  10985:     push (@check,$file_name);
1.613     albertel 10986:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10987: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10988:     my ($tmp)=keys(%locked);
                   10989:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10990:     
1.566     banghart 10991:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10992:         $is_locked = 'false';
                   10993:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10994:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10995:                $is_locked = 'true';
1.1096    raeburn  10996:                if (ref($which) eq 'ARRAY') {
                   10997:                    push(@{$which},$entry);
                   10998:                } else {
                   10999:                    last;
                   11000:                }
1.745     raeburn  11001:            }
                   11002:        }
1.566     banghart 11003:     } else {
                   11004:         $is_locked = 'false';
                   11005:     }
1.1093    raeburn  11006:     return $is_locked;
1.566     banghart 11007: }
                   11008: 
1.759     albertel 11009: sub declutter_portfile {
                   11010:     my ($file) = @_;
1.833     albertel 11011:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11012:     return $file;
                   11013: }
                   11014: 
1.559     banghart 11015: # ------------------------------------------------------------- Mark as Read Only
                   11016: 
                   11017: sub mark_as_readonly {
                   11018:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11019:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11020:     my ($tmp)=keys(%current_permissions);
                   11021:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11022:     foreach my $file (@{$files}) {
1.759     albertel 11023: 	$file = &declutter_portfile($file);
1.561     banghart 11024:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11025:     }
1.613     albertel 11026:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11027:     return;
                   11028: }
                   11029: 
1.572     banghart 11030: # ------------------------------------------------------------Save Selected Files
                   11031: 
                   11032: sub save_selected_files {
                   11033:     my ($user, $path, @files) = @_;
                   11034:     my $filename = $user."savedfiles";
1.573     banghart 11035:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11036:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11037:     foreach my $file (@files) {
1.620     albertel 11038:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11039:     }
                   11040:     foreach my $file (@other_files) {
1.574     banghart 11041:         print (OUT $file."\n");
1.572     banghart 11042:     }
1.574     banghart 11043:     close (OUT);
1.572     banghart 11044:     return 'ok';
                   11045: }
                   11046: 
1.574     banghart 11047: sub clear_selected_files {
                   11048:     my ($user) = @_;
                   11049:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11050:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11051:     print (OUT undef);
                   11052:     close (OUT);
                   11053:     return ("ok");    
                   11054: }
                   11055: 
1.572     banghart 11056: sub files_in_path {
                   11057:     my ($user, $path) = @_;
                   11058:     my $filename = $user."savedfiles";
                   11059:     my %return_files;
1.1172.2.96  raeburn  11060:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11061:     while (my $line_in = <IN>) {
1.574     banghart 11062:         chomp ($line_in);
                   11063:         my @paths_and_file = split (m!/!, $line_in);
                   11064:         my $file_part = pop (@paths_and_file);
                   11065:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11066:         $path_part.='/';
                   11067:         my $path_and_file = $path_part.$file_part;
                   11068:         if ($path_part eq $path) {
                   11069:             $return_files{$file_part}= 'selected';
                   11070:         }
                   11071:     }
1.574     banghart 11072:     close (IN);
                   11073:     return (\%return_files);
1.572     banghart 11074: }
                   11075: 
                   11076: # called in portfolio select mode, to show files selected NOT in current directory
                   11077: sub files_not_in_path {
                   11078:     my ($user, $path) = @_;
                   11079:     my $filename = $user."savedfiles";
                   11080:     my @return_files;
                   11081:     my $path_part;
1.1172.2.96  raeburn  11082:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11083:     while (my $line = <IN>) {
1.572     banghart 11084:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11085:         my @paths_and_file = split(m|/|, $line);
                   11086:         my $file_part = pop(@paths_and_file);
                   11087:         chomp($file_part);
                   11088:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11089:         $path_part .= '/';
                   11090:         my $path_and_file = $path_part.$file_part;
                   11091:         if ($path_part ne $path) {
1.800     albertel 11092:             push(@return_files, ($path_and_file));
1.572     banghart 11093:         }
                   11094:     }
1.800     albertel 11095:     close(OUT);
1.574     banghart 11096:     return (@return_files);
1.572     banghart 11097: }
                   11098: 
1.745     raeburn  11099: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11100: 
1.745     raeburn  11101: sub get_portfile_permissions {
                   11102:     my ($domain,$user) = @_;
1.613     albertel 11103:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11104:     my ($tmp)=keys(%current_permissions);
                   11105:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11106:     return \%current_permissions;
                   11107: }
                   11108: 
                   11109: #---------------------------------------------Get portfolio file access controls
                   11110: 
1.749     raeburn  11111: sub get_access_controls {
1.745     raeburn  11112:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11113:     my %access;
                   11114:     my $real_file = $file;
                   11115:     $file =~ s/\.meta$//;
1.745     raeburn  11116:     if (defined($file)) {
1.749     raeburn  11117:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11118:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11119:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11120:             }
                   11121:         }
1.745     raeburn  11122:     } else {
1.749     raeburn  11123:         foreach my $key (keys(%{$current_permissions})) {
                   11124:             if ($key =~ /\0accesscontrol$/) {
                   11125:                 if (defined($group)) {
                   11126:                     if ($key !~ m-^\Q$group\E/-) {
                   11127:                         next;
                   11128:                     }
                   11129:                 }
                   11130:                 my ($fullpath) = split(/\0/,$key);
                   11131:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11132:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11133:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11134:                     }
                   11135:                 }
                   11136:             }
                   11137:         }
                   11138:     }
                   11139:     return %access;
                   11140: }
                   11141: 
                   11142: sub modify_access_controls {
                   11143:     my ($file_name,$changes,$domain,$user)=@_;
                   11144:     my ($outcome,$deloutcome);
                   11145:     my %store_permissions;
                   11146:     my %new_values;
                   11147:     my %new_control;
                   11148:     my %translation;
                   11149:     my @deletions = ();
                   11150:     my $now = time;
                   11151:     if (exists($$changes{'activate'})) {
                   11152:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11153:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11154:             my $numnew = scalar(@newitems);
                   11155:             for (my $i=0; $i<$numnew; $i++) {
                   11156:                 my $newkey = $newitems[$i];
                   11157:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11158:                 if ($newkey =~ /^\d+:/) { 
                   11159:                     $newkey =~ s/^(\d+)/$newid/;
                   11160:                     $translation{$1} = $newid;
                   11161:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11162:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11163:                     $translation{$1} = $newid;
                   11164:                 }
1.749     raeburn  11165:                 $new_values{$file_name."\0".$newkey} = 
                   11166:                                           $$changes{'activate'}{$newitems[$i]};
                   11167:                 $new_control{$newkey} = $now;
                   11168:             }
                   11169:         }
                   11170:     }
                   11171:     my %todelete;
                   11172:     my %changed_items;
                   11173:     foreach my $action ('delete','update') {
                   11174:         if (exists($$changes{$action})) {
                   11175:             if (ref($$changes{$action}) eq 'HASH') {
                   11176:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11177:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11178:                     if ($action eq 'delete') { 
                   11179:                         $todelete{$itemnum} = 1;
                   11180:                     } else {
                   11181:                         $changed_items{$itemnum} = $key;
                   11182:                     }
                   11183:                 }
1.745     raeburn  11184:             }
                   11185:         }
1.749     raeburn  11186:     }
                   11187:     # get lock on access controls for file.
                   11188:     my $lockhash = {
                   11189:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11190:                                                        ':'.$env{'user.domain'},
                   11191:                    }; 
                   11192:     my $tries = 0;
                   11193:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11194:    
1.1172.2.79  raeburn  11195:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11196:         $tries ++;
1.1172.2.79  raeburn  11197:         sleep(0.1);
1.749     raeburn  11198:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11199:     }
                   11200:     if ($gotlock eq 'ok') {
                   11201:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11202:         my ($tmp)=keys(%curr_permissions);
                   11203:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11204:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11205:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11206:             if (ref($curr_controls) eq 'HASH') {
                   11207:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11208:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11209:                     if (defined($todelete{$itemnum})) {
                   11210:                         push(@deletions,$file_name."\0".$control_item);
                   11211:                     } else {
                   11212:                         if (defined($changed_items{$itemnum})) {
                   11213:                             $new_control{$changed_items{$itemnum}} = $now;
                   11214:                             push(@deletions,$file_name."\0".$control_item);
                   11215:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11216:                         } else {
                   11217:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11218:                         }
                   11219:                     }
1.745     raeburn  11220:                 }
                   11221:             }
                   11222:         }
1.970     raeburn  11223:         my ($group);
                   11224:         if (&is_course($domain,$user)) {
                   11225:             ($group,my $file) = split(/\//,$file_name,2);
                   11226:         }
1.749     raeburn  11227:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11228:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11229:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11230:         #  remove lock
                   11231:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11232:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11233:         my $sqlresult =
1.970     raeburn  11234:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11235:                                     $group);
1.749     raeburn  11236:     } else {
                   11237:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11238:     }
1.749     raeburn  11239:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11240: }
                   11241: 
1.827     raeburn  11242: sub make_public_indefinitely {
                   11243:     my ($requrl) = @_;
                   11244:     my $now = time;
                   11245:     my $action = 'activate';
                   11246:     my $aclnum = 0;
                   11247:     if (&is_portfolio_url($requrl)) {
                   11248:         my (undef,$udom,$unum,$file_name,$group) =
                   11249:             &parse_portfolio_url($requrl);
                   11250:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11251:         my %access_controls = &get_access_controls($current_perms,
                   11252:                                                    $group,$file_name);
                   11253:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11254:             my ($num,$scope,$end,$start) = 
                   11255:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11256:             if ($scope eq 'public') {
                   11257:                 if ($start <= $now && $end == 0) {
                   11258:                     $action = 'none';
                   11259:                 } else {
                   11260:                     $action = 'update';
                   11261:                     $aclnum = $num;
                   11262:                 }
                   11263:                 last;
                   11264:             }
                   11265:         }
                   11266:         if ($action eq 'none') {
                   11267:              return 'ok';
                   11268:         } else {
                   11269:             my %changes;
                   11270:             my $newend = 0;
                   11271:             my $newstart = $now;
                   11272:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11273:             $changes{$action}{$newkey} = {
                   11274:                 type => 'public',
                   11275:                 time => {
                   11276:                     start => $newstart,
                   11277:                     end   => $newend,
                   11278:                 },
                   11279:             };
                   11280:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11281:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11282:             return $outcome;
                   11283:         }
                   11284:     } else {
                   11285:         return 'invalid';
                   11286:     }
                   11287: }
                   11288: 
1.745     raeburn  11289: #------------------------------------------------------Get Marked as Read Only
                   11290: 
                   11291: sub get_marked_as_readonly {
                   11292:     my ($domain,$user,$what,$group) = @_;
                   11293:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11294:     my @readonly_files;
1.629     banghart 11295:     my $cmp1=$what;
                   11296:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11297:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11298:         if (defined($group)) {
                   11299:             if ($file_name !~ m-^\Q$group\E/-) {
                   11300:                 next;
                   11301:             }
                   11302:         }
1.561     banghart 11303:         if (ref($value) eq "ARRAY"){
                   11304:             foreach my $stored_what (@{$value}) {
1.629     banghart 11305:                 my $cmp2=$stored_what;
1.759     albertel 11306:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11307:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11308:                 }
1.629     banghart 11309:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11310:                     push(@readonly_files, $file_name);
1.745     raeburn  11311:                     last;
1.563     banghart 11312:                 } elsif (!defined($what)) {
                   11313:                     push(@readonly_files, $file_name);
1.745     raeburn  11314:                     last;
1.561     banghart 11315:                 }
                   11316:             }
1.745     raeburn  11317:         }
1.561     banghart 11318:     }
                   11319:     return @readonly_files;
                   11320: }
1.577     banghart 11321: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11322: 
1.577     banghart 11323: sub get_marked_as_readonly_hash {
1.745     raeburn  11324:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11325:     my %readonly_files;
1.745     raeburn  11326:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11327:         if (defined($group)) {
                   11328:             if ($file_name !~ m-^\Q$group\E/-) {
                   11329:                 next;
                   11330:             }
                   11331:         }
1.577     banghart 11332:         if (ref($value) eq "ARRAY"){
                   11333:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11334:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11335:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11336:                         if ($lock_descriptor eq 'graded') {
                   11337:                             $readonly_files{$file_name} = 'graded';
                   11338:                         } elsif ($lock_descriptor eq 'handback') {
                   11339:                             $readonly_files{$file_name} = 'handback';
                   11340:                         } else {
                   11341:                             if (!exists($readonly_files{$file_name})) {
                   11342:                                 $readonly_files{$file_name} = 'locked';
                   11343:                             }
                   11344:                         }
1.745     raeburn  11345:                     }
1.750     banghart 11346:                 } 
1.577     banghart 11347:             }
                   11348:         } 
                   11349:     }
                   11350:     return %readonly_files;
                   11351: }
1.559     banghart 11352: # ------------------------------------------------------------ Unmark as Read Only
                   11353: 
                   11354: sub unmark_as_readonly {
1.629     banghart 11355:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11356:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11357:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11358:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11359:     my $symb_crs = $what;
                   11360:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11361:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11362:     my ($tmp)=keys(%current_permissions);
                   11363:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11364:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11365:     foreach my $file (@readonly_files) {
1.759     albertel 11366: 	my $clean_file = &declutter_portfile($file);
                   11367: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11368: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11369:         my @new_locks;
                   11370:         my @del_keys;
                   11371:         if (ref($current_locks) eq "ARRAY"){
                   11372:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11373:                 my $compare=$locker;
1.749     raeburn  11374:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11375:                     $compare=join('',@{$locker});
1.746     raeburn  11376:                     if ($compare ne $symb_crs) {
                   11377:                         push(@new_locks, $locker);
                   11378:                     }
1.563     banghart 11379:                 }
                   11380:             }
1.650     albertel 11381:             if (scalar(@new_locks) > 0) {
1.563     banghart 11382:                 $current_permissions{$file} = \@new_locks;
                   11383:             } else {
                   11384:                 push(@del_keys, $file);
1.613     albertel 11385:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11386:                 delete($current_permissions{$file});
1.563     banghart 11387:             }
                   11388:         }
1.561     banghart 11389:     }
1.613     albertel 11390:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11391:     return;
                   11392: }
1.512     banghart 11393: 
1.17      www      11394: # ------------------------------------------------------------ Directory lister
                   11395: 
                   11396: sub dirlist {
1.955     raeburn  11397:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11398:     $uri=~s/^\///;
                   11399:     $uri=~s/\/$//;
1.253     stredwic 11400:     my ($udom, $uname);
1.955     raeburn  11401:     if ($getuserdir) {
1.253     stredwic 11402:         $udom = $userdomain;
                   11403:         $uname = $username;
1.955     raeburn  11404:     } else {
                   11405:         (undef,$udom,$uname)=split(/\//,$uri);
                   11406:         if(defined($userdomain)) {
                   11407:             $udom = $userdomain;
                   11408:         }
                   11409:         if(defined($username)) {
                   11410:             $uname = $username;
                   11411:         }
1.253     stredwic 11412:     }
1.955     raeburn  11413:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11414: 
1.955     raeburn  11415:     $dirRoot = $perlvar{'lonDocRoot'};
                   11416:     if (defined($getpropath)) {
                   11417:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11418:         $dirRoot =~ s/\/$//;
1.955     raeburn  11419:     } elsif (defined($getuserdir)) {
                   11420:         my $subdir=$uname.'__';
                   11421:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11422:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11423:                    ."/$udom/$subdir/$uname";
                   11424:     } elsif (defined($alternateRoot)) {
                   11425:         $dirRoot = $alternateRoot;
1.751     banghart 11426:     }
1.253     stredwic 11427: 
                   11428:     if($udom) {
                   11429:         if($uname) {
1.1135    raeburn  11430:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11431:             if ($uhome eq 'no_host') {
                   11432:                 return ([],'no_host');
                   11433:             }
1.955     raeburn  11434:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11435:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11436:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11437:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11438:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11439:             } else {
                   11440:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11441:             }
1.605     matthew  11442:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11443:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11444:                 @listing_results = split(/:/,$listing);
                   11445:             } else {
                   11446:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11447:             }
1.1135    raeburn  11448:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11449:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11450:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11451:                 return ([],$listing);
                   11452:             } else {
                   11453:                 return (\@listing_results);
1.1135    raeburn  11454:             }
1.955     raeburn  11455:         } elsif(!$alternateRoot) {
1.1136    raeburn  11456:             my (%allusers,%listerror);
1.841     albertel 11457: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11458:  	    foreach my $tryserver (keys(%servers)) {
                   11459:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11460:                                   &escape($udom),$tryserver);
                   11461:                 if ($listing eq 'unknown_cmd') {
                   11462: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11463: 				      $udom, $tryserver);
                   11464:                 } else {
                   11465:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11466:                 }
1.841     albertel 11467: 		if ($listing eq 'unknown_cmd') {
                   11468: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11469: 				      $udom, $tryserver);
                   11470: 		    @listing_results = split(/:/,$listing);
                   11471: 		} else {
                   11472: 		    @listing_results =
                   11473: 			map { &unescape($_); } split(/:/,$listing);
                   11474: 		}
1.1136    raeburn  11475:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11476:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11477:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11478:                     $listerror{$tryserver} = $listing;
                   11479:                 } else {
1.841     albertel 11480: 		    foreach my $line (@listing_results) {
                   11481: 			my ($entry) = split(/&/,$line,2);
                   11482: 			$allusers{$entry} = 1;
                   11483: 		    }
                   11484: 		}
1.253     stredwic 11485:             }
1.1136    raeburn  11486:             my @alluserslist=();
1.800     albertel 11487:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11488:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11489:             }
1.1172.2.80  raeburn  11490:             if (!%listerror) {
                   11491:                 # no errors
                   11492:                 return (\@alluserslist);
                   11493:             } elsif (scalar(keys(%servers)) == 1) {
                   11494:                 # one library server, one error
                   11495:                 my ($key) = keys(%listerror);
                   11496:                 return (\@alluserslist, $listerror{$key});
                   11497:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11498:                 # con_lost indicates that we might miss data from at least one
                   11499:                 # library server
                   11500:                 return (\@alluserslist, 'con_lost');
                   11501:             } else {
                   11502:                 # multiple library servers and no con_lost -> data should be
                   11503:                 # complete.
                   11504:                 return (\@alluserslist);
                   11505:             }
                   11506: 
1.253     stredwic 11507:         } else {
1.1136    raeburn  11508:             return ([],'missing username');
1.253     stredwic 11509:         }
1.955     raeburn  11510:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11511:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11512:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11513:         return (\@all_domains);
1.955     raeburn  11514:     } else {
1.1136    raeburn  11515:         return ([],'missing domain');
1.275     stredwic 11516:     }
                   11517: }
                   11518: 
                   11519: # --------------------------------------------- GetFileTimestamp
                   11520: # This function utilizes dirlist and returns the date stamp for
                   11521: # when it was last modified.  It will also return an error of -1
                   11522: # if an error occurs
                   11523: 
                   11524: sub GetFileTimestamp {
1.955     raeburn  11525:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11526:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11527:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11528:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11529:                                     undef,$getuserdir);
                   11530:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11531:         return -1;
                   11532:     }
                   11533:     if (ref($fileref) eq 'ARRAY') {
                   11534:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11535:         # @stats contains first the filename, then the stat output
                   11536:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11537:     } else {
                   11538:         return -1;
1.253     stredwic 11539:     }
1.26      www      11540: }
                   11541: 
1.712     albertel 11542: sub stat_file {
                   11543:     my ($uri) = @_;
1.787     albertel 11544:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11545: 
1.955     raeburn  11546:     my ($udom,$uname,$file);
1.712     albertel 11547:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11548: 	($udom,$uname,$file) =
1.811     albertel 11549: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11550: 	$file = 'userfiles/'.$file;
                   11551:     }
                   11552:     if ($uri =~ m-^/res/-) {
                   11553: 	($udom,$uname) = 
1.807     albertel 11554: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11555: 	$file = $uri;
                   11556:     }
                   11557: 
                   11558:     if (!$udom || !$uname || !$file) {
                   11559: 	# unable to handle the uri
                   11560: 	return ();
                   11561:     }
1.956     raeburn  11562:     my $getpropath;
                   11563:     if ($file =~ /^userfiles\//) {
                   11564:         $getpropath = 1;
                   11565:     }
1.1136    raeburn  11566:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11567:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11568:         return ();
                   11569:     } else {
                   11570:         if (ref($listref) eq 'ARRAY') {
                   11571:             my @stats = split('&',$listref->[0]);
                   11572: 	    shift(@stats); #filename is first
                   11573: 	    return @stats;
                   11574:         }
1.712     albertel 11575:     }
                   11576:     return ();
                   11577: }
                   11578: 
1.26      www      11579: # -------------------------------------------------------- Value of a Condition
                   11580: 
1.713     albertel 11581: # gets the value of a specific preevaluated condition
                   11582: #    stored in the string  $env{user.state.<cid>}
                   11583: # or looks up a condition reference in the bighash and if if hasn't
                   11584: # already been evaluated recurses into docondval to get the value of
                   11585: # the condition, then memoizing it to 
                   11586: #   $env{user.state.<cid>.<condition>}
1.40      www      11587: sub directcondval {
                   11588:     my $number=shift;
1.620     albertel 11589:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11590: 	&Apache::lonuserstate::evalstate();
                   11591:     }
1.713     albertel 11592:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11593: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11594:     } elsif ($number =~ /^_/) {
                   11595: 	my $sub_condition;
                   11596: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11597: 		&GDBM_READER(),0640)) {
                   11598: 	    $sub_condition=$bighash{'conditions'.$number};
                   11599: 	    untie(%bighash);
                   11600: 	}
                   11601: 	my $value = &docondval($sub_condition);
1.949     raeburn  11602: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11603: 	return $value;
                   11604:     }
1.620     albertel 11605:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11606:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11607:     } else {
                   11608:        return 2;
                   11609:     }
                   11610: }
                   11611: 
1.713     albertel 11612: # get the collection of conditions for this resource
1.26      www      11613: sub condval {
                   11614:     my $condidx=shift;
1.54      www      11615:     my $allpathcond='';
1.713     albertel 11616:     foreach my $cond (split(/\|/,$condidx)) {
                   11617: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11618: 	    $allpathcond.=
                   11619: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11620: 	}
1.191     harris41 11621:     }
1.54      www      11622:     $allpathcond=~s/\|$//;
1.713     albertel 11623:     return &docondval($allpathcond);
                   11624: }
                   11625: 
                   11626: #evaluates an expression of conditions
                   11627: sub docondval {
                   11628:     my ($allpathcond) = @_;
                   11629:     my $result=0;
                   11630:     if ($env{'request.course.id'}
                   11631: 	&& defined($allpathcond)) {
                   11632: 	my $operand='|';
                   11633: 	my @stack;
                   11634: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11635: 	    if ($chunk eq '(') {
                   11636: 		push @stack,($operand,$result);
                   11637: 	    } elsif ($chunk eq ')') {
                   11638: 		my $before=pop @stack;
                   11639: 		if (pop @stack eq '&') {
                   11640: 		    $result=$result>$before?$before:$result;
                   11641: 		} else {
                   11642: 		    $result=$result>$before?$result:$before;
                   11643: 		}
                   11644: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11645: 		$operand=$chunk;
                   11646: 	    } else {
                   11647: 		my $new=directcondval($chunk);
                   11648: 		if ($operand eq '&') {
                   11649: 		    $result=$result>$new?$new:$result;
                   11650: 		} else {
                   11651: 		    $result=$result>$new?$result:$new;
                   11652: 		}
                   11653: 	    }
                   11654: 	}
1.26      www      11655:     }
                   11656:     return $result;
1.421     albertel 11657: }
                   11658: 
                   11659: # ---------------------------------------------------- Devalidate courseresdata
                   11660: 
                   11661: sub devalidatecourseresdata {
                   11662:     my ($coursenum,$coursedomain)=@_;
                   11663:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11664:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11665: }
                   11666: 
1.763     www      11667: 
1.200     www      11668: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11669: #
                   11670: #  Parameters:
                   11671: #      $coursenum    - Number of the course.
                   11672: #      $coursedomain - Domain at which the course was created.
                   11673: #  Returns:
                   11674: #     A hash of the course parameters along (I think) with timestamps
                   11675: #     and version info.
1.877     foxr     11676: 
1.624     albertel 11677: sub get_courseresdata {
                   11678:     my ($coursenum,$coursedomain)=@_;
1.200     www      11679:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11680:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11681:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11682:     my %dumpreply;
1.417     albertel 11683:     unless (defined($cached)) {
1.624     albertel 11684: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11685: 	$result=\%dumpreply;
1.251     albertel 11686: 	my ($tmp) = keys(%dumpreply);
                   11687: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11688: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11689: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11690: 	    return $tmp;
1.416     albertel 11691: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11692: 	    $result=undef;
1.599     albertel 11693: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11694: 	}
                   11695:     }
1.624     albertel 11696:     return $result;
                   11697: }
                   11698: 
1.633     albertel 11699: sub devalidateuserresdata {
                   11700:     my ($uname,$udom)=@_;
                   11701:     my $hashid="$udom:$uname";
                   11702:     &devalidate_cache_new('userres',$hashid);
                   11703: }
                   11704: 
1.624     albertel 11705: sub get_userresdata {
                   11706:     my ($uname,$udom)=@_;
                   11707:     #most student don\'t have any data set, check if there is some data
                   11708:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11709: 
                   11710:     my $hashid="$udom:$uname";
                   11711:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11712:     if (!defined($cached)) {
                   11713: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11714: 	$result=\%resourcedata;
                   11715: 	&do_cache_new('userres',$hashid,$result,600);
                   11716:     }
                   11717:     my ($tmp)=keys(%$result);
                   11718:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11719: 	return $result;
                   11720:     }
                   11721:     #error 2 occurs when the .db doesn't exist
                   11722:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11723:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11724: 	    &logthis("<font color=\"blue\">WARNING:".
                   11725: 		     " Trying to get resource data for ".
                   11726: 		     $uname." at ".$udom.": ".
                   11727: 		     $tmp."</font>");
                   11728:         }
1.624     albertel 11729:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11730: 	#&EXT_cache_set($udom,$uname);
                   11731: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11732: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11733:     }
                   11734:     return $tmp;
                   11735: }
1.879     foxr     11736: #----------------------------------------------- resdata - return resource data
                   11737: #  Purpose:
                   11738: #    Return resource data for either users or for a course.
                   11739: #  Parameters:
                   11740: #     $name      - Course/user name.
                   11741: #     $domain    - Name of the domain the user/course is registered on.
                   11742: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11743: #     @which     - Array of names of resources desired.
                   11744: #  Returns:
                   11745: #     The value of the first reasource in @which that is found in the
                   11746: #     resource hash.
                   11747: #  Exceptional Conditions:
                   11748: #     If the $type passed in is not valid (not the string 'course' or 
                   11749: #     'user', an undefined  reference is returned.
                   11750: #     If none of the resources are found, an undef is returned
1.624     albertel 11751: sub resdata {
                   11752:     my ($name,$domain,$type,@which)=@_;
                   11753:     my $result;
                   11754:     if ($type eq 'course') {
                   11755: 	$result=&get_courseresdata($name,$domain);
                   11756:     } elsif ($type eq 'user') {
                   11757: 	$result=&get_userresdata($name,$domain);
                   11758:     }
                   11759:     if (!ref($result)) { return $result; }    
1.251     albertel 11760:     foreach my $item (@which) {
1.927     albertel 11761: 	if (defined($result->{$item->[0]})) {
                   11762: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11763: 	}
1.250     albertel 11764:     }
1.291     albertel 11765:     return undef;
1.200     www      11766: }
                   11767: 
1.1172.2.146.  .1(raebu 11768:22): sub get_domain_lti {
                   11769:22):     my ($cdom,$context) = @_;
          .4(raebu 11770:22):     my ($name,$cachename,%lti);
          .1(raebu 11771:22):     if ($context eq 'consumer') {
                   11772:22):         $name = 'ltitools';
                   11773:22):     } elsif ($context eq 'provider') {
                   11774:22):         $name = 'lti';
          .4(raebu 11775:22):     } elsif ($context eq 'linkprot') {
                   11776:22):         $name = 'ltisec';
          .1(raebu 11777:22):     } else {
                   11778:22):         return %lti;
                   11779:22):     }
          .4(raebu 11780:22): 
                   11781:22):     if ($context eq 'linkprot') {
                   11782:22):         $cachename = $context;
                   11783:22):     } else {
                   11784:22):         $cachename = $name;
                   11785:22):     }
                   11786:22): 
                   11787:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11788:22):     if (defined($cached)) {
                   11789:22):         if (ref($result) eq 'HASH') {
                   11790:22):             %lti = %{$result};
                   11791:22):         }
                   11792:22):     } else {
                   11793:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11794:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11795:22):             if ($context eq 'linkprot') {
                   11796:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11797:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11798:22):                 }
                   11799:22):             } else {
                   11800:22):                 %lti = %{$domconfig{$name}};
                   11801:22):             }
                   11802:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11803:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11804:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11805:22):                     foreach my $id (keys(%lti)) {
                   11806:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11807:22):                             foreach my $item ('key','secret') {
                   11808:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11809:22):                             }
          .1(raebu 11810:22):                         }
                   11811:22):                     }
                   11812:22):                 }
                   11813:22):             }
                   11814:22):         }
                   11815:22):         my $cachetime = 24*60*60;
          .4(raebu 11816:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11817:22):     }
                   11818:22):     return %lti;
                   11819:22): }
                   11820:22): 
                   11821:22): sub get_course_lti {
                   11822:22):     my ($cnum,$cdom) = @_;
                   11823:22):     my $hashid=$cdom.'_'.$cnum;
                   11824:22):     my %courselti;
                   11825:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11826:22):     if (defined($cached)) {
                   11827:22):         if (ref($result) eq 'HASH') {
                   11828:22):             %courselti = %{$result};
                   11829:22):         }
                   11830:22):     } else {
                   11831:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11832:22):         my $cachetime = 24*60*60;
                   11833:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11834:22):     }
                   11835:22):     return %courselti;
                   11836:22): }
                   11837:22): 
          .3(raebu 11838:22): sub courselti_itemid {
                   11839:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11840:22):     my ($chome,$itemid);
                   11841:22):     $chome = &homeserver($cnum,$cdom);
                   11842:22):     return if ($chome eq 'no_host');
                   11843:22):     if (ref($params) eq 'HASH') {
                   11844:22):         my $items = &freeze_escape($params);
                   11845:22):         my $rep;
                   11846:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11847:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11848:22):         } else {
                   11849:22):             my $escurl = &escape($url);
                   11850:22):             my $escmethod = &escape($method);
                   11851:22):             my $items = &freeze_escape($params);
                   11852:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11853:22):         }
                   11854:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11855:22):                 ($rep eq 'unknown_cmd')) {
                   11856:22):             $itemid = $rep;
                   11857:22):         }
                   11858:22):     }
                   11859:22):     return $itemid;
                   11860:22): }
                   11861:22): 
                   11862:22): sub domainlti_itemid {
                   11863:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11864:22):     my ($primary_id,$itemid);
                   11865:22):     $primary_id = &domain($cdom,'primary');
                   11866:22):     return if ($primary_id eq '');
                   11867:22):     if (ref($params) eq 'HASH') {
                   11868:22):         my $items = &freeze_escape($params);
                   11869:22):         my $rep;
                   11870:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11871:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11872:22):         } else {
                   11873:22):             my $cnum = '';
                   11874:22):             my $escurl = &escape($url);
                   11875:22):             my $escmethod = &escape($method);
                   11876:22):             my $items = &freeze_escape($params);
                   11877:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11878:22):         }
                   11879:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11880:22):                 ($rep eq 'unknown_cmd')) {
                   11881:22):             $itemid = $rep;
                   11882:22):         }
                   11883:22):     }
                   11884:22):     return $itemid;
                   11885:22): }
                   11886:22): 
1.1172.2.31  raeburn  11887: sub get_numsuppfiles {
                   11888:     my ($cnum,$cdom,$ignorecache)=@_;
                   11889:     my $hashid=$cnum.':'.$cdom;
                   11890:     my ($suppcount,$cached);
                   11891:     unless ($ignorecache) {
                   11892:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11893:     }
                   11894:     unless (defined($cached)) {
                   11895:         my $chome=&homeserver($cnum,$cdom);
                   11896:         unless ($chome eq 'no_host') {
                   11897:             ($suppcount,my $errors) = (0,0);
                   11898:             my $suppmap = 'supplemental.sequence';
                   11899:             ($suppcount,$errors) =
                   11900:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11901:         }
                   11902:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11903:     }
                   11904:     return $suppcount;
                   11905: }
                   11906: 
1.379     matthew  11907: #
                   11908: # EXT resource caching routines
                   11909: #
                   11910: 
1.1172.2.146.  .1(raebu 11911:22): {
                   11912:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11913:22): #
                   11914:22): # The course for which we cache
                   11915:22): my $cachedmapkey='';
                   11916:22): # The cached recursive maps for this course
                   11917:22): my %cachedmaps=();
                   11918:22): # When this was last done
                   11919:22): my $cachedmaptime='';
                   11920:22): 
1.379     matthew  11921: sub clear_EXT_cache_status {
1.383     albertel 11922:     &delenv('cache.EXT.');
1.379     matthew  11923: }
                   11924: 
                   11925: sub EXT_cache_status {
                   11926:     my ($target_domain,$target_user) = @_;
1.383     albertel 11927:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11928:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11929:         # We know already the user has no data
                   11930:         return 1;
                   11931:     } else {
                   11932:         return 0;
                   11933:     }
                   11934: }
                   11935: 
                   11936: sub EXT_cache_set {
                   11937:     my ($target_domain,$target_user) = @_;
1.383     albertel 11938:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11939:     #&appenv({$cachename => time});
1.379     matthew  11940: }
                   11941: 
1.28      www      11942: # --------------------------------------------------------- Value of a Variable
1.58      www      11943: sub EXT {
1.715     albertel 11944: 
1.1172.2.28  raeburn  11945:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11946:     unless ($varname) { return ''; }
1.218     albertel 11947:     #get real user name/domain, courseid and symb
                   11948:     my $courseid;
1.359     albertel 11949:     my $publicuser;
1.427     www      11950:     if ($symbparm) {
                   11951: 	$symbparm=&get_symb_from_alias($symbparm);
                   11952:     }
1.218     albertel 11953:     if (!($uname && $udom)) {
1.790     albertel 11954:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11955:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11956:     } else {
1.620     albertel 11957: 	$courseid=$env{'request.course.id'};
1.218     albertel 11958:     }
1.48      www      11959:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11960:     my $rest;
1.320     albertel 11961:     if (defined($therest[0])) {
1.48      www      11962:        $rest=join('.',@therest);
                   11963:     } else {
                   11964:        $rest='';
                   11965:     }
1.320     albertel 11966: 
1.57      www      11967:     my $qualifierrest=$qualifier;
                   11968:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11969:     my $spacequalifierrest=$space;
                   11970:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11971:     if ($realm eq 'user') {
1.48      www      11972: # --------------------------------------------------------------- user.resource
                   11973: 	if ($space eq 'resource') {
1.651     albertel 11974: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11975: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11976: 		 &&
1.1172.2.142  raeburn  11977: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11978: 		# if we are in the middle of processing the resource the
                   11979: 		# get the value we are planning on committing
                   11980:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11981:                     return $Apache::lonhomework::results{$qualifierrest};
                   11982:                 } else {
                   11983:                     return $Apache::lonhomework::history{$qualifierrest};
                   11984:                 }
1.335     albertel 11985: 	    } else {
1.359     albertel 11986: 		my %restored;
1.620     albertel 11987: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11988: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11989: 		} else {
                   11990: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11991: 		}
1.335     albertel 11992: 		return $restored{$qualifierrest};
                   11993: 	    }
1.48      www      11994: # ----------------------------------------------------------------- user.access
                   11995:         } elsif ($space eq 'access') {
1.218     albertel 11996: 	    # FIXME - not supporting calls for a specific user
1.48      www      11997:             return &allowed($qualifier,$rest);
                   11998: # ------------------------------------------ user.preferences, user.environment
                   11999:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12000: 	    if (($uname eq $env{'user.name'}) &&
                   12001: 		($udom eq $env{'user.domain'})) {
                   12002: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12003: 	    } else {
1.359     albertel 12004: 		my %returnhash;
                   12005: 		if (!$publicuser) {
                   12006: 		    %returnhash=&userenvironment($udom,$uname,
                   12007: 						 $qualifierrest);
                   12008: 		}
1.218     albertel 12009: 		return $returnhash{$qualifierrest};
                   12010: 	    }
1.48      www      12011: # ----------------------------------------------------------------- user.course
                   12012:         } elsif ($space eq 'course') {
1.218     albertel 12013: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12014:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12015: # ------------------------------------------------------------------- user.role
                   12016:         } elsif ($space eq 'role') {
1.218     albertel 12017: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12018:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12019:             if ($qualifier eq 'value') {
                   12020: 		return $role;
                   12021:             } elsif ($qualifier eq 'extent') {
                   12022:                 return $where;
                   12023:             }
                   12024: # ----------------------------------------------------------------- user.domain
                   12025:         } elsif ($space eq 'domain') {
1.218     albertel 12026:             return $udom;
1.48      www      12027: # ------------------------------------------------------------------- user.name
                   12028:         } elsif ($space eq 'name') {
1.218     albertel 12029:             return $uname;
1.48      www      12030: # ---------------------------------------------------- Any other user namespace
1.29      www      12031:         } else {
1.359     albertel 12032: 	    my %reply;
                   12033: 	    if (!$publicuser) {
                   12034: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12035: 	    }
                   12036: 	    return $reply{$qualifierrest};
1.48      www      12037:         }
1.236     www      12038:     } elsif ($realm eq 'query') {
                   12039: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12040:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12041: 						[$spacequalifierrest]);
1.620     albertel 12042: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12043:    } elsif ($realm eq 'request') {
1.48      www      12044: # ------------------------------------------------------------- request.browser
                   12045:         if ($space eq 'browser') {
1.1145    bisitz   12046:             return $env{'browser.'.$qualifier};
1.57      www      12047: # ------------------------------------------------------------ request.filename
                   12048:         } else {
1.620     albertel 12049:             return $env{'request.'.$spacequalifierrest};
1.29      www      12050:         }
1.28      www      12051:     } elsif ($realm eq 'course') {
1.48      www      12052: # ---------------------------------------------------------- course.description
1.620     albertel 12053:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12054:     } elsif ($realm eq 'resource') {
1.165     www      12055: 
1.620     albertel 12056: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12057: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12058: 	}
1.693     albertel 12059: 
1.1172.2.30  raeburn  12060:         if ($qualifier eq '') {
                   12061: 	    if ($space eq 'title') {
                   12062: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12063: 	        return &gettitle($symbparm);
                   12064: 	    }
1.693     albertel 12065: 	
1.1172.2.30  raeburn  12066: 	    if ($space eq 'map') {
                   12067: 	        my ($map) = &decode_symb($symbparm);
                   12068: 	        return &symbread($map);
                   12069: 	    }
                   12070:             if ($space eq 'maptitle') {
                   12071:                 my ($map) = &decode_symb($symbparm);
                   12072:                 return &gettitle($map);
                   12073:             }
                   12074: 	    if ($space eq 'filename') {
                   12075: 	        if ($symbparm) {
                   12076: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12077: 	        }
                   12078: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12079: 	    }
1.1172.2.30  raeburn  12080: 
                   12081:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12082:                 if ($space eq 'visibleparts') {
                   12083:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12084:                     my $item;
                   12085:                     if (ref($navmap)) {
                   12086:                         my $res = $navmap->getBySymb($symbparm);
                   12087:                         my $parts = $res->parts();
                   12088:                         if (ref($parts) eq 'ARRAY') {
                   12089:                             $item = join(',',@{$parts});
                   12090:                         }
                   12091:                         undef($navmap);
                   12092:                     }
                   12093:                     return $item;
                   12094:                 }
                   12095:             }
                   12096:         }
1.693     albertel 12097: 
                   12098: 	my ($section, $group, @groups);
1.593     albertel 12099: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12100:         if (($courseid eq '') && ($cid)) {
                   12101:             $courseid = $cid;
                   12102:         }
                   12103: 	if (($symbparm && $courseid) && 
                   12104: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12105: 
1.218     albertel 12106: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12107: 
1.60      www      12108: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12109: 	    my $symbp=$symbparm;
1.735     albertel 12110: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12111: 
                   12112: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12113: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12114: 
1.620     albertel 12115: 	    if (($env{'user.name'} eq $uname) &&
                   12116: 		($env{'user.domain'} eq $udom)) {
                   12117: 		$section=$env{'request.course.sec'};
1.733     raeburn  12118:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12119:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12120: 	    } else {
1.539     albertel 12121: 		if (! defined($usection)) {
1.551     albertel 12122: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12123: 		} else {
                   12124: 		    $section = $usection;
                   12125: 		}
1.733     raeburn  12126:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12127: 	    }
                   12128: 
                   12129: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12130: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12131: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12132: 
1.593     albertel 12133: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12134: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12135: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12136: 
1.60      www      12137: # ----------------------------------------------------------- first, check user
1.624     albertel 12138: 
                   12139: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12140: 				       ([$courselevelr,'resource'],
                   12141: 					[$courselevelm,'map'     ],
                   12142: 					[$courselevel, 'course'  ]));
1.931     albertel 12143: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12144: 
1.594     albertel 12145: # ------------------------------------------------ second, check some of course
1.684     raeburn  12146:             my $coursereply;
1.691     raeburn  12147:             if (@groups > 0) {
                   12148:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12149:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12150:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12151:             }
1.96      www      12152: 
1.684     raeburn  12153: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12154: 				  $env{'course.'.$courseid.'.domain'},
                   12155: 				  'course',
                   12156: 				  ([$seclevelr,   'resource'],
                   12157: 				   [$seclevelm,   'map'     ],
                   12158: 				   [$seclevel,    'course'  ],
                   12159: 				   [$courselevelr,'resource']));
                   12160: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12161: 
1.60      www      12162: # ------------------------------------------------------ third, check map parms
1.218     albertel 12163: 	    my %parmhash=();
                   12164: 	    my $thisparm='';
                   12165: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12166: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12167: 		    &GDBM_READER(),0640)) {
1.218     albertel 12168: 		$thisparm=$parmhash{$symbparm};
                   12169: 		untie(%parmhash);
                   12170: 	    }
1.927     albertel 12171: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12172: 	}
1.594     albertel 12173: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12174: 
1.218     albertel 12175: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12176: 	my $filename;
                   12177: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12178: 	if ($symbparm) {
1.409     www      12179: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12180: 	} else {
1.620     albertel 12181: 	    $filename=$env{'request.filename'};
1.282     albertel 12182: 	}
                   12183: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12184: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12185: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12186: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12187: 
1.927     albertel 12188: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12189: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12190: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12191: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12192: 				     $env{'course.'.$courseid.'.domain'},
                   12193: 				     'course',
1.927     albertel 12194: 				     ([$courselevelm,'map'   ],
                   12195: 				      [$courselevel, 'course']));
                   12196: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12197: 	}
1.145     www      12198: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12199: 	unless ($space eq '0') {
1.336     albertel 12200: 	    my @parts=split(/_/,$space);
                   12201: 	    my $id=pop(@parts);
                   12202: 	    my $part=join('_',@parts);
                   12203: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12204: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12205: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12206: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12207: 	}
1.395     albertel 12208: 	if ($recurse) { return undef; }
                   12209: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12210: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12211: # ---------------------------------------------------- Any other user namespace
                   12212:     } elsif ($realm eq 'environment') {
                   12213: # ----------------------------------------------------------------- environment
1.620     albertel 12214: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12215: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12216: 	} else {
1.770     albertel 12217: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12218: 		return '';
                   12219: 	    }
1.219     albertel 12220: 	    my %returnhash=&userenvironment($udom,$uname,
                   12221: 					    $spacequalifierrest);
                   12222: 	    return $returnhash{$spacequalifierrest};
                   12223: 	}
1.28      www      12224:     } elsif ($realm eq 'system') {
1.48      www      12225: # ----------------------------------------------------------------- system.time
                   12226: 	if ($space eq 'time') {
                   12227: 	    return time;
                   12228:         }
1.696     albertel 12229:     } elsif ($realm eq 'server') {
                   12230: # ----------------------------------------------------------------- system.time
                   12231: 	if ($space eq 'name') {
                   12232: 	    return $ENV{'SERVER_NAME'};
                   12233:         }
1.1172.2.146.  .1(raebu 12234:22):     } elsif ($realm eq 'client') {
                   12235:22):         if ($space eq 'remote_addr') {
                   12236:22):             return &get_requestor_ip();
                   12237:22):         }
1.28      www      12238:     }
1.48      www      12239:     return '';
1.61      www      12240: }
                   12241: 
1.927     albertel 12242: sub get_reply {
                   12243:     my ($reply_value) = @_;
1.940     raeburn  12244:     if (ref($reply_value) eq 'ARRAY') {
                   12245:         if (wantarray) {
                   12246: 	    return @$reply_value;
                   12247:         }
                   12248:         return $reply_value->[0];
                   12249:     } else {
                   12250:         return $reply_value;
1.927     albertel 12251:     }
                   12252: }
                   12253: 
1.691     raeburn  12254: sub check_group_parms {
                   12255:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12256:     my @groupitems = ();
                   12257:     my $resultitem;
1.927     albertel 12258:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12259:     foreach my $group (@{$groups}) {
                   12260:         foreach my $level (@levels) {
1.927     albertel 12261:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12262:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12263:         }
                   12264:     }
                   12265:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12266:                             $env{'course.'.$courseid.'.domain'},
                   12267:                                      'course',@groupitems);
                   12268:     return $coursereply;
                   12269: }
                   12270: 
1.1172.2.146.  .1(raebu 12271:22): sub get_map_hierarchy {
                   12272:22):     my ($mapname,$courseid) = @_;
                   12273:22):     my @recurseup = ();
                   12274:22):     if ($mapname) {
                   12275:22):         if (($cachedmapkey eq $courseid) &&
                   12276:22):             (abs($cachedmaptime-time)<5)) {
                   12277:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12278:22):                 return @{$cachedmaps{$mapname}};
                   12279:22):             }
                   12280:22):         }
                   12281:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12282:22):         if (ref($navmap)) {
                   12283:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12284:22):             undef($navmap);
                   12285:22):             $cachedmaps{$mapname} = \@recurseup;
                   12286:22):             $cachedmaptime=time;
                   12287:22):             $cachedmapkey=$courseid;
                   12288:22):         }
                   12289:22):     }
                   12290:22):     return @recurseup;
                   12291:22): }
                   12292:22): 
          .2(raebu 12293:22): }
          .1(raebu 12294:22): 
1.691     raeburn  12295: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12296:     my ($courseid,@groups) = @_;
                   12297:     @groups = sort(@groups);
1.691     raeburn  12298:     return @groups;
                   12299: }
                   12300: 
1.395     albertel 12301: sub packages_tab_default {
                   12302:     my ($uri,$varname)=@_;
                   12303:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12304: 
                   12305:     my (@extension,@specifics,$do_default);
                   12306:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12307: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12308: 	if ($pack_type eq 'default') {
                   12309: 	    $do_default=1;
                   12310: 	} elsif ($pack_type eq 'extension') {
                   12311: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12312: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12313: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12314: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12315: 	}
                   12316:     }
                   12317:     # first look for a package that matches the requested part id
                   12318:     foreach my $package (@specifics) {
                   12319: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12320: 	next if ($pack_part ne $part);
                   12321: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12322: 	    return $packagetab{"$pack_type&$name&default"};
                   12323: 	}
                   12324:     }
                   12325:     # look for any possible matching non extension_ package
                   12326:     foreach my $package (@specifics) {
                   12327: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12328: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12329: 	    return $packagetab{"$pack_type&$name&default"};
                   12330: 	}
1.585     albertel 12331: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12332: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12333: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12334: 	}
                   12335:     }
1.738     albertel 12336:     # look for any posible extension_ match
                   12337:     foreach my $package (@extension) {
                   12338: 	my ($package,$pack_type)=@{$package};
                   12339: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12340: 	    return $packagetab{"$pack_type&$name&default"};
                   12341: 	}
                   12342: 	if (defined($packagetab{$package."&$name&default"})) {
                   12343: 	    return $packagetab{$package."&$name&default"};
                   12344: 	}
                   12345:     }
                   12346:     # look for a global default setting
                   12347:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12348: 	return $packagetab{"default&$name&default"};
                   12349:     }
1.395     albertel 12350:     return undef;
                   12351: }
                   12352: 
1.334     albertel 12353: sub add_prefix_and_part {
                   12354:     my ($prefix,$part)=@_;
                   12355:     my $keyroot;
                   12356:     if (defined($prefix) && $prefix !~ /^__/) {
                   12357: 	# prefix that has a part already
                   12358: 	$keyroot=$prefix;
                   12359:     } elsif (defined($prefix)) {
                   12360: 	# prefix that is missing a part
                   12361: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12362:     } else {
                   12363: 	# no prefix at all
                   12364: 	if (defined($part)) { $keyroot='_'.$part; }
                   12365:     }
                   12366:     return $keyroot;
                   12367: }
                   12368: 
1.71      www      12369: # ---------------------------------------------------------------- Get metadata
                   12370: 
1.599     albertel 12371: my %metaentry;
1.1070    www      12372: my %importedpartids;
1.1172.2.99  raeburn  12373: my %importedrespids;
1.71      www      12374: sub metadata {
1.176     www      12375:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12376:     $uri=&declutter($uri);
1.288     albertel 12377:     # if it is a non metadata possible uri return quickly
1.529     albertel 12378:     if (($uri eq '') || 
                   12379: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12380:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12381:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12382: 	return undef;
                   12383:     }
1.1172.2.49  raeburn  12384:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12385: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12386: 	return undef;
1.288     albertel 12387:     }
1.73      www      12388:     my $filename=$uri;
                   12389:     $uri=~s/\.meta$//;
1.172     www      12390: #
                   12391: # Is the metadata already cached?
1.177     www      12392: # Look at timestamp of caching
1.172     www      12393: # Everything is cached by the main uri, libraries are never directly cached
                   12394: #
1.428     albertel 12395:     if (!defined($liburi)) {
1.599     albertel 12396: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12397: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12398:     }
                   12399:     {
1.1069    www      12400: # Imported parts would go here
1.1172.2.99  raeburn  12401:         my @origfiletagids=();
1.1069    www      12402:         my $importedparts=0;
1.1172.2.99  raeburn  12403: 
                   12404: # Imported responseids would go here
                   12405:         my $importedresponses=0;
1.172     www      12406: #
                   12407: # Is this a recursive call for a library?
                   12408: #
1.599     albertel 12409: #	if (! exists($metacache{$uri})) {
                   12410: #	    $metacache{$uri}={};
                   12411: #	}
1.924     albertel 12412: 	my $cachetime = 60*60;
1.171     www      12413:         if ($liburi) {
                   12414: 	    $liburi=&declutter($liburi);
                   12415:             $filename=$liburi;
1.401     bowersj2 12416:         } else {
1.599     albertel 12417: 	    &devalidate_cache_new('meta',$uri);
                   12418: 	    undef(%metaentry);
1.401     bowersj2 12419: 	}
1.140     www      12420:         my %metathesekeys=();
1.73      www      12421:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12422: 	my $metastring;
1.1140    www      12423: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12424: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12425: 	    $metastring = 
1.929     albertel 12426: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12427: 					  ('grade_target' => 'meta'));
                   12428: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12429: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12430:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12431: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12432: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12433: 	    $metastring=&getfile($file);
1.489     albertel 12434: 	}
1.208     albertel 12435:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12436:         my $token;
1.140     www      12437:         undef %metathesekeys;
1.71      www      12438:         while ($token=$parser->get_token) {
1.339     albertel 12439: 	    if ($token->[0] eq 'S') {
                   12440: 		if (defined($token->[2]->{'package'})) {
1.172     www      12441: #
                   12442: # This is a package - get package info
                   12443: #
1.339     albertel 12444: 		    my $package=$token->[2]->{'package'};
                   12445: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12446: 		    if (defined($token->[2]->{'id'})) { 
                   12447: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12448: 		    }
1.599     albertel 12449: 		    if ($metaentry{':packages'}) {
                   12450: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12451: 		    } else {
1.599     albertel 12452: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12453: 		    }
1.736     albertel 12454: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12455: 			my $part=$keyroot;
                   12456: 			$part=~s/^\_//;
1.736     albertel 12457: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12458: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12459: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12460: 			    # ignore package.tab specified default values
                   12461:                             # here &package_tab_default() will fetch those
                   12462: 			    if ($subp eq 'default') { next; }
1.736     albertel 12463: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12464: 			    my $unikey;
                   12465: 			    if ($pack =~ /_0$/) {
                   12466: 				$unikey='parameter_0_'.$name;
                   12467: 				$part=0;
                   12468: 			    } else {
                   12469: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12470: 			    }
1.339     albertel 12471: 			    if ($subp eq 'display') {
                   12472: 				$value.=' [Part: '.$part.']';
                   12473: 			    }
1.599     albertel 12474: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12475: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12476: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12477: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12478: 			    }
1.599     albertel 12479: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12480: 				$metaentry{':'.$unikey}=
                   12481: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12482: 			    }
1.339     albertel 12483: 			}
                   12484: 		    }
                   12485: 		} else {
1.172     www      12486: #
                   12487: # This is not a package - some other kind of start tag
1.339     albertel 12488: #
                   12489: 		    my $entry=$token->[1];
1.1068    www      12490: 		    my $unikey='';
1.175     www      12491: 
1.339     albertel 12492: 		    if ($entry eq 'import') {
1.175     www      12493: #
                   12494: # Importing a library here
1.339     albertel 12495: #
1.1067    www      12496:                         my $location=$parser->get_text('/import');
                   12497:                         my $dir=$filename;
                   12498:                         $dir=~s|[^/]*$||;
                   12499:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12500: 
                   12501:                         my $importid=$token->[2]->{'id'};
1.1068    www      12502:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12503: #
                   12504: # Check metadata for imported file to
                   12505: # see if it contained response items
                   12506: #
                   12507:                         my %currmetaentry = %metaentry;
                   12508:                         my $libresponseorder = &metadata($location,'responseorder');
                   12509:                         my $origfile;
                   12510:                         if ($libresponseorder ne '') {
                   12511:                             if ($#origfiletagids<0) {
                   12512:                                 undef(%importedrespids);
                   12513:                                 undef(%importedpartids);
                   12514:                             }
                   12515:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12516:                             if (@{$importedrespids{$importid}} > 0) {
                   12517:                                 $importedresponses = 1;
                   12518: # We need to get the original file and the imported file to get the response order correct
                   12519: # Load and inspect original file
                   12520:                                 if ($#origfiletagids<0) {
                   12521:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12522:                                     $origfile=&getfile($origfilelocation);
                   12523:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12524:                                 }
                   12525:                             }
                   12526:                         }
                   12527: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12528: # hash populated for imported library file
                   12529:                         %metaentry = %currmetaentry;
                   12530:                         undef(%currmetaentry);
1.1068    www      12531:                         if ($importmode eq 'problem') {
1.1069    www      12532: # Import as problem/response
1.1068    www      12533:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12534:                         } elsif ($importmode eq 'part') {
                   12535: # Import as part(s)
1.1069    www      12536:                            $importedparts=1;
                   12537: # We need to get the original file and the imported file to get the part order correct
                   12538: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12539: # Load and inspect original file if we didn't do that already
                   12540:                            if ($#origfiletagids<0) {
                   12541:                                undef(%importedrespids);
                   12542:                                undef(%importedpartids);
                   12543:                                if ($origfile eq '') {
                   12544:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12545:                                    $origfile=&getfile($origfilelocation);
                   12546:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12547:                                }
1.1070    www      12548:                            }
                   12549: 
1.1069    www      12550: # Load and inspect imported file
                   12551:                            my $impfile=&getfile($location);
                   12552:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12553:                            if ($#impfilepartids>=0) {
                   12554: # This problem had parts
1.1070    www      12555:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12556:                            } else {
                   12557: # Importing by turning a single problem into a problem part
                   12558: # It gets the import-tags ID as part-ID
                   12559:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12560:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12561:                            }
1.1068    www      12562:                         } else {
                   12563: # Normal import
                   12564:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12565:                            if (defined($token->[2]->{'id'})) {
                   12566:                               $unikey.='_'.$token->[2]->{'id'};
                   12567:                            }
1.1067    www      12568:                         }
                   12569: 
1.339     albertel 12570: 			if ($depthcount<20) {
1.736     albertel 12571: 			    my $metadata = 
                   12572: 				&metadata($uri,'keys', $location,$unikey,
                   12573: 					  $depthcount+1);
                   12574: 			    foreach my $meta (split(',',$metadata)) {
                   12575: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12576: 				$metathesekeys{$meta}=1;
1.339     albertel 12577: 			    }
1.1068    www      12578: 			
                   12579:                         }
1.1067    www      12580: 		    } else {
                   12581: #
                   12582: # Not importing, some other kind of non-package, non-library start tag
                   12583: # 
                   12584:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12585:                         if (defined($token->[2]->{'id'})) {
                   12586:                             $unikey.='_'.$token->[2]->{'id'};
                   12587:                         }
1.339     albertel 12588: 			if (defined($token->[2]->{'name'})) { 
                   12589: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12590: 			}
                   12591: 			$metathesekeys{$unikey}=1;
1.736     albertel 12592: 			foreach my $param (@{$token->[3]}) {
                   12593: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12594: 				$token->[2]->{$param};
1.339     albertel 12595: 			}
                   12596: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12597: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12598: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12599: 		 # only ws inside the tag, and not in default, so use default
                   12600: 		 # as value
1.599     albertel 12601: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12602: 			} elsif ( $internaltext =~ /\S/ ) {
                   12603: 		  # something interesting inside the tag
                   12604: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12605: 			} else {
1.908     albertel 12606: 		  # no interesting values, don't set a default
1.339     albertel 12607: 			}
1.172     www      12608: # end of not-a-package not-a-library import
1.339     albertel 12609: 		    }
1.172     www      12610: # end of not-a-package start tag
1.339     albertel 12611: 		}
1.172     www      12612: # the next is the end of "start tag"
1.339     albertel 12613: 	    }
                   12614: 	}
1.483     albertel 12615: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12616: 	$extension = lc($extension);
                   12617: 	if ($extension eq 'htm') { $extension='html'; }
                   12618: 
1.737     albertel 12619: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12620: 	    #no specific packages #how's our extension
                   12621: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12622: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12623: 					 \%metathesekeys);
                   12624: 	}
1.883     albertel 12625: 
                   12626: 	if (!exists($metaentry{':packages'})
                   12627: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12628: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12629: 		#no specific packages well let's get default then
                   12630: 		if ($key!~/^default&/) { next; }
1.488     albertel 12631: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12632: 					     \%metathesekeys);
                   12633: 	    }
                   12634: 	}
1.338     www      12635: # are there custom rights to evaluate
1.599     albertel 12636: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12637: 
1.338     www      12638:     #
                   12639:     # Importing a rights file here
1.339     albertel 12640:     #
                   12641: 	    unless ($depthcount) {
1.599     albertel 12642: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12643: 		my $dir=$filename;
                   12644: 		$dir=~s|[^/]*$||;
                   12645: 		$location=&filelocation($dir,$location);
1.736     albertel 12646: 		my $rights_metadata =
                   12647: 		    &metadata($uri,'keys',$location,'_rights',
                   12648: 			      $depthcount+1);
                   12649: 		foreach my $rights (split(',',$rights_metadata)) {
                   12650: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12651: 		    $metathesekeys{$rights}=1;
1.339     albertel 12652: 		}
                   12653: 	    }
                   12654: 	}
1.737     albertel 12655: 	# uniqifiy package listing
                   12656: 	my %seen;
                   12657: 	my @uniq_packages =
                   12658: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12659: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12660: 
1.1172.2.99  raeburn  12661:         if (($importedresponses) || ($importedparts)) {
                   12662:             if ($importedparts) {
1.1070    www      12663: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12664:                 $metaentry{':partorder'}='';
                   12665:                 $metathesekeys{'partorder'}=1;
                   12666:             }
                   12667:             if ($importedresponses) {
                   12668: # We had imported responses and need to rebuild responseorder
                   12669:                 $metaentry{':responseorder'}='';
                   12670:                 $metathesekeys{'responseorder'}=1;
                   12671:             }
                   12672:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12673:                 my $origid = $origfiletagids[$index+1];
                   12674:                 if ($origfiletagids[$index] eq 'part') {
                   12675: # Original part, part of the problem
                   12676:                     if ($importedparts) {
                   12677:                         $metaentry{':partorder'}.=','.$origid;
                   12678:                     }
                   12679:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12680:                     if ($importedparts) {
                   12681: # We have imported parts at this position
                   12682:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12683:                     }
                   12684:                     if ($importedresponses) {
                   12685: # We have imported responses at this position
                   12686:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12687:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12688:                         }
                   12689:                     }
                   12690:                 } else {
                   12691: # Original response item, part of the problem
                   12692:                     if ($importedresponses) {
                   12693:                         $metaentry{':responseorder'}.=','.$origid;
                   12694:                     }
                   12695:                 }
                   12696:             }
                   12697:             if ($importedparts) {
                   12698:                 $metaentry{':partorder'}=~s/^\,//;
                   12699:             }
                   12700:             if ($importedresponses) {
                   12701:                 $metaentry{':responseorder'}=~s/^\,//;
                   12702:             }
1.1070    www      12703:         }
                   12704: 
1.737     albertel 12705: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12706: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12707: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12708: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12709: # this is the end of "was not already recently cached
1.71      www      12710:     }
1.599     albertel 12711:     return $metaentry{':'.$what};
1.261     albertel 12712: }
                   12713: 
1.488     albertel 12714: sub metadata_create_package_def {
1.483     albertel 12715:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12716:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12717:     if ($subp eq 'default') { next; }
                   12718:     
1.599     albertel 12719:     if (defined($metaentry{':packages'})) {
                   12720: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12721:     } else {
1.599     albertel 12722: 	$metaentry{':packages'}=$package;
1.483     albertel 12723:     }
                   12724:     my $value=$packagetab{$key};
                   12725:     my $unikey;
                   12726:     $unikey='parameter_0_'.$name;
1.599     albertel 12727:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12728:     $$metathesekeys{$unikey}=1;
1.599     albertel 12729:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12730: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12731:     }
1.599     albertel 12732:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12733: 	$metaentry{':'.$unikey}=
                   12734: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12735:     }
                   12736: }
                   12737: 
1.261     albertel 12738: sub metadata_generate_part0 {
                   12739:     my ($metadata,$metacache,$uri) = @_;
                   12740:     my %allnames;
1.737     albertel 12741:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12742: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12743: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12744: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12745: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12746: 	    $allnames{$name}=$part;
                   12747: 	  }
                   12748: 	}
                   12749:     }
                   12750:     foreach my $name (keys(%allnames)) {
                   12751:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12752:       my $key=":parameter_0_$name";
1.261     albertel 12753:       $$metacache{"$key.part"}='0';
                   12754:       $$metacache{"$key.name"}=$name;
1.428     albertel 12755:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12756: 					   $allnames{$name}.'_'.$name.
                   12757: 					   '.type'};
1.428     albertel 12758:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12759: 			     '.display'};
1.644     www      12760:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12761:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12762:       $$metacache{"$key.display"}=$olddis;
                   12763:     }
1.71      www      12764: }
                   12765: 
1.764     albertel 12766: # ------------------------------------------------------ Devalidate title cache
                   12767: 
                   12768: sub devalidate_title_cache {
                   12769:     my ($url)=@_;
                   12770:     if (!$env{'request.course.id'}) { return; }
                   12771:     my $symb=&symbread($url);
                   12772:     if (!$symb) { return; }
                   12773:     my $key=$env{'request.course.id'}."\0".$symb;
                   12774:     &devalidate_cache_new('title',$key);
                   12775: }
                   12776: 
1.1014    droeschl 12777: # ------------------------------------------------- Get the title of a course
                   12778: 
                   12779: sub current_course_title {
                   12780:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12781: }
1.301     www      12782: # ------------------------------------------------- Get the title of a resource
                   12783: 
                   12784: sub gettitle {
                   12785:     my $urlsymb=shift;
                   12786:     my $symb=&symbread($urlsymb);
1.534     albertel 12787:     if ($symb) {
1.620     albertel 12788: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12789: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12790: 	if (defined($cached)) { 
                   12791: 	    return $result;
                   12792: 	}
1.534     albertel 12793: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12794: 	my $title='';
1.907     albertel 12795: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12796: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12797: 	} else {
                   12798: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12799: 		    &GDBM_READER(),0640)) {
                   12800: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12801: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12802: 		untie(%bighash);
                   12803: 	    }
1.534     albertel 12804: 	}
                   12805: 	$title=~s/\&colon\;/\:/gs;
                   12806: 	if ($title) {
1.1159    www      12807: # Remember both $symb and $title for dynamic metadata
                   12808:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12809:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12810: # Cache this title and then return it
1.599     albertel 12811: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12812: 	}
                   12813: 	$urlsymb=$url;
                   12814:     }
                   12815:     my $title=&metadata($urlsymb,'title');
                   12816:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12817:     return $title;
1.301     www      12818: }
1.613     albertel 12819: 
1.614     albertel 12820: sub get_slot {
                   12821:     my ($which,$cnum,$cdom)=@_;
                   12822:     if (!$cnum || !$cdom) {
1.790     albertel 12823: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12824: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12825: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12826:     }
1.703     albertel 12827:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12828:     my %slotinfo;
                   12829:     if (exists($remembered{$key})) {
                   12830: 	$slotinfo{$which} = $remembered{$key};
                   12831:     } else {
                   12832: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12833: 	&Apache::lonhomework::showhash(%slotinfo);
                   12834: 	my ($tmp)=keys(%slotinfo);
                   12835: 	if ($tmp=~/^error:/) { return (); }
                   12836: 	$remembered{$key} = $slotinfo{$which};
                   12837:     }
1.616     albertel 12838:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12839: 	return %{$slotinfo{$which}};
                   12840:     }
                   12841:     return $slotinfo{$which};
1.614     albertel 12842: }
1.1150    raeburn  12843: 
                   12844: sub get_reservable_slots {
                   12845:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12846:     my $now = time;
                   12847:     my $reservable_info;
                   12848:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12849:     if (exists($remembered{$key})) {
                   12850:         $reservable_info = $remembered{$key};
                   12851:     } else {
                   12852:         my %resv;
                   12853:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12854:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12855:         $reservable_info = \%resv;
                   12856:         $remembered{$key} = $reservable_info;
                   12857:     }
                   12858:     return $reservable_info;
                   12859: }
                   12860: 
                   12861: sub get_course_slots {
                   12862:     my ($cnum,$cdom) = @_;
                   12863:     my $hashid=$cnum.':'.$cdom;
                   12864:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12865:     if (defined($cached)) {
                   12866:         if (ref($result) eq 'HASH') {
                   12867:             return %{$result};
                   12868:         }
                   12869:     } else {
                   12870:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12871:         my ($tmp) = keys(%slots);
                   12872:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12873:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12874:             return %slots;
                   12875:         }
                   12876:     }
                   12877:     return;
                   12878: }
                   12879: 
                   12880: sub devalidate_slots_cache {
                   12881:     my ($cnum,$cdom)=@_;
                   12882:     my $hashid=$cnum.':'.$cdom;
                   12883:     &devalidate_cache_new('allslots',$hashid);
                   12884: }
                   12885: 
1.1172.2.8  raeburn  12886: sub get_coursechange {
                   12887:     my ($cdom,$cnum) = @_;
                   12888:     if ($cdom eq '' || $cnum eq '') {
                   12889:         return unless ($env{'request.course.id'});
                   12890:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12891:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12892:     }
                   12893:     my $hashid=$cdom.'_'.$cnum;
                   12894:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12895:     if ((defined($cached)) && ($change ne '')) {
                   12896:         return $change;
                   12897:     } else {
                   12898:         my %crshash;
                   12899:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12900:         if ($crshash{'internal.contentchange'} eq '') {
                   12901:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12902:             if ($change eq '') {
                   12903:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12904:                 $change = $crshash{'internal.created'};
                   12905:             }
                   12906:         } else {
                   12907:             $change = $crshash{'internal.contentchange'};
                   12908:         }
                   12909:         my $cachetime = 600;
                   12910:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12911:     }
                   12912:     return $change;
                   12913: }
                   12914: 
                   12915: sub devalidate_coursechange_cache {
                   12916:     my ($cnum,$cdom)=@_;
                   12917:     my $hashid=$cnum.':'.$cdom;
                   12918:     &devalidate_cache_new('crschange',$hashid);
                   12919: }
                   12920: 
1.31      www      12921: # ------------------------------------------------- Update symbolic store links
                   12922: 
                   12923: sub symblist {
                   12924:     my ($mapname,%newhash)=@_;
1.438     www      12925:     $mapname=&deversion(&declutter($mapname));
1.31      www      12926:     my %hash;
1.620     albertel 12927:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12928:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12929:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12930: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12931: 		next if ($url eq 'last_known'
                   12932: 			 && $env{'form.no_update_last_known'});
                   12933: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12934: 						    $newhash{$url}->[1],
                   12935: 						    $newhash{$url}->[0]);
1.191     harris41 12936:             }
1.31      www      12937:             if (untie(%hash)) {
                   12938: 		return 'ok';
                   12939:             }
                   12940:         }
                   12941:     }
                   12942:     return 'error';
1.212     www      12943: }
                   12944: 
                   12945: # --------------------------------------------------------------- Verify a symb
                   12946: 
                   12947: sub symbverify {
1.1172.2.11  raeburn  12948:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12949:     my $thisfn=$thisurl;
1.439     www      12950:     $thisfn=&declutter($thisfn);
1.215     www      12951: # direct jump to resource in page or to a sequence - will construct own symbs
                   12952:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12953: # check URL part
1.409     www      12954:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12955: 
1.431     www      12956:     unless ($url eq $thisfn) { return 0; }
1.213     www      12957: 
1.216     www      12958:     $symb=&symbclean($symb);
1.510     www      12959:     $thisurl=&deversion($thisurl);
1.439     www      12960:     $thisfn=&deversion($thisfn);
1.213     www      12961: 
                   12962:     my %bighash;
                   12963:     my $okay=0;
1.431     www      12964: 
1.620     albertel 12965:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12966:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12967:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12968:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12969:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12970:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12971:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12972:             }
                   12973:         }
                   12974:         my $ids;
1.1172.2.122  raeburn  12975:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12976:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12977:         } else {
                   12978:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12979:         }
1.1102    raeburn  12980:         unless ($ids) {
1.1172.2.13  raeburn  12981:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12982:             $ids=$bighash{$idkey};
1.216     www      12983:         }
                   12984:         if ($ids) {
                   12985: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12986:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12987:                 $symb =~ s/\?.+$//;
                   12988:             }
1.800     albertel 12989: 	    foreach my $id (split(/\,/,$ids)) {
                   12990: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12991:                if (
                   12992:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12993:    eq $symb) {
1.1172.2.11  raeburn  12994:                    if (ref($encstate)) {
                   12995:                        $$encstate = $bighash{'encrypted_'.$id};
                   12996:                    }
1.1172.2.13  raeburn  12997:                    if (($env{'request.role.adv'}) ||
                   12998:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12999:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13000:                        $okay=1;
                   13001:                        last;
                   13002:                    }
                   13003:                }
                   13004:            }
1.216     www      13005:         }
1.213     www      13006: 	untie(%bighash);
                   13007:     }
                   13008:     return $okay;
1.31      www      13009: }
                   13010: 
1.210     www      13011: # --------------------------------------------------------------- Clean-up symb
                   13012: 
                   13013: sub symbclean {
                   13014:     my $symb=shift;
1.568     albertel 13015:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13016: # remove version from map
                   13017:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13018: 
1.210     www      13019: # remove version from URL
                   13020:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13021: 
1.507     www      13022: # remove wrapper
                   13023: 
1.510     www      13024:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13025:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13026:     return $symb;
1.409     www      13027: }
                   13028: 
                   13029: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13030: 
                   13031: sub encode_symb {
                   13032:     my ($map,$resid,$url)=@_;
                   13033:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13034: }
1.409     www      13035: 
                   13036: sub decode_symb {
1.568     albertel 13037:     my $symb=shift;
                   13038:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13039:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13040:     return (&fixversion($map),$resid,&fixversion($url));
                   13041: }
                   13042: 
                   13043: sub fixversion {
                   13044:     my $fn=shift;
1.609     banghart 13045:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13046:     my %bighash;
                   13047:     my $uri=&clutter($fn);
1.620     albertel 13048:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13049: # is this cached?
1.599     albertel 13050:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13051:     if (defined($cached)) { return $result; }
                   13052: # unfortunately not cached, or expired
1.620     albertel 13053:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13054: 	    &GDBM_READER(),0640)) {
                   13055:  	if ($bighash{'version_'.$uri}) {
                   13056:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13057:  	    unless (($version eq 'mostrecent') || 
                   13058: 		    ($version==&getversion($uri))) {
1.440     www      13059:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13060:  	    }
                   13061:  	}
                   13062:  	untie %bighash;
1.413     www      13063:     }
1.599     albertel 13064:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13065: }
                   13066: 
                   13067: sub deversion {
                   13068:     my $url=shift;
                   13069:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13070:     return $url;
1.210     www      13071: }
                   13072: 
1.31      www      13073: # ------------------------------------------------------ Return symb list entry
                   13074: 
                   13075: sub symbread {
1.1172.2.126  raeburn  13076:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13077:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13078:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13079:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13080:         unless (ref($possibles) eq 'HASH') {
                   13081:             if ($ignorecachednull) {
                   13082:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13083:             } else {
                   13084:                 return $env{$cache_str};
                   13085:             }
1.1172.2.66  raeburn  13086:         }
                   13087:     }
1.242     www      13088: # no filename provided? try from environment
1.1172.2.54  raeburn  13089:     unless ($thisfn) {
1.620     albertel 13090:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13091:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13092:         }
                   13093:         $thisfn=$env{'request.filename'};
1.44      www      13094:     }
1.569     albertel 13095:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13096: # is that filename actually a symb? Verify, clean, and return
                   13097:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13098: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13099: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13100: 	}
1.242     www      13101:     }
1.44      www      13102:     $thisfn=declutter($thisfn);
1.31      www      13103:     my %hash;
1.37      www      13104:     my %bighash;
                   13105:     my $syval='';
1.620     albertel 13106:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13107:         my $targetfn = $thisfn;
1.609     banghart 13108:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13109:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13110:         }
1.687     albertel 13111: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13112: 	    $targetfn=$1;
                   13113: 	}
1.1172.2.128  raeburn  13114:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13115:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13116:                           &GDBM_READER(),0640)) {
                   13117: 	        $syval=$hash{$targetfn};
                   13118:                 untie(%hash);
                   13119:             }
1.1172.2.128  raeburn  13120:             if ($syval && $checkforblock) {
                   13121:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13122:                 if (@blockers) {
                   13123:                     $syval='';
                   13124:                 }
                   13125:             }
1.37      www      13126:         }
                   13127: # ---------------------------------------------------------- There was an entry
                   13128:         if ($syval) {
1.601     albertel 13129: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13130: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13131: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13132: 		    #return $env{$cache_str}='';
1.601     albertel 13133: 		#}    
                   13134: 		#$syval.=$1;
                   13135: 	    #}
1.37      www      13136:         } else {
                   13137: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13138:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13139:                             &GDBM_READER(),0640)) {
1.37      www      13140: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13141:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13142:               unless ($ids) { 
                   13143:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13144:               }
                   13145:               unless ($ids) {
                   13146: # alias?
                   13147: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13148:               }
1.37      www      13149:               if ($ids) {
                   13150: # ------------------------------------------------------------------- Has ID(s)
                   13151:                  my @possibilities=split(/\,/,$ids);
1.39      www      13152:                  if ($#possibilities==0) {
                   13153: # ----------------------------------------------- There is only one possibility
1.37      www      13154: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13155: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13156: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13157:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13158:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13159:                              $possibles->{$syval} = 1;
                   13160:                          }
1.1172.2.66  raeburn  13161:                      }
                   13162:                      if ($checkforblock) {
1.1172.2.126  raeburn  13163:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13164:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13165:                              if (@blockers) {
                   13166:                                  $syval = '';
                   13167:                                  untie(%bighash);
                   13168:                                  return $env{$cache_str}='';
                   13169:                              }
1.1172.2.66  raeburn  13170:                          }
                   13171:                      }
                   13172:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13173: # ------------------------------------------ There is more than one possibility
                   13174:                      my $realpossible=0;
1.800     albertel 13175:                      foreach my $id (@possibilities) {
                   13176: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13177:                          my $canaccess;
                   13178:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13179:                              $canaccess = 1;
                   13180:                          } else {
                   13181:                              $canaccess = &allowed('bre',$file);
                   13182:                          }
                   13183:                          if ($canaccess) {
                   13184:          		     my ($mapid,$resid)=split(/\./,$id);
                   13185:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13186:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13187:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13188:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13189:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13190:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13191:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13192:                                      if (@blockers > 0) {
                   13193:                                          $syval = '';
                   13194:                                      } else {
1.1172.2.66  raeburn  13195:                                          $syval = $poss_syval;
                   13196:                                          $realpossible++;
                   13197:                                      }
                   13198:                                  } else {
                   13199:                                      $syval = $poss_syval;
                   13200:                                      $realpossible++;
                   13201:                                  }
1.1172.2.126  raeburn  13202:                                  if ($syval) {
                   13203:                                      if (ref($possibles) eq 'HASH') {
                   13204:                                          $possibles->{$syval} = 1;
                   13205:                                      }
                   13206:                                  }
1.1172.2.66  raeburn  13207:                              }
1.39      www      13208: 			 }
1.191     harris41 13209:                      }
1.39      www      13210: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13211:                  } else {
                   13212:                      $syval='';
1.37      www      13213:                  }
                   13214: 	      }
1.1172.2.66  raeburn  13215:               untie(%bighash);
1.481     raeburn  13216:            }
1.31      www      13217:         }
1.62      www      13218:         if ($syval) {
1.1172.2.128  raeburn  13219: 	    return $env{$cache_str}=$syval;
1.62      www      13220:         }
1.31      www      13221:     }
1.949     raeburn  13222:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13223:     return $env{$cache_str}='';
1.31      www      13224: }
                   13225: 
                   13226: # ---------------------------------------------------------- Return random seed
                   13227: 
1.32      www      13228: sub numval {
                   13229:     my $txt=shift;
                   13230:     $txt=~tr/A-J/0-9/;
                   13231:     $txt=~tr/a-j/0-9/;
                   13232:     $txt=~tr/K-T/0-9/;
                   13233:     $txt=~tr/k-t/0-9/;
                   13234:     $txt=~tr/U-Z/0-5/;
                   13235:     $txt=~tr/u-z/0-5/;
                   13236:     $txt=~s/\D//g;
1.564     albertel 13237:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13238:     return int($txt);
1.368     albertel 13239: }
                   13240: 
1.484     albertel 13241: sub numval2 {
                   13242:     my $txt=shift;
                   13243:     $txt=~tr/A-J/0-9/;
                   13244:     $txt=~tr/a-j/0-9/;
                   13245:     $txt=~tr/K-T/0-9/;
                   13246:     $txt=~tr/k-t/0-9/;
                   13247:     $txt=~tr/U-Z/0-5/;
                   13248:     $txt=~tr/u-z/0-5/;
                   13249:     $txt=~s/\D//g;
                   13250:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13251:     my $total;
                   13252:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13253:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13254:     return int($total);
                   13255: }
                   13256: 
1.575     albertel 13257: sub numval3 {
                   13258:     use integer;
                   13259:     my $txt=shift;
                   13260:     $txt=~tr/A-J/0-9/;
                   13261:     $txt=~tr/a-j/0-9/;
                   13262:     $txt=~tr/K-T/0-9/;
                   13263:     $txt=~tr/k-t/0-9/;
                   13264:     $txt=~tr/U-Z/0-5/;
                   13265:     $txt=~tr/u-z/0-5/;
                   13266:     $txt=~s/\D//g;
                   13267:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13268:     my $total;
                   13269:     foreach my $val (@txts) { $total+=$val; }
                   13270:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13271:     return $total;
                   13272: }
                   13273: 
1.675     albertel 13274: sub digest {
                   13275:     my ($data)=@_;
                   13276:     my $digest=&Digest::MD5::md5($data);
                   13277:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13278:     my ($e,$f);
                   13279:     {
                   13280:         use integer;
                   13281:         $e=($a+$b);
                   13282:         $f=($c+$d);
                   13283:         if ($_64bit) {
                   13284:             $e=(($e<<32)>>32);
                   13285:             $f=(($f<<32)>>32);
                   13286:         }
                   13287:     }
                   13288:     if (wantarray) {
                   13289: 	return ($e,$f);
                   13290:     } else {
                   13291: 	my $g;
                   13292: 	{
                   13293: 	    use integer;
                   13294: 	    $g=($e+$f);
                   13295: 	    if ($_64bit) {
                   13296: 		$g=(($g<<32)>>32);
                   13297: 	    }
                   13298: 	}
                   13299: 	return $g;
                   13300:     }
                   13301: }
                   13302: 
1.368     albertel 13303: sub latest_rnd_algorithm_id {
1.675     albertel 13304:     return '64bit5';
1.366     albertel 13305: }
1.32      www      13306: 
1.503     albertel 13307: sub get_rand_alg {
                   13308:     my ($courseid)=@_;
1.790     albertel 13309:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13310:     if ($courseid) {
1.620     albertel 13311: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13312:     }
                   13313:     return &latest_rnd_algorithm_id();
                   13314: }
                   13315: 
1.562     albertel 13316: sub validCODE {
                   13317:     my ($CODE)=@_;
                   13318:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13319:     return 0;
                   13320: }
                   13321: 
1.491     albertel 13322: sub getCODE {
1.620     albertel 13323:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13324:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13325: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13326: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13327: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13328:     }
                   13329:     return undef;
                   13330: }
1.1133    foxr     13331: #
                   13332: #  Determines the random seed for a specific context:
                   13333: #
                   13334: # parameters:
                   13335: #   symb      - in course context the symb for the seed.
                   13336: #   course_id - The course id of the form domain_coursenum.
                   13337: #   domain    - Domain for the user.
                   13338: #   course    - Course for the user.
                   13339: #   cenv      - environment of the course.
                   13340: #
                   13341: # NOTE:
                   13342: #   All parameters are picked out of the environment if missing
                   13343: #   or not defined.
                   13344: #   If a symb cannot be determined the current time is used instead.
                   13345: #
                   13346: #  For a given well defined symb, courside, domain, username,
                   13347: #  and course environment, the seed is reproducible.
                   13348: #
1.31      www      13349: sub rndseed {
1.1133    foxr     13350:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13351:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13352:     if (!defined($symb)) {
1.366     albertel 13353: 	unless ($symb=$wsymb) { return time; }
                   13354:     }
1.1146    foxr     13355:     if (!defined $courseid) { 
                   13356: 	$courseid=$wcourseid; 
                   13357:     }
                   13358:     if (!defined $domain) { $domain=$wdomain; }
                   13359:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13360: 
                   13361:     my $which;
                   13362:     if (defined($cenv->{'rndseed'})) {
                   13363: 	$which = $cenv->{'rndseed'};
                   13364:     } else {
                   13365: 	$which =&get_rand_alg($courseid);
                   13366:     }
1.491     albertel 13367:     if (defined(&getCODE())) {
1.675     albertel 13368: 	if ($which eq '64bit5') {
                   13369: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13370: 	} elsif ($which eq '64bit4') {
1.575     albertel 13371: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13372: 	} else {
                   13373: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13374: 	}
1.675     albertel 13375:     } elsif ($which eq '64bit5') {
                   13376: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13377:     } elsif ($which eq '64bit4') {
                   13378: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13379:     } elsif ($which eq '64bit3') {
                   13380: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13381:     } elsif ($which eq '64bit2') {
                   13382: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13383:     } elsif ($which eq '64bit') {
                   13384: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13385:     }
                   13386:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13387: }
                   13388: 
                   13389: sub rndseed_32bit {
                   13390:     my ($symb,$courseid,$domain,$username)=@_;
                   13391:     {
                   13392: 	use integer;
                   13393: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13394: 	my $symbseed=numval($symb) << 22;
                   13395: 	my $namechck=unpack("%32C*",$username) << 17;
                   13396: 	my $nameseed=numval($username) << 12;
                   13397: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13398: 	my $courseseed=unpack("%32C*",$courseid);
                   13399: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13400: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13401: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13402: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13403: 	return $num;
                   13404:     }
                   13405: }
                   13406: 
                   13407: sub rndseed_64bit {
                   13408:     my ($symb,$courseid,$domain,$username)=@_;
                   13409:     {
                   13410: 	use integer;
                   13411: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13412: 	my $symbseed=numval($symb) << 10;
                   13413: 	my $namechck=unpack("%32S*",$username);
                   13414: 	
                   13415: 	my $nameseed=numval($username) << 21;
                   13416: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13417: 	my $courseseed=unpack("%32S*",$courseid);
                   13418: 	
                   13419: 	my $num1=$symbchck+$symbseed+$namechck;
                   13420: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13421: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13422: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13423: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13424: 	return "$num1,$num2";
1.155     albertel 13425:     }
1.366     albertel 13426: }
                   13427: 
1.443     albertel 13428: sub rndseed_64bit2 {
                   13429:     my ($symb,$courseid,$domain,$username)=@_;
                   13430:     {
                   13431: 	use integer;
                   13432: 	# strings need to be an even # of cahracters long, it it is odd the
                   13433:         # last characters gets thrown away
                   13434: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13435: 	my $symbseed=numval($symb) << 10;
                   13436: 	my $namechck=unpack("%32S*",$username.' ');
                   13437: 	
                   13438: 	my $nameseed=numval($username) << 21;
1.501     albertel 13439: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13440: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13441: 	
                   13442: 	my $num1=$symbchck+$symbseed+$namechck;
                   13443: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13444: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13445: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13446: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13447: 	return "$num1,$num2";
                   13448:     }
                   13449: }
                   13450: 
                   13451: sub rndseed_64bit3 {
                   13452:     my ($symb,$courseid,$domain,$username)=@_;
                   13453:     {
                   13454: 	use integer;
                   13455: 	# strings need to be an even # of cahracters long, it it is odd the
                   13456:         # last characters gets thrown away
                   13457: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13458: 	my $symbseed=numval2($symb) << 10;
                   13459: 	my $namechck=unpack("%32S*",$username.' ');
                   13460: 	
                   13461: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13462: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13463: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13464: 	
                   13465: 	my $num1=$symbchck+$symbseed+$namechck;
                   13466: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13467: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13468: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13469: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13470: 	
1.503     albertel 13471: 	return "$num1:$num2";
1.443     albertel 13472:     }
                   13473: }
                   13474: 
1.575     albertel 13475: sub rndseed_64bit4 {
                   13476:     my ($symb,$courseid,$domain,$username)=@_;
                   13477:     {
                   13478: 	use integer;
                   13479: 	# strings need to be an even # of cahracters long, it it is odd the
                   13480:         # last characters gets thrown away
                   13481: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13482: 	my $symbseed=numval3($symb) << 10;
                   13483: 	my $namechck=unpack("%32S*",$username.' ');
                   13484: 	
                   13485: 	my $nameseed=numval3($username) << 21;
                   13486: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13487: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13488: 	
                   13489: 	my $num1=$symbchck+$symbseed+$namechck;
                   13490: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13491: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13492: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13493: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13494: 	
1.575     albertel 13495: 	return "$num1:$num2";
                   13496:     }
                   13497: }
                   13498: 
1.675     albertel 13499: sub rndseed_64bit5 {
                   13500:     my ($symb,$courseid,$domain,$username)=@_;
                   13501:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13502:     return "$num1:$num2";
                   13503: }
                   13504: 
1.366     albertel 13505: sub rndseed_CODE_64bit {
                   13506:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13507:     {
1.366     albertel 13508: 	use integer;
1.443     albertel 13509: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13510: 	my $symbseed=numval2($symb);
1.491     albertel 13511: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13512: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13513: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13514: 	my $num1=$symbseed+$CODEchck;
                   13515: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13516: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13517: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13518: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13519: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13520: 	return "$num1:$num2";
1.366     albertel 13521:     }
                   13522: }
                   13523: 
1.575     albertel 13524: sub rndseed_CODE_64bit4 {
                   13525:     my ($symb,$courseid,$domain,$username)=@_;
                   13526:     {
                   13527: 	use integer;
                   13528: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13529: 	my $symbseed=numval3($symb);
                   13530: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13531: 	my $CODEseed=numval3(&getCODE());
                   13532: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13533: 	my $num1=$symbseed+$CODEchck;
                   13534: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13535: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13536: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13537: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13538: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13539: 	return "$num1:$num2";
                   13540:     }
                   13541: }
                   13542: 
1.675     albertel 13543: sub rndseed_CODE_64bit5 {
                   13544:     my ($symb,$courseid,$domain,$username)=@_;
                   13545:     my $code = &getCODE();
                   13546:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13547:     return "$num1:$num2";
                   13548: }
                   13549: 
1.366     albertel 13550: sub setup_random_from_rndseed {
                   13551:     my ($rndseed)=@_;
1.503     albertel 13552:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13553: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13554:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13555:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13556:         } else {
                   13557:             &Math::Random::random_set_seed($num1,$num2);
                   13558:         }
1.366     albertel 13559:     } else {
                   13560: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13561:     }
1.36      albertel 13562: }
                   13563: 
1.474     albertel 13564: sub latest_receipt_algorithm_id {
1.835     albertel 13565:     return 'receipt3';
1.474     albertel 13566: }
                   13567: 
1.480     www      13568: sub recunique {
                   13569:     my $fucourseid=shift;
                   13570:     my $unique;
1.835     albertel 13571:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13572: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13573: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13574:     } else {
                   13575: 	$unique=$perlvar{'lonReceipt'};
                   13576:     }
                   13577:     return unpack("%32C*",$unique);
                   13578: }
                   13579: 
                   13580: sub recprefix {
                   13581:     my $fucourseid=shift;
                   13582:     my $prefix;
1.835     albertel 13583:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13584: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13585: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13586:     } else {
                   13587: 	$prefix=$perlvar{'lonHostID'};
                   13588:     }
                   13589:     return unpack("%32C*",$prefix);
                   13590: }
                   13591: 
1.76      www      13592: sub ireceipt {
1.474     albertel 13593:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13594: 
                   13595:     my $return =&recprefix($fucourseid).'-';
                   13596: 
                   13597:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13598: 	$env{'request.state'} eq 'construct') {
                   13599: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13600: 	return $return;
                   13601:     }
                   13602: 
1.76      www      13603:     my $cuname=unpack("%32C*",$funame);
                   13604:     my $cudom=unpack("%32C*",$fudom);
                   13605:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13606:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13607:     my $cunique=&recunique($fucourseid);
1.474     albertel 13608:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13609:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13610: 
1.790     albertel 13611: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13612: 			       
                   13613: 	$return.= ($cunique%$cuname+
                   13614: 		   $cunique%$cudom+
                   13615: 		   $cusymb%$cuname+
                   13616: 		   $cusymb%$cudom+
                   13617: 		   $cucourseid%$cuname+
                   13618: 		   $cucourseid%$cudom+
                   13619: 		   $cpart%$cuname+
                   13620: 		   $cpart%$cudom);
                   13621:     } else {
                   13622: 	$return.= ($cunique%$cuname+
                   13623: 		   $cunique%$cudom+
                   13624: 		   $cusymb%$cuname+
                   13625: 		   $cusymb%$cudom+
                   13626: 		   $cucourseid%$cuname+
                   13627: 		   $cucourseid%$cudom);
                   13628:     }
                   13629:     return $return;
1.76      www      13630: }
                   13631: 
                   13632: sub receipt {
1.474     albertel 13633:     my ($part)=@_;
1.790     albertel 13634:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13635:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13636: }
1.260     ng       13637: 
1.790     albertel 13638: sub whichuser {
                   13639:     my ($passedsymb)=@_;
                   13640:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13641:     if (defined($env{'form.grade_symb'})) {
                   13642: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13643: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13644: 	if (!$allowed &&
                   13645: 	    exists($env{'request.course.sec'}) &&
                   13646: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13647: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13648: 			      '/'.$env{'request.course.sec'});
                   13649: 	}
                   13650: 	if ($allowed) {
                   13651: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13652: 	    $courseid=$tmp_courseid;
                   13653: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13654: 	    ($name)=&get_env_multiple('form.grade_username');
                   13655: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13656: 	}
                   13657:     }
                   13658:     if (!$passedsymb) {
                   13659: 	$symb=&symbread();
                   13660:     } else {
                   13661: 	$symb=$passedsymb;
                   13662:     }
                   13663:     $courseid=$env{'request.course.id'};
                   13664:     $domain=$env{'user.domain'};
                   13665:     $name=$env{'user.name'};
                   13666:     if ($name eq 'public' && $domain eq 'public') {
                   13667: 	if (!defined($env{'form.username'})) {
                   13668: 	    $env{'form.username'}.=time.rand(10000000);
                   13669: 	}
                   13670: 	$name.=$env{'form.username'};
                   13671:     }
                   13672:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13673: 
                   13674: }
                   13675: 
1.36      albertel 13676: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13677: # returns either the contents of the file or 
                   13678: # -1 if the file doesn't exist
1.481     raeburn  13679: #
                   13680: # if the target is a file that was uploaded via DOCS, 
                   13681: # a check will be made to see if a current copy exists on the local server,
                   13682: # if it does this will be served, otherwise a copy will be retrieved from
                   13683: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13684: # the local server.   
1.472     albertel 13685: 
1.36      albertel 13686: sub getfile {
1.538     albertel 13687:     my ($file) = @_;
1.609     banghart 13688:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13689:     &repcopy($file);
                   13690:     return &readfile($file);
                   13691: }
                   13692: 
                   13693: sub repcopy_userfile {
                   13694:     my ($file)=@_;
1.1142    raeburn  13695:     my $londocroot = $perlvar{'lonDocRoot'};
                   13696:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13697:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13698:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13699: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13700:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13701:     if (-e "$file") {
1.828     www      13702: # we already have a local copy, check it out
1.538     albertel 13703: 	my @fileinfo = stat($file);
1.828     www      13704: 	my $rtncode;
                   13705: 	my $info;
1.538     albertel 13706: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13707: 	if ($lwpresp ne 'ok') {
1.828     www      13708: # there is no such file anymore, even though we had a local copy
1.482     albertel 13709: 	    if ($rtncode eq '404') {
1.538     albertel 13710: 		unlink($file);
1.482     albertel 13711: 	    }
                   13712: 	    return -1;
                   13713: 	}
                   13714: 	if ($info < $fileinfo[9]) {
1.828     www      13715: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13716: 	    return 'ok';
1.828     www      13717: 	} else {
                   13718: # the file is outdated, get rid of it
                   13719: 	    unlink($file);
1.482     albertel 13720: 	}
1.828     www      13721:     }
                   13722: # one way or the other, at this point, we don't have the file
                   13723: # construct the correct path for the file
                   13724:     my @parts = ($cdom,$cnum); 
                   13725:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13726: 	push @parts, split(/\//,$1);
                   13727:     }
                   13728:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13729:     foreach my $part (@parts) {
                   13730: 	$path .= '/'.$part;
                   13731: 	if (!-e $path) {
                   13732: 	    mkdir($path,0770);
1.482     albertel 13733: 	}
                   13734:     }
1.828     www      13735: # now the path exists for sure
                   13736: # get a user agent
                   13737:     my $ua=new LWP::UserAgent;
                   13738:     my $transferfile=$file.'.in.transfer';
                   13739: # FIXME: this should flock
                   13740:     if (-e $transferfile) { return 'ok'; }
                   13741:     my $request;
                   13742:     $uri=~s/^\///;
1.980     raeburn  13743:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13744:     my $hostname = &hostname($homeserver);
1.980     raeburn  13745:     my $protocol = $protocol{$homeserver};
                   13746:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13747:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13748:     my $response=$ua->request($request,$transferfile);
                   13749: # did it work?
                   13750:     if ($response->is_error()) {
                   13751: 	unlink($transferfile);
                   13752: 	&logthis("Userfile repcopy failed for $uri");
                   13753: 	return -1;
                   13754:     }
                   13755: # worked, rename the transfer file
                   13756:     rename($transferfile,$file);
1.607     raeburn  13757:     return 'ok';
1.481     raeburn  13758: }
                   13759: 
1.517     albertel 13760: sub tokenwrapper {
                   13761:     my $uri=shift;
1.980     raeburn  13762:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13763:     $uri=~s|^/||;
1.620     albertel 13764:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13765:     my $token=$1;
1.552     albertel 13766:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13767:     if ($udom && $uname && $file) {
                   13768: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13769:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13770:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13771:         my $hostname = &hostname($homeserver);
1.980     raeburn  13772:         my $protocol = $protocol{$homeserver};
                   13773:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13774:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13775:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13776:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13777:     } else {
                   13778:         return '/adm/notfound.html';
                   13779:     }
                   13780: }
                   13781: 
1.828     www      13782: # call with reqtype HEAD: get last modification time
                   13783: # call with reqtype GET: get the file contents
                   13784: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13785: #
1.481     raeburn  13786: sub getuploaded {
                   13787:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13788:     $uri=~s/^\///;
1.980     raeburn  13789:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13790:     my $hostname = &hostname($homeserver);
1.980     raeburn  13791:     my $protocol = $protocol{$homeserver};
                   13792:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13793:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13794:     my $ua=new LWP::UserAgent;
                   13795:     my $request=new HTTP::Request($reqtype,$uri);
                   13796:     my $response=$ua->request($request);
                   13797:     $$rtncode = $response->code;
1.482     albertel 13798:     if (! $response->is_success()) {
                   13799: 	return 'failed';
                   13800:     }      
                   13801:     if ($reqtype eq 'HEAD') {
1.486     www      13802: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13803:     } elsif ($reqtype eq 'GET') {
                   13804: 	$$info = $response->content;
1.472     albertel 13805:     }
1.482     albertel 13806:     return 'ok';
1.36      albertel 13807: }
                   13808: 
1.481     raeburn  13809: sub readfile {
                   13810:     my $file = shift;
                   13811:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13812:     my $fh;
1.1172.2.96  raeburn  13813:     open($fh,"<",$file);
1.481     raeburn  13814:     my $a='';
1.800     albertel 13815:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13816:     return $a;
                   13817: }
                   13818: 
1.36      albertel 13819: sub filelocation {
1.590     banghart 13820:     my ($dir,$file) = @_;
                   13821:     my $location;
                   13822:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13823: 
                   13824:     if ($file =~ m-^/adm/-) {
                   13825: 	$file=~s-^/adm/wrapper/-/-;
                   13826: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13827:     }
1.882     albertel 13828: 
1.1139    www      13829:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13830:         $location = $file;
1.609     banghart 13831:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13832:         my ($udom,$uname,$filename)=
1.811     albertel 13833:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13834:         my $home=&homeserver($uname,$udom);
                   13835:         my $is_me=0;
                   13836:         my @ids=&current_machine_ids();
                   13837:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13838:         if ($is_me) {
1.1117    foxr     13839:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13840:         } else {
                   13841:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13842:   	      $udom.'/'.$uname.'/'.$filename;
                   13843:         }
1.882     albertel 13844:     } elsif ($file =~ m-^/adm/-) {
                   13845: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13846:     } else {
                   13847:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13848:         $file=~s:^/(res|priv)/:/:;
                   13849:         my $space=$1;
1.590     banghart 13850:         if ( !( $file =~ m:^/:) ) {
                   13851:             $location = $dir. '/'.$file;
                   13852:         } else {
1.1142    raeburn  13853:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13854:         }
1.59      albertel 13855:     }
1.590     banghart 13856:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13857:     while ($location=~m{/\.\./}) {
                   13858: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13859: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13860: 	} else {
                   13861: 	    $location=~ s{/\.\./}{/}g;
                   13862: 	}
                   13863:     } #remove dir/..
1.590     banghart 13864:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13865:     return $location;
1.46      www      13866: }
1.36      albertel 13867: 
1.46      www      13868: sub hreflocation {
                   13869:     my ($dir,$file)=@_;
1.980     raeburn  13870:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13871: 	$file=filelocation($dir,$file);
1.700     albertel 13872:     } elsif ($file=~m-^/adm/-) {
                   13873: 	$file=~s-^/adm/wrapper/-/-;
                   13874: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13875:     }
                   13876:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13877: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13878:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13879: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13880: 	        {/uploaded/$1/$2/}x;
1.46      www      13881:     }
1.913     albertel 13882:     if ($file=~ m{^/userfiles/}) {
                   13883: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13884:     }
1.462     albertel 13885:     return $file;
1.465     albertel 13886: }
                   13887: 
1.1139    www      13888: 
                   13889: 
                   13890: 
                   13891: 
1.465     albertel 13892: sub current_machine_domains {
1.853     albertel 13893:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13894: }
                   13895: 
                   13896: sub machine_domains {
                   13897:     my ($hostname) = @_;
1.465     albertel 13898:     my @domains;
1.838     albertel 13899:     my %hostname = &all_hostnames();
1.465     albertel 13900:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13901: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13902: 	if ($hostname eq $name) {
1.844     albertel 13903: 	    push(@domains,&host_domain($id));
1.465     albertel 13904: 	}
                   13905:     }
                   13906:     return @domains;
                   13907: }
                   13908: 
                   13909: sub current_machine_ids {
1.853     albertel 13910:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13911: }
                   13912: 
                   13913: sub machine_ids {
                   13914:     my ($hostname) = @_;
                   13915:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13916:     my @ids;
1.888     albertel 13917:     my %name_to_host = &all_names();
1.889     albertel 13918:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13919: 	return @{ $name_to_host{$hostname} };
                   13920:     }
                   13921:     return;
1.31      www      13922: }
                   13923: 
1.824     raeburn  13924: sub additional_machine_domains {
                   13925:     my @domains;
1.1172.2.142  raeburn  13926:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13927:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13928:             while( my $line = <$fh>) {
                   13929:                 chomp($line);
                   13930:                 $line =~ s/\s//g;
                   13931:                 push(@domains,$line);
                   13932:             }
                   13933:             close($fh);
                   13934:         }
1.824     raeburn  13935:     }
                   13936:     return @domains;
                   13937: }
                   13938: 
                   13939: sub default_login_domain {
                   13940:     my $domain = $perlvar{'lonDefDomain'};
                   13941:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13942:     foreach my $posdom (&current_machine_domains(),
                   13943:                         &additional_machine_domains()) {
                   13944:         if (lc($posdom) eq lc($testdomain)) {
                   13945:             $domain=$posdom;
                   13946:             last;
                   13947:         }
                   13948:     }
                   13949:     return $domain;
                   13950: }
                   13951: 
1.1172.2.106  raeburn  13952: sub shared_institution {
1.1172.2.136  raeburn  13953:     my ($dom,$lonhost) = @_;
                   13954:     if ($lonhost eq '') {
                   13955:         $lonhost = $perlvar{'lonHostID'};
                   13956:     }
1.1172.2.106  raeburn  13957:     my $same_intdom;
1.1172.2.136  raeburn  13958:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13959:     if ($hostintdom ne '') {
                   13960:         my %iphost = &get_iphost();
                   13961:         my $primary_id = &domain($dom,'primary');
                   13962:         my $primary_ip = &get_host_ip($primary_id);
                   13963:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13964:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13965:                 my $intdom = &internet_dom($id);
                   13966:                 if ($intdom eq $hostintdom) {
                   13967:                     $same_intdom = 1;
                   13968:                     last;
                   13969:                 }
                   13970:             }
                   13971:         }
                   13972:     }
                   13973:     return $same_intdom;
                   13974: }
                   13975: 
1.1172.2.120  raeburn  13976: sub uses_sts {
                   13977:     my ($ignore_cache) = @_;
                   13978:     my $lonhost = $perlvar{'lonHostID'};
                   13979:     my $hostname = &hostname($lonhost);
                   13980:     my $sts_on;
                   13981:     if ($protocol{$lonhost} eq 'https') {
                   13982:         my $cachetime = 12*3600;
                   13983:         if (!$ignore_cache) {
                   13984:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13985:             if (defined($cached)) {
                   13986:                 return $sts_on;
                   13987:             }
                   13988:         }
1.1172.2.121  raeburn  13989:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13990:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13991:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13992:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13993:         if ($response->is_success) {
                   13994:             my $has_sts = $response->header('Strict-Transport-Security');
                   13995:             if ($has_sts eq '') {
                   13996:                 $sts_on = 0;
                   13997:             } else {
                   13998:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13999:                     my $maxage = $1;
                   14000:                     if ($maxage) {
                   14001:                         $sts_on = 1;
                   14002:                     } else {
                   14003:                         $sts_on = 0;
                   14004:                     }
                   14005:                 } else {
                   14006:                     $sts_on = 0;
                   14007:                 }
                   14008:             }
                   14009:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14010:         }
                   14011:     }
                   14012:     return;
                   14013: }
                   14014: 
1.1172.2.142  raeburn  14015: sub waf_allssl {
                   14016:     my ($host_name) = @_;
                   14017:     my $alias = &get_proxy_alias();
                   14018:     if ($host_name eq '') {
                   14019:         $host_name = $ENV{'SERVER_NAME'};
                   14020:     }
                   14021:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14022:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14023:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14024:         if ($defdomdefaults{'waf_sslopt'}) {
                   14025:             return $defdomdefaults{'waf_sslopt'};
                   14026:         }
                   14027:     }
                   14028:     return;
                   14029: }
                   14030: 
1.1172.2.134  raeburn  14031: sub get_requestor_ip {
                   14032:     my ($r,$nolookup,$noproxy) = @_;
                   14033:     my $from_ip;
                   14034:     if (ref($r)) {
1.1172.2.142  raeburn  14035:         if ($r->can('useragent_ip')) {
                   14036:             if ($noproxy && $r->can('client_ip')) {
                   14037:                 $from_ip = $r->client_ip();
                   14038:             } else {
                   14039:                 $from_ip = $r->useragent_ip();
                   14040:             }
                   14041:         } elsif ($r->connection->can('remote_ip')) {
                   14042:             $from_ip = $r->connection->remote_ip();
                   14043:         } else {
                   14044:             $from_ip = $r->get_remote_host($nolookup);
                   14045:         }
1.1172.2.134  raeburn  14046:     } else {
                   14047:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14048:     }
1.1172.2.142  raeburn  14049:     return $from_ip if ($noproxy);
                   14050:    # Who controls proxy settings for server
                   14051:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14052:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14053:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14054:         if ($proxyinfo->{'vpnint'}) {
                   14055:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14056:                 return $from_ip;
                   14057:             }
                   14058:         }
                   14059:         if ($proxyinfo->{'trusted'}) {
                   14060:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14061:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14062:                 my ($ip,$xfor);
                   14063:                 if (ref($r)) {
                   14064:                     if ($ipheader) {
                   14065:                         $ip = $r->headers_in->{$ipheader};
                   14066:                     }
                   14067:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14068:                 } else {
                   14069:                     if ($ipheader) {
                   14070:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14071:                     }
                   14072:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14073:                 }
                   14074:                 if (($ip eq '') && ($xfor ne '')) {
                   14075:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14076:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14077:                             $ip = $poss_ip;
                   14078:                             last;
                   14079:                         }
                   14080:                     }
                   14081:                 }
                   14082:                 if ($ip ne '') {
                   14083:                     return $ip;
                   14084:                 }
                   14085:             }
                   14086:         }
                   14087:     }
1.1172.2.134  raeburn  14088:     return $from_ip;
                   14089: }
                   14090: 
1.1172.2.142  raeburn  14091: sub get_proxy_settings {
                   14092:     my ($dom_in_use) = @_;
                   14093:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14094:     my $proxyinfo = {
                   14095:                        ipheader => $domdefaults{'waf_ipheader'},
                   14096:                        trusted  => $domdefaults{'waf_trusted'},
                   14097:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14098:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14099:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14100:                     };
                   14101:     return $proxyinfo;
                   14102: }
                   14103: 
                   14104: sub ip_match {
                   14105:     my ($ip,$pattern_str) = @_;
                   14106:     $ip=Net::CIDR::cidrvalidate($ip);
                   14107:     if ($ip) {
                   14108:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14109:     }
                   14110:     return;
                   14111: }
                   14112: 
                   14113: sub get_proxy_alias {
                   14114:     my ($lonid) = @_;
                   14115:     if ($lonid eq '') {
                   14116:         $lonid = $perlvar{'lonHostID'};
                   14117:     }
                   14118:     if (!defined(&hostname($lonid))) {
                   14119:         return;
                   14120:     }
                   14121:     if ($lonid ne '') {
                   14122:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14123:         if ($cached) {
                   14124:             return $alias;
                   14125:         }
                   14126:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14127:         if ($dom ne '') {
                   14128:             my $cachetime = 60*60*24;
                   14129:             my %domconfig =
                   14130:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14131:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14132:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14133:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14134:                 }
                   14135:             }
                   14136:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14137:         }
                   14138:     }
                   14139:     return;
                   14140: }
                   14141: 
                   14142: sub use_proxy_alias {
                   14143:     my ($r,$lonid) = @_;
                   14144:     my $alias = &get_proxy_alias($lonid);
                   14145:     if ($alias) {
                   14146:         my $dom = &host_domain($lonid);
                   14147:         if ($dom ne '') {
                   14148:             my $proxyinfo = &get_proxy_settings($dom);
                   14149:             my ($vpnint,$remote_ip);
                   14150:             if (ref($proxyinfo) eq 'HASH') {
                   14151:                 $vpnint = $proxyinfo->{'vpnint'};
                   14152:                 if ($vpnint) {
                   14153:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14154:                 }
                   14155:             }
                   14156:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14157:                 return $alias;
                   14158:             }
                   14159:         }
                   14160:     }
                   14161:     return;
                   14162: }
                   14163: 
                   14164: sub alias_sso {
                   14165:     my ($lonid) = @_;
                   14166:     if ($lonid eq '') {
                   14167:         $lonid = $perlvar{'lonHostID'};
                   14168:     }
                   14169:     if (!defined(&hostname($lonid))) {
                   14170:         return;
                   14171:     }
                   14172:     if ($lonid ne '') {
                   14173:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14174:         if ($cached) {
                   14175:             return $use_alias;
                   14176:         }
                   14177:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14178:         if ($dom ne '') {
                   14179:             my $cachetime = 60*60*24;
                   14180:             my %domconfig =
                   14181:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14182:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14183:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14184:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14185:                 }
                   14186:             }
                   14187:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14188:         }
                   14189:     }
                   14190:     return;
                   14191: }
                   14192: 
                   14193: sub get_saml_landing {
                   14194:     my ($lonid) = @_;
                   14195:     if ($lonid eq '') {
                   14196:         my $defdom = &default_login_domain();
                   14197:         my @hosts = &current_machine_ids();
                   14198:         if (@hosts > 1) {
                   14199:             foreach my $hostid (@hosts) {
                   14200:                 if (&host_domain($hostid) eq $defdom) {
                   14201:                     $lonid = $hostid;
                   14202:                     last;
                   14203:                 }
                   14204:             }
                   14205:         } else {
                   14206:             $lonid = $perlvar{'lonHostID'};
                   14207:         }
                   14208:         if ($lonid) {
                   14209:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14210:                 return;
                   14211:             }
                   14212:         } else {
                   14213:             return;
                   14214:         }
                   14215:     } elsif (!defined(&hostname($lonid))) {
                   14216:         return;
                   14217:     }
                   14218:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14219:     if ($cached) {
                   14220:         return $landing;
                   14221:     }
                   14222:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14223:     if ($dom ne '') {
                   14224:         my $cachetime = 60*60*24;
                   14225:         my %domconfig =
                   14226:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14227:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14228:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14229:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14230:                     $landing = 1;
                   14231:                 }
                   14232:             }
                   14233:         }
                   14234:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14235:     }
                   14236:     return;
                   14237: }
                   14238: 
1.31      www      14239: # ------------------------------------------------------------- Declutters URLs
                   14240: 
                   14241: sub declutter {
                   14242:     my $thisfn=shift;
1.569     albertel 14243:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14244:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14245:         $thisfn=~s{^/home/httpd/html}{};
                   14246:     }
1.31      www      14247:     $thisfn=~s/^\///;
1.697     albertel 14248:     $thisfn=~s|^adm/wrapper/||;
                   14249:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14250:     $thisfn=~s/^res\///;
1.1172    bisitz   14251:     $thisfn=~s/^priv\///;
1.1032    raeburn  14252:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14253:         $thisfn=~s/\?.+$//;
                   14254:     }
1.268     www      14255:     return $thisfn;
                   14256: }
                   14257: 
                   14258: # ------------------------------------------------------------- Clutter up URLs
                   14259: 
                   14260: sub clutter {
                   14261:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14262:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14263: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14264:        $thisfn='/res'.$thisfn; 
                   14265:     }
1.1031    raeburn  14266:     if ($thisfn !~m|^/adm|) {
                   14267: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14268: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14269: 	} else {
                   14270: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14271: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14272: 	    if ($embstyle eq 'ssi'
                   14273: 		|| ($embstyle eq 'hdn')
                   14274: 		|| ($embstyle eq 'rat')
                   14275: 		|| ($embstyle eq 'prv')
                   14276: 		|| ($embstyle eq 'ign')) {
                   14277: 		#do nothing with these
                   14278: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14279: 		|| ($embstyle eq 'emb')
                   14280: 		|| ($embstyle eq 'wrp')) {
                   14281: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14282: 	    } elsif ($embstyle eq 'unk'
                   14283: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14284: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14285: 	    } else {
1.718     www      14286: #		&logthis("Got a blank emb style");
1.695     albertel 14287: 	    }
1.694     albertel 14288: 	}
1.1172.2.146.  .1(raebu 14289:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14290:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14291:     }
1.31      www      14292:     return $thisfn;
1.12      www      14293: }
                   14294: 
1.787     albertel 14295: sub clutter_with_no_wrapper {
                   14296:     my $uri = &clutter(shift);
                   14297:     if ($uri =~ m-^/adm/-) {
                   14298: 	$uri =~ s-^/adm/wrapper/-/-;
                   14299: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14300:     }
                   14301:     return $uri;
                   14302: }
                   14303: 
1.557     albertel 14304: sub freeze_escape {
                   14305:     my ($value)=@_;
                   14306:     if (ref($value)) {
                   14307: 	$value=&nfreeze($value);
                   14308: 	return '__FROZEN__'.&escape($value);
                   14309:     }
                   14310:     return &escape($value);
                   14311: }
                   14312: 
1.11      www      14313: 
1.557     albertel 14314: sub thaw_unescape {
                   14315:     my ($value)=@_;
                   14316:     if ($value =~ /^__FROZEN__/) {
                   14317: 	substr($value,0,10,undef);
                   14318: 	$value=&unescape($value);
                   14319: 	return &thaw($value);
                   14320:     }
                   14321:     return &unescape($value);
                   14322: }
                   14323: 
1.436     albertel 14324: sub correct_line_ends {
                   14325:     my ($result)=@_;
                   14326:     $$result =~s/\r\n/\n/mg;
                   14327:     $$result =~s/\r/\n/mg;
1.415     albertel 14328: }
1.1       albertel 14329: # ================================================================ Main Program
                   14330: 
1.184     www      14331: sub goodbye {
1.204     albertel 14332:    &logthis("Starting Shut down");
1.443     albertel 14333: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14334:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14335: #converted
1.599     albertel 14336: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14337:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14338: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14339: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14340: #1.1 only
1.870     albertel 14341: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14342: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14343: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14344: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14345:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14346:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14347:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14348:    &flushcourselogs();
                   14349:    &logthis("Shutting down");
                   14350: }
                   14351: 
1.852     albertel 14352: sub get_dns {
1.1172.2.17  raeburn  14353:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14354:     if (!$ignore_cache) {
                   14355: 	my ($content,$cached)=
                   14356: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14357: 	if ($cached) {
1.1172.2.17  raeburn  14358: 	    &$func($content,$hashref);
1.869     albertel 14359: 	    return;
                   14360: 	}
                   14361:     }
                   14362: 
                   14363:     my %alldns;
1.1172.2.96  raeburn  14364:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14365:         foreach my $dns (<$config>) {
                   14366: 	    next if ($dns !~ /^\^(\S*)/x);
                   14367:             my $line = $1;
                   14368:             my ($host,$protocol) = split(/:/,$line);
                   14369:             if ($protocol ne 'https') {
                   14370:                 $protocol = 'http';
                   14371:             }
                   14372: 	    $alldns{$host} = $protocol;
1.979     raeburn  14373:         }
1.1172.2.96  raeburn  14374:         close($config);
1.869     albertel 14375:     }
                   14376:     while (%alldns) {
1.1172.2.52  raeburn  14377: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14378:         my @content;
                   14379:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14380:             my $command = (split('/',$url))[3];
                   14381:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14382:             delete($alldns{$dns});
                   14383:             next if (($dir eq '') || ($file eq ''));
                   14384:             if (open(my $config,'<',"$dir/$file")) {
                   14385:                 @content = <$config>;
                   14386:                 close($config);
                   14387:             }
                   14388:         } else {
                   14389: 	    my $ua=new LWP::UserAgent;
                   14390:             $ua->timeout(30);
                   14391: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14392: 	    my $response=$ua->request($request);
                   14393:             delete($alldns{$dns});
                   14394: 	    next if ($response->is_error());
                   14395: 	    @content = split("\n",$response->content);
                   14396:         }
1.1172.2.17  raeburn  14397:         unless ($nocache) {
1.1172.2.23  raeburn  14398: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14399:         }
                   14400: 	&$func(\@content,$hashref);
1.869     albertel 14401: 	return;
1.852     albertel 14402:     }
1.871     albertel 14403:     my $which = (split('/',$url))[3];
                   14404:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14405:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14406:         my @content = <$config>;
                   14407:         &$func(\@content,$hashref);
                   14408:     }
1.1172.2.17  raeburn  14409:     return;
                   14410: }
                   14411: 
                   14412: # ------------------------------------------------------Get DNS checksums file
                   14413: sub parse_dns_checksums_tab {
                   14414:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14415:     my $lonhost = $perlvar{'lonHostID'};
                   14416:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14417:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14418:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14419:     my $webconfdir = '/etc/httpd/conf';
                   14420:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14421:         $webconfdir = '/etc/apache2';
                   14422:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14423:         if ($1 >= 10) {
                   14424:             $webconfdir = '/etc/apache2';
                   14425:         }
                   14426:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14427:         if ($1 >= 10.0) {
                   14428:             $webconfdir = '/etc/apache2';
                   14429:         }
                   14430:     }
1.1172.2.17  raeburn  14431:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14432:     my (%chksum,%revnum);
                   14433:     if (ref($lines) eq 'ARRAY') {
                   14434:         chomp(@{$lines});
1.1172.2.34  raeburn  14435:         my $version = shift(@{$lines});
                   14436:         if ($version eq $release) {
1.1172.2.17  raeburn  14437:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14438:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14439:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14440:                     if ($webconfdir eq '/etc/apache2') {
                   14441:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14442:                     }
                   14443:                 }
1.1172.2.34  raeburn  14444:                 $chksum{$file} = $shasum;
                   14445:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14446:             }
                   14447:             if (ref($hashref) eq 'HASH') {
                   14448:                 %{$hashref} = (
                   14449:                                 sums     => \%chksum,
                   14450:                                 versions => \%revnum,
                   14451:                               );
                   14452:             }
                   14453:         }
                   14454:     }
1.869     albertel 14455:     return;
1.852     albertel 14456: }
1.1172.2.17  raeburn  14457: 
                   14458: sub fetch_dns_checksums {
                   14459:     my %checksums;
1.1172.2.34  raeburn  14460:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14461:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14462:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14463:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14464:              \%checksums);
                   14465:     return \%checksums;
                   14466: }
                   14467: 
1.1172.2.142  raeburn  14468: sub parse_getdns_url {
                   14469:     my ($command,$url) = @_;
                   14470:     my $dir = $perlvar{'lonTabDir'};
                   14471:     my $file;
                   14472:     if ($command eq 'hosts') {
                   14473:         $file = 'dns_hosts.tab';
                   14474:     } elsif ($command eq 'domain') {
                   14475:         $file = 'dns_domain.tab';
                   14476:     } elsif ($command eq 'checksums') {
                   14477:         my $version = (split('/',$url))[4];
                   14478:         $file = "dns_checksums/$version.tab",
                   14479:     }
                   14480:     return ($dir,$file);
                   14481: }
                   14482: 
1.327     albertel 14483: # ------------------------------------------------------------ Read domain file
                   14484: {
1.852     albertel 14485:     my $loaded;
1.846     albertel 14486:     my %domain;
                   14487: 
1.852     albertel 14488:     sub parse_domain_tab {
                   14489: 	my ($lines) = @_;
                   14490: 	foreach my $line (@$lines) {
                   14491: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14492: 
1.846     albertel 14493: 	    chomp($line);
1.852     albertel 14494: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14495: 	    my %this_domain;
                   14496: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14497: 			       'lang_def', 'city', 'longi', 'lati',
                   14498: 			       'primary') {
                   14499: 		$this_domain{$field} = shift(@elements);
                   14500: 	    }
                   14501: 	    $domain{$name} = \%this_domain;
1.852     albertel 14502: 	}
                   14503:     }
1.864     albertel 14504: 
                   14505:     sub reset_domain_info {
                   14506: 	undef($loaded);
                   14507: 	undef(%domain);
                   14508:     }
                   14509: 
1.852     albertel 14510:     sub load_domain_tab {
1.1172.2.70  raeburn  14511: 	my ($ignore_cache,$nocache) = @_;
                   14512: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14513: 	my $fh;
1.1172.2.96  raeburn  14514: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14515: 	    my @lines = <$fh>;
                   14516: 	    &parse_domain_tab(\@lines);
1.448     albertel 14517: 	}
1.852     albertel 14518: 	close($fh);
                   14519: 	$loaded = 1;
1.327     albertel 14520:     }
1.846     albertel 14521: 
                   14522:     sub domain {
1.852     albertel 14523: 	&load_domain_tab() if (!$loaded);
                   14524: 
1.846     albertel 14525: 	my ($name,$what) = @_;
                   14526: 	return if ( !exists($domain{$name}) );
                   14527: 
                   14528: 	if (!$what) {
                   14529: 	    return $domain{$name}{'description'};
                   14530: 	}
                   14531: 	return $domain{$name}{$what};
                   14532:     }
1.974     raeburn  14533: 
                   14534:     sub domain_info {
                   14535:         &load_domain_tab() if (!$loaded);
                   14536:         return %domain;
                   14537:     }
                   14538: 
1.327     albertel 14539: }
                   14540: 
                   14541: 
1.1       albertel 14542: # ------------------------------------------------------------- Read hosts file
                   14543: {
1.838     albertel 14544:     my %hostname;
1.844     albertel 14545:     my %hostdom;
1.845     albertel 14546:     my %libserv;
1.852     albertel 14547:     my $loaded;
1.888     albertel 14548:     my %name_to_host;
1.1074    raeburn  14549:     my %internetdom;
1.1107    raeburn  14550:     my %LC_dns_serv;
1.852     albertel 14551: 
                   14552:     sub parse_hosts_tab {
                   14553: 	my ($file) = @_;
                   14554: 	foreach my $configline (@$file) {
                   14555: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14556:             chomp($configline);
                   14557: 	    if ($configline =~ /^\^/) {
                   14558:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14559:                     $LC_dns_serv{$1} = 1;
                   14560:                 }
                   14561:                 next;
                   14562:             }
1.1074    raeburn  14563: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14564: 	    $name=~s/\s//g;
                   14565: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14566:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14567:                     my $curr = $hostname{$id};
                   14568:                     my $skip;
                   14569:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14570:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14571:                             $skip = 1;
                   14572:                         } else {
                   14573:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14574:                         }
                   14575:                     }
                   14576:                     unless ($skip) {
                   14577:                         push(@{$name_to_host{$name}},$id);
                   14578:                     }
                   14579:                 } else {
                   14580:                     push(@{$name_to_host{$name}},$id);
                   14581:                 }
1.852     albertel 14582: 		$hostname{$id}=$name;
                   14583: 		$hostdom{$id}=$domain;
                   14584: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14585:                 if (defined($protocol)) {
                   14586:                     if ($protocol eq 'https') {
                   14587:                         $protocol{$id} = $protocol;
                   14588:                     } else {
                   14589:                         $protocol{$id} = 'http'; 
                   14590:                     }
1.968     raeburn  14591:                 } else {
1.969     raeburn  14592:                     $protocol{$id} = 'http';
1.968     raeburn  14593:                 }
1.1074    raeburn  14594:                 if (defined($intdom)) {
                   14595:                     $internetdom{$id} = $intdom;
                   14596:                 }
1.852     albertel 14597: 	    }
                   14598: 	}
                   14599:     }
1.864     albertel 14600:     
                   14601:     sub reset_hosts_info {
1.897     albertel 14602: 	&purge_remembered();
1.864     albertel 14603: 	&reset_domain_info();
                   14604: 	&reset_hosts_ip_info();
1.892     albertel 14605: 	undef(%name_to_host);
1.864     albertel 14606: 	undef(%hostname);
                   14607: 	undef(%hostdom);
                   14608: 	undef(%libserv);
                   14609: 	undef($loaded);
                   14610:     }
1.1       albertel 14611: 
1.852     albertel 14612:     sub load_hosts_tab {
1.1172.2.70  raeburn  14613: 	my ($ignore_cache,$nocache) = @_;
                   14614: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14615: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14616: 	my @config = <$config>;
                   14617: 	&parse_hosts_tab(\@config);
                   14618: 	close($config);
                   14619: 	$loaded=1;
1.1       albertel 14620:     }
1.852     albertel 14621: 
1.838     albertel 14622:     sub hostname {
1.852     albertel 14623: 	&load_hosts_tab() if (!$loaded);
                   14624: 
1.838     albertel 14625: 	my ($lonid) = @_;
                   14626: 	return $hostname{$lonid};
                   14627:     }
1.845     albertel 14628: 
1.838     albertel 14629:     sub all_hostnames {
1.852     albertel 14630: 	&load_hosts_tab() if (!$loaded);
                   14631: 
1.838     albertel 14632: 	return %hostname;
                   14633:     }
1.845     albertel 14634: 
1.888     albertel 14635:     sub all_names {
1.1172.2.70  raeburn  14636:         my ($ignore_cache,$nocache) = @_;
                   14637: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14638: 
                   14639: 	return %name_to_host;
                   14640:     }
                   14641: 
1.974     raeburn  14642:     sub all_host_domain {
                   14643:         &load_hosts_tab() if (!$loaded);
                   14644:         return %hostdom;
                   14645:     }
                   14646: 
1.845     albertel 14647:     sub is_library {
1.852     albertel 14648: 	&load_hosts_tab() if (!$loaded);
                   14649: 
1.845     albertel 14650: 	return exists($libserv{$_[0]});
                   14651:     }
                   14652: 
                   14653:     sub all_library {
1.852     albertel 14654: 	&load_hosts_tab() if (!$loaded);
                   14655: 
1.845     albertel 14656: 	return %libserv;
                   14657:     }
                   14658: 
1.1062    droeschl 14659:     sub unique_library {
                   14660: 	#2x reverse removes all hostnames that appear more than once
                   14661:         my %unique = reverse &all_library();
                   14662:         return reverse %unique;
                   14663:     }
                   14664: 
1.841     albertel 14665:     sub get_servers {
1.852     albertel 14666: 	&load_hosts_tab() if (!$loaded);
                   14667: 
1.841     albertel 14668: 	my ($domain,$type) = @_;
                   14669: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14670: 	                                          : %hostname;
                   14671: 	my %result;
1.842     albertel 14672: 	if (ref($domain) eq 'ARRAY') {
                   14673: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14674: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14675: 		    $result{$host} = $hostname;
                   14676: 		}
                   14677: 	    }
                   14678: 	} else {
                   14679: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14680: 		if ($hostdom{$host} eq $domain) {
                   14681: 		    $result{$host} = $hostname;
                   14682: 		}
1.841     albertel 14683: 	    }
                   14684: 	}
                   14685: 	return %result;
                   14686:     }
1.845     albertel 14687: 
1.1062    droeschl 14688:     sub get_unique_servers {
                   14689:         my %unique = reverse &get_servers(@_);
                   14690: 	return reverse %unique;
                   14691:     }
                   14692: 
1.844     albertel 14693:     sub host_domain {
1.852     albertel 14694: 	&load_hosts_tab() if (!$loaded);
                   14695: 
1.844     albertel 14696: 	my ($lonid) = @_;
                   14697: 	return $hostdom{$lonid};
                   14698:     }
                   14699: 
1.841     albertel 14700:     sub all_domains {
1.852     albertel 14701: 	&load_hosts_tab() if (!$loaded);
                   14702: 
1.841     albertel 14703: 	my %seen;
                   14704: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14705: 	return @uniq;
                   14706:     }
1.1074    raeburn  14707: 
                   14708:     sub internet_dom {
                   14709:         &load_hosts_tab() if (!$loaded);
                   14710: 
                   14711:         my ($lonid) = @_;
                   14712:         return $internetdom{$lonid};
                   14713:     }
1.1107    raeburn  14714: 
                   14715:     sub is_LC_dns {
                   14716:         &load_hosts_tab() if (!$loaded);
                   14717: 
                   14718:         my ($hostname) = @_;
                   14719:         return exists($LC_dns_serv{$hostname});
                   14720:     }
                   14721: 
1.1       albertel 14722: }
                   14723: 
1.847     albertel 14724: { 
                   14725:     my %iphost;
1.856     albertel 14726:     my %name_to_ip;
                   14727:     my %lonid_to_ip;
1.869     albertel 14728: 
1.847     albertel 14729:     sub get_hosts_from_ip {
                   14730: 	my ($ip) = @_;
                   14731: 	my %iphosts = &get_iphost();
                   14732: 	if (ref($iphosts{$ip})) {
                   14733: 	    return @{$iphosts{$ip}};
                   14734: 	}
                   14735: 	return;
1.839     albertel 14736:     }
1.864     albertel 14737:     
                   14738:     sub reset_hosts_ip_info {
                   14739: 	undef(%iphost);
                   14740: 	undef(%name_to_ip);
                   14741: 	undef(%lonid_to_ip);
                   14742:     }
1.856     albertel 14743: 
                   14744:     sub get_host_ip {
                   14745: 	my ($lonid) = @_;
                   14746: 	if (exists($lonid_to_ip{$lonid})) {
                   14747: 	    return $lonid_to_ip{$lonid};
                   14748: 	}
                   14749: 	my $name=&hostname($lonid);
                   14750:    	my $ip = gethostbyname($name);
                   14751: 	return if (!$ip || length($ip) ne 4);
                   14752: 	$ip=inet_ntoa($ip);
                   14753: 	$name_to_ip{$name}   = $ip;
                   14754: 	$lonid_to_ip{$lonid} = $ip;
                   14755: 	return $ip;
                   14756:     }
1.847     albertel 14757:     
                   14758:     sub get_iphost {
1.1172.2.70  raeburn  14759: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14760: 
1.869     albertel 14761: 	if (!$ignore_cache) {
                   14762: 	    if (%iphost) {
                   14763: 		return %iphost;
                   14764: 	    }
                   14765: 	    my ($ip_info,$cached)=
                   14766: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14767: 	    if ($cached) {
                   14768: 		%iphost      = %{$ip_info->[0]};
                   14769: 		%name_to_ip  = %{$ip_info->[1]};
                   14770: 		%lonid_to_ip = %{$ip_info->[2]};
                   14771: 		return %iphost;
                   14772: 	    }
                   14773: 	}
1.894     albertel 14774: 
                   14775: 	# get yesterday's info for fallback
                   14776: 	my %old_name_to_ip;
                   14777: 	my ($ip_info,$cached)=
                   14778: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14779: 	if ($cached) {
                   14780: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14781: 	}
                   14782: 
1.1172.2.70  raeburn  14783: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14784: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14785: 	    my $ip;
                   14786: 	    if (!exists($name_to_ip{$name})) {
                   14787: 		$ip = gethostbyname($name);
                   14788: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14789: 		    if (defined($old_name_to_ip{$name})) {
                   14790: 			$ip = $old_name_to_ip{$name};
                   14791: 			&logthis("Can't find $name defaulting to old $ip");
                   14792: 		    } else {
                   14793: 			&logthis("Name $name no IP found");
                   14794: 			next;
                   14795: 		    }
                   14796: 		} else {
                   14797: 		    $ip=inet_ntoa($ip);
1.847     albertel 14798: 		}
                   14799: 		$name_to_ip{$name} = $ip;
                   14800: 	    } else {
                   14801: 		$ip = $name_to_ip{$name};
1.653     albertel 14802: 	    }
1.888     albertel 14803: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14804: 		$lonid_to_ip{$id} = $ip;
                   14805: 	    }
                   14806: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14807: 	}
1.1172.2.70  raeburn  14808:         unless ($nocache) {
                   14809: 	    &do_cache_new('iphost','iphost',
                   14810: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14811: 		          48*60*60);
                   14812:         }
1.869     albertel 14813: 
1.847     albertel 14814: 	return %iphost;
1.598     albertel 14815:     }
                   14816: 
1.992     raeburn  14817:     #
                   14818:     #  Given a DNS returns the loncapa host name for that DNS 
                   14819:     # 
                   14820:     sub host_from_dns {
                   14821:         my ($dns) = @_;
                   14822:         my @hosts;
                   14823:         my $ip;
                   14824: 
1.993     raeburn  14825:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14826:             $ip = $name_to_ip{$dns};
                   14827:         }
                   14828:         if (!$ip) {
                   14829:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14830:             if (length($ip) == 4) { 
                   14831: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14832:             }
                   14833:         }
                   14834:         if ($ip) {
                   14835: 	    @hosts = get_hosts_from_ip($ip);
                   14836: 	    return $hosts[0];
                   14837:         }
                   14838:         return undef;
1.986     foxr     14839:     }
1.992     raeburn  14840: 
1.1074    raeburn  14841:     sub get_internet_names {
                   14842:         my ($lonid) = @_;
                   14843:         return if ($lonid eq '');
                   14844:         my ($idnref,$cached)=
                   14845:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14846:         if ($cached) {
                   14847:             return $idnref;
                   14848:         }
                   14849:         my $ip = &get_host_ip($lonid);
                   14850:         my @hosts = &get_hosts_from_ip($ip);
                   14851:         my %iphost = &get_iphost();
                   14852:         my (@idns,%seen);
                   14853:         foreach my $id (@hosts) {
                   14854:             my $dom = &host_domain($id);
                   14855:             my $prim_id = &domain($dom,'primary');
                   14856:             my $prim_ip = &get_host_ip($prim_id);
                   14857:             next if ($seen{$prim_ip});
                   14858:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14859:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14860:                     my $intdom = &internet_dom($id);
                   14861:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14862:                         push(@idns,$intdom);
                   14863:                     }
                   14864:                 }
                   14865:             }
                   14866:             $seen{$prim_ip} = 1;
                   14867:         }
1.1172.2.23  raeburn  14868:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14869:     }
                   14870: 
1.986     foxr     14871: }
                   14872: 
1.1079    raeburn  14873: sub all_loncaparevs {
1.1172.2.39  raeburn  14874:     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  14875: }
                   14876: 
1.1172.2.27  raeburn  14877: # ------------------------------------------------------- Read loncaparev table
                   14878: {
                   14879:     sub load_loncaparevs {
                   14880:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14881:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14882:                 while (my $configline=<$config>) {
                   14883:                     chomp($configline);
                   14884:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14885:                     $loncaparevs{$hostid}=$loncaparev;
                   14886:                 }
                   14887:                 close($config);
                   14888:             }
                   14889:         }
                   14890:     }
                   14891: }
                   14892: 
                   14893: # ----------------------------------------------------- Read serverhostID table
                   14894: {
                   14895:     sub load_serverhomeIDs {
                   14896:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14897:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14898:                 while (my $configline=<$config>) {
                   14899:                     chomp($configline);
                   14900:                     my ($name,$id)=split(/:/,$configline);
                   14901:                     $serverhomeIDs{$name}=$id;
                   14902:                 }
                   14903:                 close($config);
                   14904:             }
                   14905:         }
                   14906:     }
                   14907: }
                   14908: 
                   14909: 
1.862     albertel 14910: BEGIN {
                   14911: 
                   14912: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14913:     unless ($readit) {
                   14914: {
                   14915:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14916:     %perlvar = (%perlvar,%{$configvars});
                   14917: }
                   14918: 
                   14919: 
1.1       albertel 14920: # ------------------------------------------------------ Read spare server file
                   14921: {
1.1172.2.96  raeburn  14922:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14923: 
                   14924:     while (my $configline=<$config>) {
                   14925:        chomp($configline);
1.284     matthew  14926:        if ($configline) {
1.784     albertel 14927: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14928: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14929: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14930:        }
                   14931:     }
1.448     albertel 14932:     close($config);
1.1       albertel 14933: }
1.11      www      14934: # ------------------------------------------------------------ Read permissions
                   14935: {
1.1172.2.96  raeburn  14936:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14937: 
                   14938:     while (my $configline=<$config>) {
1.448     albertel 14939: 	chomp($configline);
                   14940: 	if ($configline) {
                   14941: 	    my ($role,$perm)=split(/ /,$configline);
                   14942: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14943: 	}
1.11      www      14944:     }
1.448     albertel 14945:     close($config);
1.11      www      14946: }
                   14947: 
                   14948: # -------------------------------------------- Read plain texts for permissions
                   14949: {
1.1172.2.96  raeburn  14950:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14951: 
                   14952:     while (my $configline=<$config>) {
1.448     albertel 14953: 	chomp($configline);
                   14954: 	if ($configline) {
1.742     raeburn  14955: 	    my ($short,@plain)=split(/:/,$configline);
                   14956:             %{$prp{$short}} = ();
                   14957: 	    if (@plain > 0) {
                   14958:                 $prp{$short}{'std'} = $plain[0];
                   14959:                 for (my $i=1; $i<@plain; $i++) {
                   14960:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14961:                 }
                   14962:             }
1.448     albertel 14963: 	}
1.135     www      14964:     }
1.448     albertel 14965:     close($config);
1.135     www      14966: }
                   14967: 
                   14968: # ---------------------------------------------------------- Read package table
                   14969: {
1.1172.2.96  raeburn  14970:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14971: 
                   14972:     while (my $configline=<$config>) {
1.483     albertel 14973: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14974: 	chomp($configline);
                   14975: 	my ($short,$plain)=split(/:/,$configline);
                   14976: 	my ($pack,$name)=split(/\&/,$short);
                   14977: 	if ($plain ne '') {
                   14978: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14979: 	    $packagetab{$short}=$plain; 
                   14980: 	}
1.11      www      14981:     }
1.448     albertel 14982:     close($config);
1.329     matthew  14983: }
                   14984: 
1.1172.2.27  raeburn  14985: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14986: 
1.1172.2.27  raeburn  14987: &load_loncaparevs();
                   14988: 
                   14989: # ------------------------------------------------------- Read serverhostID table
                   14990: 
                   14991: &load_serverhomeIDs();
1.1074    raeburn  14992: 
1.1172.2.27  raeburn  14993: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14994: {
                   14995:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14996:     if (-e $file) {
                   14997:         my $parser = HTML::LCParser->new($file);
                   14998:         while (my $token = $parser->get_token()) {
                   14999:             if ($token->[0] eq 'S') {
                   15000:                 my $item = $token->[1];
                   15001:                 my $name = $token->[2]{'name'};
                   15002:                 my $value = $token->[2]{'value'};
                   15003:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15004:                     my $release = $parser->get_text();
                   15005:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15006:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15007:                 }
                   15008:             }
                   15009:         }
                   15010:     }
1.1073    raeburn  15011: }
                   15012: 
1.1138    raeburn  15013: # ---------------------------------------------------------- Read managers table
                   15014: {
                   15015:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15016:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15017:             while (my $configline=<$config>) {
                   15018:                 chomp($configline);
                   15019:                 next if ($configline =~ /^\#/);
                   15020:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15021:                     $managerstab{$configline} = 1;
                   15022:                 }
                   15023:             }
                   15024:             close($config);
                   15025:         }
                   15026:     }
                   15027: }
                   15028: 
1.329     matthew  15029: # ------------- set up temporary directory
                   15030: {
1.1117    foxr     15031:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15032: 
1.11      www      15033: }
                   15034: 
1.1172.2.104  raeburn  15035: # ------------- set default texengine (domain default overrides this)
                   15036: {
                   15037:     $deftex = LONCAPA::texengine();
                   15038: }
                   15039: 
1.1172.2.114  raeburn  15040: # ------------- set default minimum length for passwords for internal auth users
                   15041: {
                   15042:     $passwdmin = LONCAPA::passwd_min();
                   15043: }
                   15044: 
1.794     albertel 15045: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15046: 				'compress_threshold'=> 20_000,
                   15047:  			        });
1.185     www      15048: 
1.281     www      15049: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15050: $dumpcount=0;
1.958     www      15051: $locknum=0;
1.22      www      15052: 
1.163     harris41 15053: &logtouch();
1.672     albertel 15054: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15055: $readit=1;
1.564     albertel 15056:     {
                   15057: 	use integer;
                   15058: 	my $test=(2**32)+1;
1.568     albertel 15059: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15060: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15061:     }
1.195     www      15062: }
1.1       albertel 15063: }
1.179     www      15064: 
1.1       albertel 15065: 1;
1.191     harris41 15066: __END__
                   15067: 
1.243     albertel 15068: =pod
                   15069: 
1.191     harris41 15070: =head1 NAME
                   15071: 
1.243     albertel 15072: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15073: 
                   15074: =head1 SYNOPSIS
                   15075: 
1.243     albertel 15076: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15077: 
                   15078:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15079: 
1.243     albertel 15080: Common parameters:
                   15081: 
                   15082: =over 4
                   15083: 
                   15084: =item *
                   15085: 
                   15086: $uname : an internal username (if $cname expecting a course Id specifically)
                   15087: 
                   15088: =item *
                   15089: 
                   15090: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15091: 
                   15092: =item *
                   15093: 
                   15094: $symb : a resource instance identifier
                   15095: 
                   15096: =item *
                   15097: 
                   15098: $namespace : the name of a .db file that contains the data needed or
                   15099: being set.
                   15100: 
                   15101: =back
                   15102: 
1.394     bowersj2 15103: =head1 OVERVIEW
1.191     harris41 15104: 
1.394     bowersj2 15105: lonnet provides subroutines which interact with the
                   15106: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15107: about classes, users, and resources.
1.243     albertel 15108: 
                   15109: For many of these objects you can also use this to store data about
                   15110: them or modify them in various ways.
1.191     harris41 15111: 
1.394     bowersj2 15112: =head2 Symbs
1.191     harris41 15113: 
1.394     bowersj2 15114: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15115: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15116: map, the resource number of the resource in the map, and the URL of
                   15117: the resource itself. The latter is somewhat redundant, but might help
                   15118: if maps change.
                   15119: 
                   15120: An example is
                   15121: 
                   15122:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15123: 
                   15124: The respective map entry is
                   15125: 
                   15126:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15127:   title="Problem 2">
                   15128:  </resource>
                   15129: 
                   15130: Symbs are used by the random number generator, as well as to store and
                   15131: restore data specific to a certain instance of for example a problem.
                   15132: 
                   15133: =head2 Storing And Retrieving Data
                   15134: 
                   15135: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15136: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15137: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15138: is is the non-critical message twin of cstore. These functions are for
                   15139: handlers to store a perl hash to a user's permanent data space in an
                   15140: easy manner, and to retrieve it again on another call. It is expected
                   15141: that a handler would use this once at the beginning to retrieve data,
                   15142: and then again once at the end to send only the new data back.
                   15143: 
                   15144: The data is stored in the user's data directory on the user's
                   15145: homeserver under the ID of the course.
                   15146: 
                   15147: The hash that is returned by restore will have all of the previous
                   15148: value for all of the elements of the hash.
                   15149: 
                   15150: Example:
                   15151: 
                   15152:  #creating a hash
                   15153:  my %hash;
                   15154:  $hash{'foo'}='bar';
                   15155: 
                   15156:  #storing it
                   15157:  &Apache::lonnet::cstore(\%hash);
                   15158: 
                   15159:  #changing a value
                   15160:  $hash{'foo'}='notbar';
                   15161: 
                   15162:  #adding a new value
                   15163:  $hash{'bar'}='foo';
                   15164:  &Apache::lonnet::cstore(\%hash);
                   15165: 
                   15166:  #retrieving the hash
                   15167:  my %history=&Apache::lonnet::restore();
                   15168: 
                   15169:  #print the hash
                   15170:  foreach my $key (sort(keys(%history))) {
                   15171:    print("\%history{$key} = $history{$key}");
                   15172:  }
                   15173: 
                   15174: Will print out:
1.191     harris41 15175: 
1.394     bowersj2 15176:  %history{1:foo} = bar
                   15177:  %history{1:keys} = foo:timestamp
                   15178:  %history{1:timestamp} = 990455579
                   15179:  %history{2:bar} = foo
                   15180:  %history{2:foo} = notbar
                   15181:  %history{2:keys} = foo:bar:timestamp
                   15182:  %history{2:timestamp} = 990455580
                   15183:  %history{bar} = foo
                   15184:  %history{foo} = notbar
                   15185:  %history{timestamp} = 990455580
                   15186:  %history{version} = 2
                   15187: 
                   15188: Note that the special hash entries C<keys>, C<version> and
                   15189: C<timestamp> were added to the hash. C<version> will be equal to the
                   15190: total number of versions of the data that have been stored. The
                   15191: C<timestamp> attribute will be the UNIX time the hash was
                   15192: stored. C<keys> is available in every historical section to list which
                   15193: keys were added or changed at a specific historical revision of a
                   15194: hash.
                   15195: 
                   15196: B<Warning>: do not store the hash that restore returns directly. This
                   15197: will cause a mess since it will restore the historical keys as if the
                   15198: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15199: 
1.394     bowersj2 15200: Calling convention:
1.191     harris41 15201: 
1.1172.2.27  raeburn  15202:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15203:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15204: 
1.394     bowersj2 15205: For more detailed information, see lonnet specific documentation.
1.191     harris41 15206: 
1.394     bowersj2 15207: =head1 RETURN MESSAGES
1.191     harris41 15208: 
1.394     bowersj2 15209: =over 4
1.191     harris41 15210: 
1.394     bowersj2 15211: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15212: 
1.394     bowersj2 15213: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15214: when the connection is brought back up
1.191     harris41 15215: 
1.394     bowersj2 15216: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15217: for later delivery
1.191     harris41 15218: 
1.967     bisitz   15219: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15220: 
1.394     bowersj2 15221: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15222: that was requested
1.191     harris41 15223: 
1.243     albertel 15224: =back
1.191     harris41 15225: 
1.243     albertel 15226: =head1 PUBLIC SUBROUTINES
1.191     harris41 15227: 
1.243     albertel 15228: =head2 Session Environment Functions
1.191     harris41 15229: 
1.243     albertel 15230: =over 4
1.191     harris41 15231: 
1.394     bowersj2 15232: =item * 
                   15233: X<appenv()>
1.949     raeburn  15234: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15235: the user envirnoment file, and will be restored for each access this
1.620     albertel 15236: user makes during this session, also modifies the %env for the current
1.949     raeburn  15237: process. Optional rolesarrayref - if defined contains a reference to an array
                   15238: of roles which are exempt from the restriction on modifying user.role entries 
                   15239: in the user's environment.db and in %env.    
1.191     harris41 15240: 
                   15241: =item *
1.394     bowersj2 15242: X<delenv()>
1.987     raeburn  15243: B<delenv($delthis,$regexp)>: removes all items from the session
                   15244: environment file that begin with $delthis. If the 
                   15245: optional second arg - $regexp - is true, $delthis is treated as a 
                   15246: regular expression, otherwise \Q$delthis\E is used. 
                   15247: The values are also deleted from the current processes %env.
1.191     harris41 15248: 
1.795     albertel 15249: =item * get_env_multiple($name) 
                   15250: 
                   15251: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15252: values may be defined and end up as an array ref.
                   15253: 
                   15254: returns an array of values
                   15255: 
1.243     albertel 15256: =back
                   15257: 
                   15258: =head2 User Information
1.191     harris41 15259: 
1.243     albertel 15260: =over 4
1.191     harris41 15261: 
                   15262: =item *
1.394     bowersj2 15263: X<queryauthenticate()>
                   15264: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15265: authentication scheme
                   15266: 
                   15267: =item *
1.394     bowersj2 15268: X<authenticate()>
1.1073    raeburn  15269: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15270: authenticate user from domain's lib servers (first use the current
                   15271: one). C<$upass> should be the users password.
1.1073    raeburn  15272: $checkdefauth is optional (value is 1 if a check should be made to
                   15273:    authenticate user using default authentication method, and allow
                   15274:    account creation if username does not have account in the domain).
                   15275: $clientcancheckhost is optional (value is 1 if checking whether the
                   15276:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15277: 
                   15278: =item *
1.394     bowersj2 15279: X<homeserver()>
                   15280: B<homeserver($uname,$udom)>: find the server which has
                   15281: the user's directory and files (there must be only one), this caches
                   15282: the answer, and also caches if there is a borken connection.
1.191     harris41 15283: 
                   15284: =item *
1.394     bowersj2 15285: X<idget()>
                   15286: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15287: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15288: username, and only 1 username per ID in a specific domain) (returns
                   15289: hash: id=>name,id=>name)
1.191     harris41 15290: 
                   15291: =item *
1.394     bowersj2 15292: X<idrget()>
                   15293: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15294: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15295: 
                   15296: =item *
1.394     bowersj2 15297: X<idput()>
                   15298: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15299: 
                   15300: =item *
1.394     bowersj2 15301: X<rolesinit()>
1.1169    droeschl 15302: B<rolesinit($udom,$username)>: get user privileges.
                   15303: returns user role, first access and timer interval hashes
1.243     albertel 15304: 
                   15305: =item *
1.1171    droeschl 15306: X<privileged()>
                   15307: B<privileged($username,$domain)>: returns a true if user has a
                   15308: privileged and active role (i.e. su or dc), false otherwise.
                   15309: 
                   15310: =item *
1.551     albertel 15311: X<getsection()>
                   15312: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15313: course $cname, return section name/number or '' for "not in course"
                   15314: and '-1' for "no section"
                   15315: 
                   15316: =item *
1.394     bowersj2 15317: X<userenvironment()>
                   15318: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15319: passed in @what from the requested user's environment, returns a hash
                   15320: 
1.858     raeburn  15321: =item * 
                   15322: X<userlog_query()>
1.859     albertel 15323: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15324: activity.log file. %filters defines filters applied when parsing the
                   15325: log file. These can be start or end timestamps, or the type of action
                   15326: - log to look for Login or Logout events, check for Checkin or
                   15327: Checkout, role for role selection. The response is in the form
                   15328: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15329: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15330: 
1.243     albertel 15331: =back
                   15332: 
                   15333: =head2 User Roles
                   15334: 
                   15335: =over 4
                   15336: 
                   15337: =item *
                   15338: 
1.1172.2.65  raeburn  15339: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15340: returns codes for allowed actions.
                   15341: 
                   15342: The first argument is required, all others are optional.
                   15343: 
                   15344: $priv is the privilege being checked.
                   15345: $uri contains additional information about what is being checked for access (e.g.,
                   15346: URL, course ID etc.).
                   15347: $symb is the unique resource instance identifier in a course; if needed,
                   15348: but not provided, it will be retrieved via a call to &symbread().
                   15349: $role is the role for which a priv is being checked (only used if priv is evb).
                   15350: $clientip is the user's IP address (only used when checking for access to portfolio
                   15351: files).
                   15352: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15353: prevents recursive calls to &allowed.
                   15354: 
1.243     albertel 15355:  F: full access
                   15356:  U,I,K: authentication modes (cxx only)
                   15357:  '': forbidden
                   15358:  1: user needs to choose course
                   15359:  2: browse allowed
1.766     albertel 15360:  A: passphrase authentication needed
1.1172.2.65  raeburn  15361:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15362:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15363: 
                   15364: =item *
                   15365: 
1.1172.2.13  raeburn  15366: constructaccess($url,$setpriv) : check for access to construction space URL
                   15367: 
                   15368: See if the owner domain and name in the URL match those in the
                   15369: expected environment.  If so, return three element list
                   15370: ($ownername,$ownerdomain,$ownerhome).
                   15371: 
                   15372: Otherwise return the null string.
                   15373: 
                   15374: If second argument 'setpriv' is true, it assigns the privileges,
                   15375: and returns the same three element list, unless the owner has
                   15376: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15377: in which case the null string is returned.
                   15378: 
                   15379: =item *
                   15380: 
1.1172.2.84  raeburn  15381: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15382: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15383: for system, domain, and course level. $uname and $udom are optional (current
                   15384: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15385: 
                   15386: =item *
                   15387: 
1.988     raeburn  15388: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15389: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15390: $type is Course (default) or Community.
1.988     raeburn  15391: If $forcedefault evaluates to true, text returned will be default 
                   15392: text for $type. Otherwise, if this is a course, the text returned 
                   15393: will be a custom name for the role (if defined in the course's 
                   15394: environment).  If no custom name is defined the default is returned.
                   15395:    
1.832     raeburn  15396: =item *
                   15397: 
1.1172.2.23  raeburn  15398: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15399: All arguments are optional. Returns a hash of a roles, either for
                   15400: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15401: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15402: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15403: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15404: For each key, value is set to colon-separated start and end times for
                   15405: the role.  If no username and domain are specified, will default to
1.934     raeburn  15406: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15407: of role statuses (active, future or previous), roles 
                   15408: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15409: to restrict the list of roles reported. If no array ref is 
                   15410: provided for types, will default to return only active roles.
1.834     albertel 15411: 
1.1172.2.13  raeburn  15412: =item *
                   15413: 
                   15414: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15415: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15416: 
                   15417: Additional optional arguments are: $type (if role checking is to be restricted
                   15418: to certain user status types -- previous (expired roles), active (currently
                   15419: available roles) or future (roles available in the future), and
                   15420: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15421: have active Domain Coordinator role in course's domain or in additional
                   15422: domains (specified in 'Domains to check for privileged users' in course
                   15423: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15424: 
                   15425: =item *
                   15426: 
                   15427: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15428: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15429: $possdomains and $possroles are optional array refs -- to domains to check and
                   15430: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15431: users' roles.db to check for a dc or su role in any domain. This can be
                   15432: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15433: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15434: this then allows &privileged_by_domain() to be used, which caches the identity
                   15435: of privileged users, eliminating the need for repeated calls to &dump().
                   15436: 
                   15437: =item *
                   15438: 
                   15439: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15440: where the outer hash keys are domains specified in the $possdomains array ref,
                   15441: next inner hash keys are privileged roles specified in the $roles array ref,
                   15442: and the innermost hash contains key = value pairs for username:domain = end:start
                   15443: for active or future "privileged" users with that role in that domain. To avoid
                   15444: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15445: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15446: 
1.243     albertel 15447: =back
                   15448: 
                   15449: =head2 User Modification
                   15450: 
                   15451: =over 4
                   15452: 
                   15453: =item *
                   15454: 
1.957     raeburn  15455: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15456: user for the level given by URL.  Optional start and end dates (leave empty
                   15457: string or zero for "no date")
1.191     harris41 15458: 
                   15459: =item *
                   15460: 
1.243     albertel 15461: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15462: change a users, password, possible return values are: ok,
                   15463: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15464: refused
1.191     harris41 15465: 
                   15466: =item *
                   15467: 
1.243     albertel 15468: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15469: 
                   15470: =item *
                   15471: 
1.1058    raeburn  15472: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15473:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15474: 
                   15475: will update user information (firstname,middlename,lastname,generation,
                   15476: permanentemail), and if forceid is true, student/employee ID also.
                   15477: A user's institutional affiliation(s) can also be updated.
                   15478: User information fields will not be overwritten with empty entries 
                   15479: unless the field is included in the $candelete array reference.
                   15480: This array is included when a single user is modified via "Manage Users",
                   15481: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15482: 
                   15483: =item *
                   15484: 
1.286     matthew  15485: modifystudent
                   15486: 
1.957     raeburn  15487: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15488: The course id is resolved based on the current user's environment.  
                   15489: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15490: associated with a course.
                   15491: 
1.297     matthew  15492: This call is essentially a wrapper for lonnet::modifyuser and
                   15493: lonnet::modify_student_enrollment
1.286     matthew  15494: 
                   15495: Inputs: 
                   15496: 
                   15497: =over 4
                   15498: 
1.957     raeburn  15499: =item B<$udom> Student's loncapa domain
1.286     matthew  15500: 
1.957     raeburn  15501: =item B<$uname> Student's loncapa login name
1.286     matthew  15502: 
1.964     bisitz   15503: =item B<$uid> Student/Employee ID
1.286     matthew  15504: 
1.957     raeburn  15505: =item B<$umode> Student's authentication mode
1.286     matthew  15506: 
1.957     raeburn  15507: =item B<$upass> Student's password
1.286     matthew  15508: 
1.957     raeburn  15509: =item B<$first> Student's first name
1.286     matthew  15510: 
1.957     raeburn  15511: =item B<$middle> Student's middle name
1.286     matthew  15512: 
1.957     raeburn  15513: =item B<$last> Student's last name
1.286     matthew  15514: 
1.957     raeburn  15515: =item B<$gene> Student's generation
1.286     matthew  15516: 
1.957     raeburn  15517: =item B<$usec> Student's section in course
1.286     matthew  15518: 
                   15519: =item B<$end> Unix time of the roles expiration
                   15520: 
                   15521: =item B<$start> Unix time of the roles start date
                   15522: 
                   15523: =item B<$forceid> If defined, allow $uid to be changed
                   15524: 
                   15525: =item B<$desiredhome> server to use as home server for student
                   15526: 
1.957     raeburn  15527: =item B<$email> Student's permanent e-mail address
                   15528: 
                   15529: =item B<$type> Type of enrollment (auto or manual)
                   15530: 
1.963     raeburn  15531: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15532: 
                   15533: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15534: 
1.963     raeburn  15535: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15536: 
1.963     raeburn  15537: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15538: 
1.1172.2.19  raeburn  15539: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15540: 
                   15541: =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  15542: 
1.286     matthew  15543: =back
1.297     matthew  15544: 
                   15545: =item *
                   15546: 
                   15547: modify_student_enrollment
                   15548: 
1.1172.2.31  raeburn  15549: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15550: 'role.request.course' must be defined for this function to proceed.
                   15551: 
                   15552: Inputs:
                   15553: 
                   15554: =over 4
                   15555: 
1.1172.2.31  raeburn  15556: =item $udom, student's domain
1.297     matthew  15557: 
1.1172.2.31  raeburn  15558: =item $uname, student's name
1.297     matthew  15559: 
1.1172.2.31  raeburn  15560: =item $uid, student's user id
1.297     matthew  15561: 
1.1172.2.31  raeburn  15562: =item $first, student's first name
1.297     matthew  15563: 
                   15564: =item $middle
                   15565: 
                   15566: =item $last
                   15567: 
                   15568: =item $gene
                   15569: 
                   15570: =item $usec
                   15571: 
                   15572: =item $end
                   15573: 
                   15574: =item $start
                   15575: 
1.957     raeburn  15576: =item $type
                   15577: 
                   15578: =item $locktype
                   15579: 
                   15580: =item $cid
                   15581: 
                   15582: =item $selfenroll
                   15583: 
                   15584: =item $context
                   15585: 
1.1172.2.19  raeburn  15586: =item $credits, number of credits student will earn from this class
                   15587: 
1.1172.2.76  raeburn  15588: =item $instsec, institutional course section code for student
                   15589: 
1.297     matthew  15590: =back
                   15591: 
1.191     harris41 15592: 
                   15593: =item *
                   15594: 
1.243     albertel 15595: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15596: custom role; give a custom role to a user for the level given by URL.  Specify
                   15597: name and domain of role author, and role name
1.191     harris41 15598: 
                   15599: =item *
                   15600: 
1.243     albertel 15601: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15602: 
                   15603: =item *
                   15604: 
1.243     albertel 15605: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15606: 
                   15607: =back
                   15608: 
                   15609: =head2 Course Infomation
                   15610: 
                   15611: =over 4
1.191     harris41 15612: 
                   15613: =item *
                   15614: 
1.1118    foxr     15615: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15616: specified course id, including all environment settings for the
                   15617: course, the description of the course will be in the hash under the
                   15618: key 'description'
1.191     harris41 15619: 
1.1118    foxr     15620: $options is an optional parameter that if supplied is a hash reference that controls
                   15621: what how this function works.  It has the following key/values:
                   15622: 
                   15623: =over 4
                   15624: 
                   15625: =item freshen_cache
                   15626: 
                   15627: If defined, and the environment cache for the course is valid, it is 
                   15628: returned in the returned hash.
                   15629: 
                   15630: =item one_time
                   15631: 
                   15632: If defined, the last cache time is set to _now_
                   15633: 
                   15634: =item user
                   15635: 
                   15636: If defined, the supplied username is used instead of the current user.
                   15637: 
                   15638: 
                   15639: =back
                   15640: 
1.191     harris41 15641: =item *
                   15642: 
1.624     albertel 15643: resdata($name,$domain,$type,@which) : request for current parameter
                   15644: setting for a specific $type, where $type is either 'course' or 'user',
                   15645: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15646: answers for 10 minutes.
1.243     albertel 15647: 
1.877     foxr     15648: =item *
                   15649: 
                   15650: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15651: data base, returning a hash that is keyed by the resource name and has
                   15652: values that are the resource value.  I believe that the timestamps and
                   15653: versions are also returned.
                   15654: 
1.1172.2.31  raeburn  15655: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15656: supplemental content area. This routine caches the number of files for
                   15657: 10 minutes.
                   15658: 
1.243     albertel 15659: =back
                   15660: 
                   15661: =head2 Course Modification
                   15662: 
                   15663: =over 4
1.191     harris41 15664: 
                   15665: =item *
                   15666: 
1.243     albertel 15667: writecoursepref($courseid,%prefs) : write preferences (environment
                   15668: database) for a course
1.191     harris41 15669: 
                   15670: =item *
                   15671: 
1.1011    raeburn  15672: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15673: 
                   15674: =item *
                   15675: 
1.1038    raeburn  15676: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15677: 
1.1167    droeschl 15678: =item *
                   15679: 
                   15680: is_course($courseid), is_course($cdom, $cnum)
                   15681: 
                   15682: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15683: two component version $cdom, $cnum. It checks if the specified course exists.
                   15684: 
                   15685: Returns:
                   15686:     undef if the course doesn't exist, otherwise
                   15687:     in scalar context the combined courseid.
                   15688:     in list context the two components of the course identifier, domain and 
                   15689:     courseid.    
                   15690: 
1.243     albertel 15691: =back
                   15692: 
1.1172.2.109  raeburn  15693: =head2 Bubblesheet Configuration
                   15694: 
                   15695: =over 4
                   15696: 
                   15697: =item *
                   15698: 
                   15699: get_scantron_config($which)
                   15700: 
                   15701: $which - the name of the configuration to parse from the file.
                   15702: 
                   15703: Parses and returns the bubblesheet configuration line selected as a
                   15704: hash of configuration file fields.
                   15705: 
                   15706: 
                   15707: Returns:
                   15708:     If the named configuration is not in the file, an empty
                   15709:     hash is returned.
                   15710: 
                   15711:     a hash with the fields
                   15712:       name         - internal name for the this configuration setup
                   15713:       description  - text to display to operator that describes this config
                   15714:       CODElocation - if 0 or the string 'none'
                   15715:                           - no CODE exists for this config
                   15716:                      if -1 || the string 'letter'
                   15717:                           - a CODE exists for this config and is
                   15718:                             a string of letters
                   15719:                      Unsupported value (but planned for future support)
                   15720:                           if a positive integer
                   15721:                                - The CODE exists as the first n items from
                   15722:                                  the question section of the form
                   15723:                           if the string 'number'
                   15724:                                - The CODE exists for this config and is
                   15725:                                  a string of numbers
                   15726:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15727:                      the CODE starts
                   15728:       CODElength  - length of the CODE
                   15729:       IDstart     - column where the student/employee ID starts
                   15730:       IDlength    - length of the student/employee ID info
                   15731:       Qstart      - column where the information from the bubbled
                   15732:                     'questions' start
                   15733:       Qlength     - number of columns comprising a single bubble line from
                   15734:                     the sheet. (usually either 1 or 10)
                   15735:       Qon         - either a single character representing the character used
                   15736:                     to signal a bubble was chosen in the positional setup, or
                   15737:                     the string 'letter' if the letter of the chosen bubble is
                   15738:                     in the final, or 'number' if a number representing the
                   15739:                     chosen bubble is in the file (1->A 0->J)
                   15740:       Qoff        - the character used to represent that a bubble was
                   15741:                     left blank
                   15742:       PaperID     - if the scanning process generates a unique number for each
                   15743:                     sheet scanned the column that this ID number starts in
                   15744:       PaperIDlength - number of columns that comprise the unique ID number
                   15745:                       for the sheet of paper
                   15746:       FirstName   - column that the first name starts in
                   15747:       FirstNameLength - number of columns that the first name spans
                   15748:       LastName    - column that the last name starts in
                   15749:       LastNameLength - number of columns that the last name spans
                   15750:       BubblesPerRow - number of bubbles available in each row used to
                   15751:                       bubble an answer. (If not specified, 10 assumed).
                   15752: 
                   15753: 
                   15754: =item *
                   15755: 
                   15756: get_scantronformat_file($cdom)
                   15757: 
                   15758: $cdom - the course's domain (optional); if not supplied, uses
                   15759: domain for current $env{'request.course.id'}.
                   15760: 
                   15761: Returns an array containing lines from the scantron format file for
                   15762: the domain of the course.
                   15763: 
                   15764: If a url for a custom.tab file is listed in domain's configuration.db,
                   15765: lines are from this file.
                   15766: 
                   15767: Otherwise, if a default.tab has been published in RES space by the
                   15768: domainconfig user, lines are from this file.
                   15769: 
                   15770: Otherwise, fall back to getting lines from the legacy file on the
                   15771: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15772: 
                   15773: =back
                   15774: 
1.243     albertel 15775: =head2 Resource Subroutines
                   15776: 
                   15777: =over 4
1.191     harris41 15778: 
                   15779: =item *
                   15780: 
1.243     albertel 15781: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15782: 
                   15783: =item *
                   15784: 
1.243     albertel 15785: repcopy($filename) : subscribes to the requested file, and attempts to
                   15786: replicate from the owning library server, Might return
1.607     raeburn  15787: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15788: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15789: resource. Expects the local filesystem pathname
                   15790: (/home/httpd/html/res/....)
                   15791: 
                   15792: =back
                   15793: 
                   15794: =head2 Resource Information
                   15795: 
                   15796: =over 4
1.191     harris41 15797: 
                   15798: =item *
                   15799: 
1.1172.2.28  raeburn  15800: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15801: and returns the value of a variety of different possible values,
                   15802: $varname should be a request string, and the other parameters can be
                   15803: used to specify who and what one is asking about. Ordinarily, $cid 
                   15804: does not need to be specified, as it is retrived from 
                   15805: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15806: within lonuserstate::loadmap() when initializing a course, before
                   15807: $env{'request.course.id'} has been set, so it needs to be provided
                   15808: in that one case.
1.243     albertel 15809: 
                   15810: Possible values for $varname are environment.lastname (or other item
                   15811: from the envirnment hash), user.name (or someother aspect about the
                   15812: user), resource.0.maxtries (or some other part and parameter of a
                   15813: resource)
1.204     albertel 15814: 
                   15815: =item *
                   15816: 
1.243     albertel 15817: directcondval($number) : get current value of a condition; reads from a state
                   15818: string
1.204     albertel 15819: 
                   15820: =item *
                   15821: 
1.243     albertel 15822: condval($condidx) : value of condition index based on state
1.204     albertel 15823: 
                   15824: =item *
                   15825: 
1.243     albertel 15826: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15827: resource's metadata, $what should be either a specific key, or either
                   15828: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15829: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15830: 
                   15831: this function automatically caches all requests
1.191     harris41 15832: 
                   15833: =item *
                   15834: 
1.243     albertel 15835: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15836: network of library servers; returns file handle of where SQL and regex results
                   15837: will be stored for query
1.191     harris41 15838: 
                   15839: =item *
                   15840: 
1.1172.2.66  raeburn  15841: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15842: return symbolic list entry (all arguments optional).
                   15843: 
                   15844: Args: filename is the filename (including path) for the file for which a symb
                   15845: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15846: to check access status if more than one resource was found in the bighash
                   15847: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15848: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15849: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15850: cause possible symbs to be checked to determine if they are subject to content
                   15851: blocking, if so they will not be included as possible symbs; possibles is a
                   15852: ref to a hash, which, as a side effect, will be populated with all possible
                   15853: symbs (content blocking not tested).
                   15854: 
1.243     albertel 15855: returns the data handle
1.191     harris41 15856: 
                   15857: =item *
                   15858: 
1.1172.2.17  raeburn  15859: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15860: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15861: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15862: on failure, user must be in a course, as it assumes the existence of
                   15863: the course initial hash, and uses $env('request.course.id'}.  The third
                   15864: arg is an optional reference to a scalar.  If this arg is passed in the
                   15865: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15866: encrypted; otherwise it will be null.
1.243     albertel 15867: 
1.191     harris41 15868: =item *
                   15869: 
1.243     albertel 15870: symbclean($symb) : removes versions numbers from a symb, returns the
                   15871: cleaned symb
1.191     harris41 15872: 
                   15873: =item *
                   15874: 
1.243     albertel 15875: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15876: course map, user must be in a course for it to work.
1.191     harris41 15877: 
                   15878: =item *
                   15879: 
1.243     albertel 15880: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15881: 
                   15882: =item *
                   15883: 
1.243     albertel 15884: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15885: a random seed, all arguments are optional, if they aren't sent it uses the
                   15886: environment to derive them. Note: if symb isn't sent and it can't get one
                   15887: from &symbread it will use the current time as its return value
1.191     harris41 15888: 
                   15889: =item *
                   15890: 
1.243     albertel 15891: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15892: unfakeable, receipt
1.191     harris41 15893: 
                   15894: =item *
                   15895: 
1.620     albertel 15896: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15897: 
                   15898: =item *
                   15899: 
1.243     albertel 15900: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15901: 
                   15902: =item *
                   15903: 
1.243     albertel 15904: 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 15905: 
                   15906: =item *
                   15907: 
1.243     albertel 15908: 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 15909: 
                   15910: =item *
                   15911: 
1.243     albertel 15912: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15913: 
                   15914: =item *
                   15915: 
1.243     albertel 15916: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15917: forcing spreadsheet to reevaluate the resource scores next time.
                   15918: 
1.1172.2.13  raeburn  15919: =item *
                   15920: 
                   15921: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15922: when viewing in course context.
                   15923: 
                   15924:  input: six args -- filename (decluttered), course number, course domain,
                   15925:                     url, symb (if registered) and group (if this is a
                   15926:                     group item -- e.g., bulletin board, group page etc.).
                   15927: 
                   15928:  output: array of five scalars --
                   15929:          $cfile -- url for file editing if editable on current server
                   15930:          $home -- homeserver of resource (i.e., for author if published,
                   15931:                                           or course if uploaded.).
                   15932:          $switchserver --  1 if server switch will be needed.
                   15933:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15934:          $forceview -- 1 if icon/link should be to go to view mode
                   15935: 
                   15936: =item *
                   15937: 
                   15938: is_course_upload($file,$cnum,$cdom)
                   15939: 
                   15940: Used in course context to determine if current file was uploaded to
                   15941: the course (i.e., would be found in /userfiles/docs on the course's
                   15942: homeserver.
                   15943: 
                   15944:   input: 3 args -- filename (decluttered), course number and course domain.
                   15945:   output: boolean -- 1 if file was uploaded.
                   15946: 
1.243     albertel 15947: =back
                   15948: 
                   15949: =head2 Storing/Retreiving Data
                   15950: 
                   15951: =over 4
1.191     harris41 15952: 
                   15953: =item *
                   15954: 
1.1172.2.64  raeburn  15955: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15956: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15957: the remaining args aren't required and if they aren't passed or are '' they will
                   15958: be derived from the env (with the exception of $laststore, which is an
                   15959: optional arg used when a user's submission is stored in grading).
                   15960: $laststore is $version=$timestamp, where $version is the most recent version
                   15961: number retrieved for the corresponding $symb in the $namespace db file, and
                   15962: $timestamp is the timestamp for that transaction (UNIX time).
                   15963: $laststore is currently only passed when cstore() is called by
                   15964: structuretags::finalize_storage().
1.191     harris41 15965: 
                   15966: =item *
                   15967: 
1.1172.2.64  raeburn  15968: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15969: but uses critical subroutine
1.191     harris41 15970: 
                   15971: =item *
                   15972: 
1.243     albertel 15973: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15974: all args are optional
1.191     harris41 15975: 
                   15976: =item *
                   15977: 
1.717     albertel 15978: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15979: dumps the complete (or key matching regexp) namespace into a hash
                   15980: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15981: normally &store()ed into
                   15982: 
                   15983: $range should be either an integer '100' (give me the first 100
                   15984:                                            matching records)
                   15985:               or be  two integers sperated by a - with no spaces
                   15986:                  '30-50' (give me the 30th through the 50th matching
                   15987:                           records)
                   15988: 
                   15989: 
                   15990: =item *
                   15991: 
1.1172.2.59  raeburn  15992: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15993: replaces a &store() version of data with a replacement set of data
                   15994: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15995: reference. If $tolog is true, the transaction is logged in the courselog
                   15996: with an action=PUTSTORE.
1.717     albertel 15997: 
                   15998: =item *
                   15999: 
1.243     albertel 16000: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16001: works very similar to store/cstore, but all data is stored in a
                   16002: temporary location and can be reset using tmpreset, $storehash should
                   16003: be a hash reference, returns nothing on success
1.191     harris41 16004: 
                   16005: =item *
                   16006: 
1.243     albertel 16007: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16008: similar to restore, but all data is stored in a temporary location and
                   16009: can be reset using tmpreset. Returns a hash of values on success,
                   16010: error string otherwise.
1.191     harris41 16011: 
                   16012: =item *
                   16013: 
1.243     albertel 16014: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16015: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16016: 
                   16017: =item *
                   16018: 
1.243     albertel 16019: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16020: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16021: 
                   16022: =item *
                   16023: 
1.243     albertel 16024: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16025: namesp ($udom and $uname are optional)
1.191     harris41 16026: 
                   16027: =item *
                   16028: 
1.702     albertel 16029: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16030: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16031: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16032: 
1.702     albertel 16033: $range should be either an integer '100' (give me the first 100
                   16034:                                            matching records)
                   16035:               or be  two integers sperated by a - with no spaces
                   16036:                  '30-50' (give me the 30th through the 50th matching
                   16037:                           records)
1.449     matthew  16038: =item *
                   16039: 
                   16040: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16041: $store can be a scalar, an array reference, or if the amount to be 
                   16042: incremented is > 1, a hash reference.
                   16043: 
                   16044: ($udom and $uname are optional)
1.191     harris41 16045: 
                   16046: =item *
                   16047: 
1.243     albertel 16048: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16049: ($udom and $uname are optional)
1.191     harris41 16050: 
                   16051: =item *
                   16052: 
1.243     albertel 16053: cput($namespace,$storehash,$udom,$uname) : critical put
                   16054: ($udom and $uname are optional)
1.191     harris41 16055: 
                   16056: =item *
                   16057: 
1.748     albertel 16058: newput($namespace,$storehash,$udom,$uname) :
                   16059: 
                   16060: Attempts to store the items in the $storehash, but only if they don't
                   16061: currently exist, if this succeeds you can be certain that you have 
                   16062: successfully created a new key value pair in the $namespace db.
                   16063: 
                   16064: 
                   16065: Args:
                   16066:  $namespace: name of database to store values to
                   16067:  $storehash: hashref to store to the db
                   16068:  $udom: (optional) domain of user containing the db
                   16069:  $uname: (optional) name of user caontaining the db
                   16070: 
                   16071: Returns:
                   16072:  'ok' -> succeeded in storing all keys of $storehash
                   16073:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16074:                         least <key> already existed in the db (other
                   16075:                         requested keys may also already exist)
1.967     bisitz   16076:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16077:  'con_lost' -> unable to contact request server
                   16078:  'refused' -> action was not allowed by remote machine
                   16079: 
                   16080: 
                   16081: =item *
                   16082: 
1.243     albertel 16083: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16084: reference filled in from namesp (encrypts the return communication)
                   16085: ($udom and $uname are optional)
1.191     harris41 16086: 
                   16087: =item *
                   16088: 
1.243     albertel 16089: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16090: critical subroutine
                   16091: 
1.806     raeburn  16092: =item *
                   16093: 
1.860     raeburn  16094: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16095: array reference filled in from namespace found in domain level on either
                   16096: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16097: 
                   16098: =item *
                   16099: 
1.860     raeburn  16100: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16101: domain level either on specified domain server ($uhome) or primary domain 
                   16102: server ($udom and $uhome are optional)
1.806     raeburn  16103: 
1.943     raeburn  16104: =item * 
                   16105: 
1.1172.2.35  raeburn  16106: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16107: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16108: the target domain.
                   16109: 
                   16110: May also include additional key => value pairs for the following groups:
                   16111: 
                   16112: =over
                   16113: 
                   16114: =item
                   16115: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16116: 
                   16117: =over
                   16118: 
                   16119: =item defaultquota, authorquota
                   16120: 
                   16121: =back
                   16122: 
                   16123: =item
                   16124: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16125: portfolio for users).
                   16126: 
                   16127: =over
                   16128: 
                   16129: =item
                   16130: aboutme, blog, webdav, portfolio
                   16131: 
                   16132: =back
                   16133: 
                   16134: =item
                   16135: requestcourses: ability to request courses, and how requests are processed.
                   16136: 
                   16137: =over
                   16138: 
                   16139: =item
1.1172.2.37  raeburn  16140: official, unofficial, community, textbook
1.1172.2.35  raeburn  16141: 
                   16142: =back
                   16143: 
                   16144: =item
                   16145: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16146: 
                   16147: =over
                   16148: 
                   16149: =item
1.1172.2.44  raeburn  16150: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16151: 
                   16152: =back
                   16153: 
                   16154: =item
                   16155: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16156: for course's uploaded content.
                   16157: 
                   16158: =over
                   16159: 
                   16160: =item
1.1172.2.68  raeburn  16161: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16162: communityquota, textbookquota
1.1172.2.35  raeburn  16163: 
                   16164: =back
                   16165: 
                   16166: =item
                   16167: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16168: on your servers.
                   16169: 
                   16170: =over
                   16171: 
                   16172: =item
                   16173: remotesessions, hostedsessions
                   16174: 
                   16175: =back
                   16176: 
                   16177: =back
                   16178: 
                   16179: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16180: utility to create a configuration.db file on a domain's primary library server
                   16181: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16182: -- corresponding values are authentication type (internal, krb4, krb5,
                   16183: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16184: will be available. Values are retrieved from cache (if current), unless the
                   16185: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16186: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16187: 
                   16188: Typical usage:
1.943     raeburn  16189: 
1.1172.2.35  raeburn  16190: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16191: 
1.243     albertel 16192: =back
                   16193: 
                   16194: =head2 Network Status Functions
                   16195: 
                   16196: =over 4
1.191     harris41 16197: 
                   16198: =item *
                   16199: 
1.1137    raeburn  16200: dirlist() : return directory list based on URI (first arg).
                   16201: 
                   16202: Inputs: 1 required, 5 optional.
                   16203: 
                   16204: =over
                   16205: 
                   16206: =item 
                   16207: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16208: 
                   16209: =item
                   16210: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16211: 
                   16212: =item
                   16213: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16214: 
                   16215: =item
                   16216: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16217: 
                   16218: =item
                   16219: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16220: 
                   16221: =item 
                   16222: $alternateRoot - path to prepend in place of path from $uri.
                   16223: 
                   16224: =back
                   16225: 
                   16226: Returns: Array of up to two items.
                   16227: 
                   16228: =over
                   16229: 
                   16230: a reference to an array of files/subdirectories
                   16231: 
                   16232: =over
                   16233: 
                   16234: Each element in the array of files/subdirectories is a & separated list of
                   16235: item name and the result of running stat on the item.  If dirlist was requested
                   16236: for a file instead of a directory, the item name will be ''. For a directory 
                   16237: listing, if the item is a metadata file, the element will end &N&M 
                   16238: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16239: default copyright set (1).  
                   16240: 
                   16241: =back
                   16242: 
                   16243: a scalar containing error condition (if encountered).
                   16244: 
                   16245: =over
                   16246: 
                   16247: =item 
                   16248: no_host (no homeserver identified for $username:$domain).
                   16249: 
                   16250: =item 
                   16251: no_such_host (server contacted for listing not identified as valid host).
                   16252: 
                   16253: =item 
                   16254: con_lost (connection to remote server failed).
                   16255: 
                   16256: =item 
                   16257: refused (invalid $username:$domain received on lond side).
                   16258: 
                   16259: =item 
                   16260: no_such_dir (directory at specified path on lond side does not exist). 
                   16261: 
                   16262: =item 
                   16263: empty (directory at specified path on lond side is empty).
                   16264: 
                   16265: =over
                   16266: 
                   16267: This is currently not encountered because the &ls3, &ls2, 
                   16268: &ls (_handler) routines on the lond side do not filter out
                   16269: . and .. from a directory listing. 
                   16270: 
                   16271: =back
                   16272: 
                   16273: =back
                   16274: 
                   16275: =back
1.191     harris41 16276: 
                   16277: =item *
                   16278: 
1.243     albertel 16279: spareserver() : find server with least workload from spare.tab
                   16280: 
1.986     foxr     16281: 
                   16282: =item *
                   16283: 
                   16284: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16285: if there is no corresponding loncapa host.
                   16286: 
1.243     albertel 16287: =back
                   16288: 
1.986     foxr     16289: 
1.243     albertel 16290: =head2 Apache Request
                   16291: 
                   16292: =over 4
1.191     harris41 16293: 
                   16294: =item *
                   16295: 
1.243     albertel 16296: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16297: localhost, posts hash
                   16298: 
                   16299: =back
                   16300: 
                   16301: =head2 Data to String to Data
                   16302: 
                   16303: =over 4
1.191     harris41 16304: 
                   16305: =item *
                   16306: 
1.243     albertel 16307: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16308: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16309: 
                   16310: =item *
                   16311: 
1.243     albertel 16312: hashref2str($hashref) : convert a hashref into a string complete with
                   16313: escaping and '=' and '&' separators, supports elements that are
                   16314: arrayrefs and hashrefs
1.191     harris41 16315: 
                   16316: =item *
                   16317: 
1.243     albertel 16318: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16319: with escaping and '&' separators, supports elements that are arrayrefs
                   16320: and hashrefs
1.191     harris41 16321: 
                   16322: =item *
                   16323: 
1.243     albertel 16324: str2hash($string) : convert string to hash using unescaping and
                   16325: splitting on '=' and '&', supports elements that are arrayrefs and
                   16326: hashrefs
1.191     harris41 16327: 
                   16328: =item *
                   16329: 
1.243     albertel 16330: str2array($string) : convert string to hash using unescaping and
                   16331: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16332: 
                   16333: =back
                   16334: 
                   16335: =head2 Logging Routines
                   16336: 
                   16337: 
                   16338: These routines allow one to make log messages in the lonnet.log and
                   16339: lonnet.perm logfiles.
1.191     harris41 16340: 
1.1119    foxr     16341: =over 4
                   16342: 
1.191     harris41 16343: =item *
                   16344: 
1.243     albertel 16345: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16346: 
                   16347: =item *
                   16348: 
1.243     albertel 16349: logthis() : append message to the normal lonnet.log file, it gets
                   16350: preiodically rolled over and deleted.
1.191     harris41 16351: 
                   16352: =item *
                   16353: 
1.243     albertel 16354: logperm() : append a permanent message to lonnet.perm.log, this log
                   16355: file never gets deleted by any automated portion of the system, only
                   16356: messages of critical importance should go in here.
                   16357: 
1.1119    foxr     16358: 
1.243     albertel 16359: =back
                   16360: 
                   16361: =head2 General File Helper Routines
                   16362: 
                   16363: =over 4
1.191     harris41 16364: 
                   16365: =item *
                   16366: 
1.481     raeburn  16367: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16368: (a) files in /uploaded
                   16369:   (i) If a local copy of the file exists - 
                   16370:       compares modification date of local copy with last-modified date for 
                   16371:       definitive version stored on home server for course. If local copy is 
                   16372:       stale, requests a new version from the home server and stores it. 
                   16373:       If the original has been removed from the home server, then local copy 
                   16374:       is unlinked.
                   16375:   (ii) If local copy does not exist -
                   16376:       requests the file from the home server and stores it. 
                   16377:   
                   16378:   If $caller is 'uploadrep':  
                   16379:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16380:     for request for files originally uploaded via DOCS. 
                   16381:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16382:   
                   16383:   Otherwise:
                   16384:      This indicates a call from the content generation phase of the request.
                   16385:      -  returns the entire contents of the file or -1.
                   16386:      
                   16387: (b) files in /res
                   16388:    - returns the entire contents of a file or -1; 
                   16389:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16390: 
1.712     albertel 16391: 
                   16392: =item *
                   16393: 
                   16394: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16395:                   reference
                   16396: 
                   16397: returns either a stat() list of data about the file or an empty list
                   16398: if the file doesn't exist or couldn't find out about it (connection
                   16399: problems or user unknown)
                   16400: 
1.191     harris41 16401: =item *
                   16402: 
1.243     albertel 16403: filelocation($dir,$file) : returns file system location of a file
                   16404: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16405: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16406: and a file of ../bob will become /a/bob)
1.191     harris41 16407: 
                   16408: =item *
                   16409: 
                   16410: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16411: filelocation except for hrefs
                   16412: 
                   16413: =item *
                   16414: 
1.1172.2.49  raeburn  16415: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16416: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16417: 
1.243     albertel 16418: =back
                   16419: 
1.608     albertel 16420: =head2 Usererfile file routines (/uploaded*)
                   16421: 
                   16422: =over 4
                   16423: 
                   16424: =item *
                   16425: 
                   16426: userfileupload(): main rotine for putting a file in a user or course's
                   16427:                   filespace, arguments are,
                   16428: 
1.620     albertel 16429:  formname - required - this is the name of the element in $env where the
1.608     albertel 16430:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16431:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16432:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16433:  context - if coursedoc, store the file in the course of the active role
                   16434:              of the current user; 
                   16435:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16436:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16437:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16438:          if undefined, it will be placed in "unknown"
                   16439: 
                   16440:  (This routine calls clean_filename() to remove any dangerous
                   16441:  characters from the filename, and then calls finuserfileupload() to
                   16442:  complete the transaction)
                   16443: 
                   16444:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16445:  and /adm/notfound.html if unsuccessful
                   16446: 
                   16447: =item *
                   16448: 
                   16449: clean_filename(): routine for cleaing a filename up for storage in
                   16450:                  userfile space, argument is:
                   16451: 
                   16452:  filename - proposed filename
                   16453: 
                   16454: returns: the new clean filename
                   16455: 
                   16456: =item *
                   16457: 
1.1090    raeburn  16458: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16459: userspace, probably shouldn't be called directly
                   16460: 
                   16461:   docuname: username or courseid of destination for the file
                   16462:   docudom: domain of user/course of destination for the file
                   16463:   formname: same as for userfileupload()
1.1090    raeburn  16464:   fname: filename (including subdirectories) for the file
                   16465:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16466:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16467:   allfiles: reference to hash used to store objects found by parser
                   16468:   codebase: reference to hash used for codebases of java objects found by parser
                   16469:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16470:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16471:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16472:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16473:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16474:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16475:   mimetype: reference to scalar to accommodate mime type determined
                   16476:             from File::MMagic if $parser = parse.
1.608     albertel 16477: 
                   16478:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16479:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16480:  was 'overwrite').
                   16481:  
1.608     albertel 16482: 
                   16483: =item *
                   16484: 
                   16485: renameuserfile(): renames an existing userfile to a new name
                   16486: 
                   16487:   Args:
                   16488:    docuname: username or courseid of destination for the file
                   16489:    docudom: domain of user/course of destination for the file
                   16490:    old: current file name (including any subdirs under userfiles)
                   16491:    new: desired file name (including any subdirs under userfiles)
                   16492: 
                   16493: =item *
                   16494: 
                   16495: mkdiruserfile(): creates a directory is a userfiles dir
                   16496: 
                   16497:   Args:
                   16498:    docuname: username or courseid of destination for the file
                   16499:    docudom: domain of user/course of destination for the file
                   16500:    dir: dir to create (including any subdirs under userfiles)
                   16501: 
                   16502: =item *
                   16503: 
                   16504: removeuserfile(): removes a file that exists in userfiles
                   16505: 
                   16506:   Args:
                   16507:    docuname: username or courseid of destination for the file
                   16508:    docudom: domain of user/course of destination for the file
                   16509:    fname: filname to delete (including any subdirs under userfiles)
                   16510: 
                   16511: =item *
                   16512: 
                   16513: removeuploadedurl(): convience function for removeuserfile()
                   16514: 
                   16515:   Args:
                   16516:    url:  a full /uploaded/... url to delete
                   16517: 
1.747     albertel 16518: =item * 
                   16519: 
                   16520: get_portfile_permissions():
                   16521:   Args:
                   16522:     domain: domain of user or course contain the portfolio files
                   16523:     user: name of user or num of course contain the portfolio files
                   16524:   Returns:
                   16525:     hashref of a dump of the proper file_permissions.db
                   16526:    
                   16527: 
                   16528: =item * 
                   16529: 
                   16530: get_access_controls():
                   16531: 
                   16532: Args:
                   16533:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16534:   group: (optional) the group you want the files associated with
                   16535:   file: (optional) the file you want access info on
                   16536: 
                   16537: Returns:
1.749     raeburn  16538:     a hash (keys are file names) of hashes containing
                   16539:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16540:         values are XML containing access control settings (see below) 
1.747     albertel 16541: 
                   16542: Internal notes:
                   16543: 
1.749     raeburn  16544:  access controls are stored in file_permissions.db as key=value pairs.
                   16545:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16546:         where scope -> public,guest,course,group,domains or users.
                   16547:               end -> UNIX time for end of access (0 -> no end date)
                   16548:               start -> UNIX time for start of access
                   16549: 
                   16550:     value -> XML description of access control
                   16551:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16552:             <start></start>
                   16553:             <end></end>
                   16554: 
                   16555:             <password></password>  for scope type = guest
                   16556: 
                   16557:             <domain></domain>     for scope type = course or group
                   16558:             <number></number>
                   16559:             <roles id="">
                   16560:              <role></role>
                   16561:              <access></access>
                   16562:              <section></section>
                   16563:              <group></group>
                   16564:             </roles>
                   16565: 
                   16566:             <dom></dom>         for scope type = domains
                   16567: 
                   16568:             <users>             for scope type = users
                   16569:              <user>
                   16570:               <uname></uname>
                   16571:               <udom></udom>
                   16572:              </user>
                   16573:             </users>
                   16574:            </scope> 
                   16575:               
                   16576:  Access data is also aggregated for each file in an additional key=value pair:
                   16577:  key -> path to file/file_name\0accesscontrol 
                   16578:  value -> reference to hash
                   16579:           hash contains key = value pairs
                   16580:           where key = uniqueID:scope_end_start
                   16581:                 value = UNIX time record was last updated
                   16582: 
                   16583:           Used to improve speed of look-ups of access controls for each file.  
                   16584:  
                   16585:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16586: 
1.1172.2.13  raeburn  16587: =item *
                   16588: 
1.749     raeburn  16589: modify_access_controls():
                   16590: 
                   16591: Modifies access controls for a portfolio file
                   16592: Args
                   16593: 1. file name
                   16594: 2. reference to hash of required changes,
                   16595: 3. domain
                   16596: 4. username
                   16597:   where domain,username are the domain of the portfolio owner 
                   16598:   (either a user or a course) 
                   16599: 
                   16600: Returns:
                   16601: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16602: 2. result of deletions ('ok' or 'error', with error message).
                   16603: 3. reference to hash of any new or updated access controls.
                   16604: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16605:    key = integer (inbound ID)
1.1172.2.13  raeburn  16606:    value = uniqueID
                   16607: 
                   16608: =item *
                   16609: 
                   16610: get_timebased_id():
                   16611: 
                   16612: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16613: course via the Course Editor (e.g., folders, composite pages,
                   16614: group bulletin boards).
                   16615: 
                   16616: Args: (first three required; six others optional)
                   16617: 
                   16618: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16619:    docssequence, or name of group
                   16620: 
                   16621: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16622:    e.g., num, boardids
                   16623: 
                   16624: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16625:    file will be named nohist_namespace.db
                   16626: 
                   16627: 4. cdom: domain of course; default is current course domain from %env
                   16628: 
                   16629: 5. cnum: course number; default is current course number from %env
                   16630: 
                   16631: 6. idtype: set to concat if an additional digit is to be appended to the
                   16632:    unix timestamp to form the suffix, if the plain timestamp is already
                   16633:    in use.  Default is to not do this, but simply increment the unix
                   16634:    timestamp by 1 until a unique key is obtained.
                   16635: 
                   16636: 7. who: holder of locking key; defaults to user:domain for user.
                   16637: 
                   16638: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16639:    retrying); default is 3.
                   16640: 
                   16641: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16642: 
                   16643: Returns:
                   16644: 
                   16645: 1. suffix obtained (numeric)
                   16646: 
                   16647: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16648: 
                   16649: 3. error: contains (localized) error message if an error occurred.
                   16650: 
1.747     albertel 16651: 
1.608     albertel 16652: =back
                   16653: 
1.243     albertel 16654: =head2 HTTP Helper Routines
                   16655: 
                   16656: =over 4
                   16657: 
1.191     harris41 16658: =item *
                   16659: 
                   16660: escape() : unpack non-word characters into CGI-compatible hex codes
                   16661: 
                   16662: =item *
                   16663: 
                   16664: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16665: 
1.243     albertel 16666: =back
                   16667: 
                   16668: =head1 PRIVATE SUBROUTINES
                   16669: 
                   16670: =head2 Underlying communication routines (Shouldn't call)
                   16671: 
                   16672: =over 4
                   16673: 
                   16674: =item *
                   16675: 
                   16676: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16677: 
                   16678: =item *
                   16679: 
                   16680: reply() : uses subreply to send a message to remote machine, logs all failures
                   16681: 
                   16682: =item *
                   16683: 
                   16684: critical() : passes a critical message to another server; if cannot
                   16685: get through then place message in connection buffer directory and
                   16686: returns con_delayed, if incapable of saving message, returns
                   16687: con_failed
                   16688: 
                   16689: =item *
                   16690: 
                   16691: reconlonc() : tries to reconnect lonc client processes.
                   16692: 
                   16693: =back
                   16694: 
                   16695: =head2 Resource Access Logging
                   16696: 
                   16697: =over 4
                   16698: 
                   16699: =item *
                   16700: 
                   16701: flushcourselogs() : flush (save) buffer logs and access logs
                   16702: 
                   16703: =item *
                   16704: 
                   16705: courselog($what) : save message for course in hash
                   16706: 
                   16707: =item *
                   16708: 
                   16709: courseacclog($what) : save message for course using &courselog().  Perform
                   16710: special processing for specific resource types (problems, exams, quizzes, etc).
                   16711: 
1.191     harris41 16712: =item *
                   16713: 
                   16714: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16715: as a PerlChildExitHandler
1.243     albertel 16716: 
                   16717: =back
                   16718: 
                   16719: =head2 Other
                   16720: 
                   16721: =over 4
                   16722: 
                   16723: =item *
                   16724: 
                   16725: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16726: 
                   16727: =back
                   16728: 
                   16729: =cut
1.877     foxr     16730: 

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