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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .7(raebu    4:22): # $Id: lonnet.pm,v 1.1172.2.146.2.6 2022/09/19 20:51:17 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.1172.2.146.  .6(raebu 1312:22): sub can_switchserver {
                   1313:22):     my ($udom,$home) = @_;
                   1314:22):     my ($canswitch,@intdoms);
                   1315:22):     my $internet_names = &get_internet_names($home);
                   1316:22):     if (ref($internet_names) eq 'ARRAY') {
                   1317:22):         @intdoms = @{$internet_names};
                   1318:22):     }
                   1319:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1320:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1321:22):         $canswitch = 1;
                   1322:22):     } else {
                   1323:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1324:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1325:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1326:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1327:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1328:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1329:22):                                         $udomdefaults{'remotesessions'},
                   1330:22):                                         $defdomdefaults{'hostedsessions'});
                   1331:22):     }
                   1332:22):     return $canswitch;
                   1333:22): }
                   1334:22): 
1.1073    raeburn  1335: sub can_host_session {
1.1074    raeburn  1336:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1337:     my $canhost = 1;
1.1074    raeburn  1338:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1339:     if (ref($remotesessions) eq 'HASH') {
                   1340:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1341:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1342:                 $canhost = 0;
                   1343:             } else {
                   1344:                 $canhost = 1;
                   1345:             }
                   1346:         }
                   1347:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1348:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1349:                 $canhost = 1;
                   1350:             } else {
                   1351:                 $canhost = 0;
                   1352:             }
                   1353:         }
                   1354:         if ($canhost) {
                   1355:             if ($remotesessions->{'version'} ne '') {
                   1356:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1357:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1358:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1359:                         my $major = $1;
                   1360:                         my $minor = $2;
                   1361:                         if (($major < $reqmajor ) ||
                   1362:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1363:                             $canhost = 0;
                   1364:                         }
                   1365:                     } else {
                   1366:                         $canhost = 0;
                   1367:                     }
                   1368:                 }
                   1369:             }
                   1370:         }
                   1371:     }
                   1372:     if ($canhost) {
                   1373:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1374:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1375:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1376:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1377:                 if (($uint_dom ne '') && 
                   1378:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1379:                     $canhost = 0;
                   1380:                 } else {
                   1381:                     $canhost = 1;
                   1382:                 }
                   1383:             }
                   1384:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1385:                 if (($uint_dom ne '') && 
                   1386:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1387:                     $canhost = 1;
                   1388:                 } else {
                   1389:                     $canhost = 0;
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     return $canhost;
                   1395: }
                   1396: 
1.1083    raeburn  1397: sub spare_can_host {
                   1398:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1399:     my $canhost=1;
1.1172.2.62  raeburn  1400:     my $try_server_hostname = &hostname($try_server);
                   1401:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1402:     my $serverhomedom = &host_domain($serverhomeID);
                   1403:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1404:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1405:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1406:             $canhost = 0;
                   1407:         }
                   1408:     }
1.1172.2.136  raeburn  1409:     if ($canhost) {
                   1410:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1411:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1412:                 unless (&shared_institution($udom,$try_server)) {
                   1413:                     $canhost = 0;
                   1414:                 }
                   1415:             }
                   1416:         }
                   1417:     }
1.1172.2.62  raeburn  1418:     if (($canhost) && ($uint_dom)) {
                   1419:         my @intdoms;
                   1420:         my $internet_names = &get_internet_names($try_server);
                   1421:         if (ref($internet_names) eq 'ARRAY') {
                   1422:             @intdoms = @{$internet_names};
                   1423:         }
                   1424:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1425:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1426:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1427:                                          $remotesessions,
                   1428:                                          $defdomdefaults{'hostedsessions'});
                   1429:         }
1.1083    raeburn  1430:     }
                   1431:     return $canhost;
                   1432: }
                   1433: 
1.1123    raeburn  1434: sub this_host_spares {
                   1435:     my ($dom) = @_;
1.1126    raeburn  1436:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1437:     my @hosts = &current_machine_ids();
                   1438:     foreach my $lonhost (@hosts) {
                   1439:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1440:             $dom_in_use = $dom;
                   1441:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1442:             last;
                   1443:         }
                   1444:     }
1.1126    raeburn  1445:     if ($dom_in_use ne '') {
                   1446:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1447:     }
                   1448:     if (ref($result) ne 'HASH') {
                   1449:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1450:         $dom_in_use = &host_domain($lonhost_in_use);
                   1451:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1452:         if (ref($result) ne 'HASH') {
                   1453:             $result = \%spareid;
                   1454:         }
                   1455:     }
                   1456:     return $result;
                   1457: }
                   1458: 
                   1459: sub spares_for_offload  {
                   1460:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1461:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1462:     if (defined($cached)) {
                   1463:         return $result;
                   1464:     } else {
1.1126    raeburn  1465:         my $cachetime = 60*60*24;
                   1466:         my %domconfig =
                   1467:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1468:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1469:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1470:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1471:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1472:                 }
                   1473:             }
                   1474:         }
                   1475:     }
1.1126    raeburn  1476:     return;
1.1123    raeburn  1477: }
                   1478: 
1.1129    raeburn  1479: sub get_lonbalancer_config {
                   1480:     my ($servers) = @_;
                   1481:     my ($currbalancer,$currtargets);
                   1482:     if (ref($servers) eq 'HASH') {
                   1483:         foreach my $server (keys(%{$servers})) {
                   1484:             my %what = (
                   1485:                          spareid => 1,
                   1486:                          perlvar => 1,
                   1487:                        );
                   1488:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1489:             if ($result eq 'ok') {
                   1490:                 if (ref($returnhash) eq 'HASH') {
                   1491:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1492:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1493:                             $currbalancer = $server;
                   1494:                             $currtargets = {};
                   1495:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1496:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1497:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1498:                                 }
                   1499:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1500:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1501:                                 }
                   1502:                             }
                   1503:                             last;
                   1504:                         }
                   1505:                     }
                   1506:                 }
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return ($currbalancer,$currtargets);
                   1511: }
                   1512: 
                   1513: sub check_loadbalancing {
1.1172.2.88  raeburn  1514:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1515:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1516:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1517:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1518:     my @hosts = &current_machine_ids();
1.1129    raeburn  1519:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1520:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1521:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1522:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1523:     my $domneedscache; 
1.1129    raeburn  1524:     my $cachetime = 60*60*24;
                   1525: 
                   1526:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1527:         $dom_in_use = $udom;
                   1528:         $homeintdom = 1;
                   1529:     } else {
                   1530:         $dom_in_use = $serverhomedom;
                   1531:     }
                   1532:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1533:     unless (defined($cached)) {
                   1534:         my %domconfig =
                   1535:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1536:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1537:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1538:         } else {
                   1539:             $domneedscache = $dom_in_use;
1.1129    raeburn  1540:         }
                   1541:     }
                   1542:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1543:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1544:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1545:         if ($is_balancer) {
                   1546:             if (ref($currrules) eq 'HASH') {
                   1547:                 if ($homeintdom) {
                   1548:                     if ($uname ne '') {
                   1549:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1550:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1551:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1552:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1553:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1554:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1555:                             }
                   1556:                         }
                   1557:                         if ($rule_in_effect eq '') {
                   1558:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1559:                             if ($userenv{'inststatus'} ne '') {
                   1560:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1561:                                 my ($othertitle,$usertypes,$types) =
                   1562:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1563:                                 if (ref($types) eq 'ARRAY') {
                   1564:                                     foreach my $type (@{$types}) {
                   1565:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1566:                                             if (exists($currrules->{$type})) {
                   1567:                                                 $rule_in_effect = $currrules->{$type};
                   1568:                                             }
                   1569:                                         }
                   1570:                                     }
                   1571:                                 }
                   1572:                             } else {
                   1573:                                 if (exists($currrules->{'default'})) {
                   1574:                                     $rule_in_effect = $currrules->{'default'};
                   1575:                                 }
                   1576:                             }
                   1577:                         }
                   1578:                     } else {
                   1579:                         if (exists($currrules->{'default'})) {
                   1580:                             $rule_in_effect = $currrules->{'default'};
                   1581:                         }
                   1582:                     }
                   1583:                 } else {
                   1584:                     if ($currrules->{'_LC_external'} ne '') {
                   1585:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1586:                     }
                   1587:                 }
                   1588:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1589:                                                        $uname,$udom);
                   1590:             }
                   1591:         }
                   1592:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1593:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1594:         unless (defined($cached)) {
                   1595:             my %domconfig =
                   1596:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1597:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1598:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1599:             } else {
                   1600:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1601:             }
                   1602:         }
                   1603:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1604:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1605:                 &check_balancer_result($result,@hosts);
                   1606:             if ($is_balancer) {
1.1129    raeburn  1607:                 if (ref($currrules) eq 'HASH') {
                   1608:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1609:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1610:                     }
                   1611:                 }
                   1612:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1613:                                                        $uname,$udom);
                   1614:             }
                   1615:         } else {
                   1616:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1617:                 $is_balancer = 1;
                   1618:                 $offloadto = &this_host_spares($dom_in_use);
                   1619:             }
1.1172.2.75  raeburn  1620:             unless (defined($cached)) {
                   1621:                 $domneedscache = $serverhomedom;
                   1622:             }
1.1129    raeburn  1623:         }
                   1624:     } else {
                   1625:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1626:             $is_balancer = 1;
                   1627:             $offloadto = &this_host_spares($dom_in_use);
                   1628:         }
1.1172.2.75  raeburn  1629:         unless (defined($cached)) {
                   1630:             $domneedscache = $serverhomedom;
                   1631:         }
                   1632:     }
                   1633:     if ($domneedscache) {
                   1634:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1635:     }
1.1172.2.130  raeburn  1636:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1637:         my $lowest_load = 30000;
                   1638:         if (ref($offloadto) eq 'HASH') {
                   1639:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1640:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1641:                     ($otherserver,$lowest_load) =
                   1642:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1643:                 }
1.1129    raeburn  1644:             }
1.1172.2.5  raeburn  1645:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1646: 
1.1172.2.5  raeburn  1647:             if (!$found_server) {
                   1648:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1649:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1650:                         ($otherserver,$lowest_load) =
                   1651:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1652:                     }
                   1653:                 }
                   1654:             }
                   1655:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1656:             if (@{$offloadto} == 1) {
                   1657:                 $otherserver = $offloadto->[0];
                   1658:             } elsif (@{$offloadto} > 1) {
                   1659:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1660:                     ($otherserver,$lowest_load) =
                   1661:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1662:                 }
                   1663:             }
                   1664:         }
1.1172.2.88  raeburn  1665:         unless ($caller eq 'login') {
                   1666:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1667:                 $is_balancer = 0;
                   1668:                 if ($uname ne '' && $udom ne '') {
                   1669:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1670:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1671:                                  'user.loadbalcheck.time' => time});
                   1672:                     }
1.1172.2.5  raeburn  1673:                 }
1.1129    raeburn  1674:             }
                   1675:         }
1.1172.2.130  raeburn  1676:     }
                   1677:     if (($is_balancer) && (!$homeintdom)) {
                   1678:         undef($setcookie);
1.1129    raeburn  1679:     }
1.1172.2.107  raeburn  1680:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1681: }
                   1682: 
1.1172.2.12  raeburn  1683: sub check_balancer_result {
                   1684:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1685:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1686:     if (ref($result) eq 'HASH') {
                   1687:         if ($result->{'lonhost'} ne '') {
                   1688:             my $currbalancer = $result->{'lonhost'};
                   1689:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1690:                 $is_balancer = 1;
                   1691:                 $currtargets = $result->{'targets'};
                   1692:                 $currrules = $result->{'rules'};
                   1693:             }
                   1694:         } else {
                   1695:             foreach my $key (keys(%{$result})) {
                   1696:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1697:                     (ref($result->{$key}) eq 'HASH')) {
                   1698:                     $is_balancer = 1;
                   1699:                     $currrules = $result->{$key}{'rules'};
                   1700:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1701:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1702:                     last;
                   1703:                 }
                   1704:             }
                   1705:         }
                   1706:     }
1.1172.2.107  raeburn  1707:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1708: }
                   1709: 
1.1129    raeburn  1710: sub get_loadbalancer_targets {
                   1711:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1712:     my $offloadto;
1.1172.2.4  raeburn  1713:     if ($rule_in_effect eq 'none') {
                   1714:         return [$perlvar{'lonHostID'}];
                   1715:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1716:         $offloadto = $currtargets;
                   1717:     } else {
                   1718:         if ($rule_in_effect eq 'homeserver') {
                   1719:             my $homeserver = &homeserver($uname,$udom);
                   1720:             if ($homeserver ne 'no_host') {
                   1721:                 $offloadto = [$homeserver];
                   1722:             }
                   1723:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1724:             my %domconfig =
                   1725:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1726:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1727:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1728:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1729:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1730:                     }
                   1731:                 }
                   1732:             } else {
1.1172.2.7  raeburn  1733:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1734:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1735:                 if (&hostname($remotebalancer) ne '') {
                   1736:                     $offloadto = [$remotebalancer];
                   1737:                 }
                   1738:             }
                   1739:         } elsif (&hostname($rule_in_effect) ne '') {
                   1740:             $offloadto = [$rule_in_effect];
                   1741:         }
                   1742:     }
                   1743:     return $offloadto;
                   1744: }
                   1745: 
1.1127    raeburn  1746: sub internet_dom_servers {
                   1747:     my ($dom) = @_;
                   1748:     my (%uniqservers,%servers);
                   1749:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1750:     my @machinedoms = &machine_domains($primaryserver);
                   1751:     foreach my $mdom (@machinedoms) {
                   1752:         my %currservers = %servers;
                   1753:         my %server = &get_servers($mdom);
                   1754:         %servers = (%currservers,%server);
                   1755:     }
                   1756:     my %by_hostname;
                   1757:     foreach my $id (keys(%servers)) {
                   1758:         push(@{$by_hostname{$servers{$id}}},$id);
                   1759:     }
                   1760:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1761:         if (@{$by_hostname{$hostname}} > 1) {
                   1762:             my $match = 0;
                   1763:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1764:                 if (&host_domain($id) eq $dom) {
                   1765:                     $uniqservers{$id} = $hostname;
                   1766:                     $match = 1;
                   1767:                 }
                   1768:             }
                   1769:             unless ($match) {
                   1770:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1771:             }
                   1772:         } else {
                   1773:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1774:         }
                   1775:     }
                   1776:     return %uniqservers;
                   1777: }
                   1778: 
1.1       albertel 1779: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1780: 
1.599     albertel 1781: my %homecache;
1.1       albertel 1782: sub homeserver {
1.230     stredwic 1783:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1784:     my $index="$uname:$udom";
1.426     albertel 1785: 
1.599     albertel 1786:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1787: 
                   1788:     my %servers = &get_servers($udom,'library');
                   1789:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1790:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1791: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1792: 
                   1793: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1794: 	if ($answer eq 'found') {
                   1795: 	    delete($badServerCache{$tryserver}); 
                   1796: 	    return $homecache{$index}=$tryserver;
                   1797: 	} elsif ($answer eq 'no_host') {
                   1798: 	    $badServerCache{$tryserver}=1;
                   1799: 	}
1.1       albertel 1800:     }    
                   1801:     return 'no_host';
1.70      www      1802: }
                   1803: 
                   1804: # ------------------------------------- Find the usernames behind a list of IDs
                   1805: 
                   1806: sub idget {
                   1807:     my ($udom,@ids)=@_;
                   1808:     my %returnhash=();
                   1809:     
1.841     albertel 1810:     my %servers = &get_servers($udom,'library');
                   1811:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1812: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1813: 	$idlist=~tr/A-Z/a-z/; 
                   1814: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1815: 	my @answer=();
                   1816: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1817: 	    @answer=split(/\&/,$reply);
                   1818: 	}                    ;
                   1819: 	my $i;
                   1820: 	for ($i=0;$i<=$#ids;$i++) {
                   1821: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1822: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1823: 	    } 
                   1824: 	}
                   1825:     } 
1.70      www      1826:     return %returnhash;
                   1827: }
                   1828: 
                   1829: # ------------------------------------- Find the IDs behind a list of usernames
                   1830: 
                   1831: sub idrget {
                   1832:     my ($udom,@unames)=@_;
                   1833:     my %returnhash=();
1.800     albertel 1834:     foreach my $uname (@unames) {
                   1835:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1836:     }
1.70      www      1837:     return %returnhash;
                   1838: }
                   1839: 
                   1840: # ------------------------------- Store away a list of names and associated IDs
                   1841: 
                   1842: sub idput {
                   1843:     my ($udom,%ids)=@_;
                   1844:     my %servers=();
1.800     albertel 1845:     foreach my $uname (keys(%ids)) {
                   1846: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1847:         my $uhom=&homeserver($uname,$udom);
1.70      www      1848:         if ($uhom ne 'no_host') {
1.800     albertel 1849:             my $id=&escape($ids{$uname});
1.70      www      1850:             $id=~tr/A-Z/a-z/;
1.800     albertel 1851:             my $esc_unam=&escape($uname);
1.70      www      1852: 	    if ($servers{$uhom}) {
1.800     albertel 1853: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1854:             } else {
1.800     albertel 1855:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1856:             }
                   1857:         }
1.191     harris41 1858:     }
1.800     albertel 1859:     foreach my $server (keys(%servers)) {
                   1860:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1861:     }
1.344     www      1862: }
                   1863: 
1.1172.2.30  raeburn  1864: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1865: 
                   1866: sub iddel {
                   1867:     my ($udom,$idshashref,$uhome)=@_;
                   1868:     my %result=();
                   1869:     unless (ref($idshashref) eq 'HASH') {
                   1870:         return %result;
                   1871:     }
                   1872:     my %servers=();
                   1873:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1874:         my $uhom;
                   1875:         if ($uhome) {
                   1876:             $uhom = $uhome;
                   1877:         } else {
                   1878:             $uhom=&homeserver($uname,$udom);
                   1879:         }
                   1880:         if ($uhom ne 'no_host') {
                   1881:             if ($servers{$uhom}) {
                   1882:                 $servers{$uhom}.='&'.&escape($id);
                   1883:             } else {
                   1884:                 $servers{$uhom}=&escape($id);
                   1885:             }
                   1886:         }
                   1887:     }
                   1888:     foreach my $server (keys(%servers)) {
                   1889:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1890:     }
                   1891:     return %result;
                   1892: }
                   1893: 
1.1023    raeburn  1894: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1895: sub dump_dom {
1.1165    droeschl 1896:     my ($namespace, $udom, $regexp) = @_;
                   1897: 
                   1898:     $udom ||= $env{'user.domain'};
                   1899: 
                   1900:     return () unless $udom;
                   1901: 
                   1902:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1903: }
                   1904: 
1.1023    raeburn  1905: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1906: 
                   1907: sub get_dom {
1.1172.2.146.  .1(raebu 1908:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1909:     return if ($udom eq 'public');
1.806     raeburn  1910:     my $items='';
                   1911:     foreach my $item (@$storearr) {
                   1912:         $items.=&escape($item).'&';
                   1913:     }
                   1914:     $items=~s/\&$//;
1.860     raeburn  1915:     if (!$udom) {
                   1916:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1917:         return if ($udom eq 'public');
1.860     raeburn  1918:         if (defined(&domain($udom,'primary'))) {
                   1919:             $uhome=&domain($udom,'primary');
                   1920:         } else {
1.874     albertel 1921:             undef($uhome);
1.860     raeburn  1922:         }
                   1923:     } else {
                   1924:         if (!$uhome) {
                   1925:             if (defined(&domain($udom,'primary'))) {
                   1926:                 $uhome=&domain($udom,'primary');
                   1927:             }
                   1928:         }
                   1929:     }
                   1930:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  1931:         my $rep;
                   1932:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1933:             # domain information is hosted on this machine
                   1934:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 1935:22):         } else {
                   1936:22):             if ($encrypt) {
                   1937:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1938:22):             } else {
                   1939:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1940:22):             }
1.1172.2.139  raeburn  1941:         }
1.866     raeburn  1942:         my %returnhash;
1.875     albertel 1943:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1944:             return %returnhash;
                   1945:         }
1.806     raeburn  1946:         my @pairs=split(/\&/,$rep);
                   1947:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1948:             return @pairs;
                   1949:         }
                   1950:         my $i=0;
                   1951:         foreach my $item (@$storearr) {
                   1952:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1953:             $i++;
                   1954:         }
                   1955:         return %returnhash;
                   1956:     } else {
1.880     banghart 1957:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1958:     }
                   1959: }
                   1960: 
                   1961: # -------------------------------------------- put items in domain db files 
                   1962: 
                   1963: sub put_dom {
1.1172.2.146.  .1(raebu 1964:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  1965:     if (!$udom) {
                   1966:         $udom=$env{'user.domain'};
                   1967:         if (defined(&domain($udom,'primary'))) {
                   1968:             $uhome=&domain($udom,'primary');
                   1969:         } else {
1.874     albertel 1970:             undef($uhome);
1.860     raeburn  1971:         }
                   1972:     } else {
                   1973:         if (!$uhome) {
                   1974:             if (defined(&domain($udom,'primary'))) {
                   1975:                 $uhome=&domain($udom,'primary');
                   1976:             }
                   1977:         }
                   1978:     } 
                   1979:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1980:         my $items='';
                   1981:         foreach my $item (keys(%$storehash)) {
                   1982:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1983:         }
                   1984:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 1985:22):         if ($encrypt) {
                   1986:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1987:22):         } else {
                   1988:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1989:22):         }
1.806     raeburn  1990:     } else {
1.860     raeburn  1991:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1992:     }
                   1993: }
                   1994: 
1.1023    raeburn  1995: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1996: sub newput_dom {
1.1023    raeburn  1997:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1998:     my $result;
                   1999:     if (!$udom) {
                   2000:         $udom=$env{'user.domain'};
                   2001:     }
1.1023    raeburn  2002:     if ($udom) {
                   2003:         my $uname = &get_domainconfiguser($udom);
                   2004:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2005:     }
                   2006:     return $result;
                   2007: }
                   2008: 
1.1023    raeburn  2009: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2010: sub del_dom {
1.1023    raeburn  2011:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2012:     if (ref($storearr) eq 'ARRAY') {
                   2013:         if (!$udom) {
                   2014:             $udom=$env{'user.domain'};
                   2015:         }
1.1023    raeburn  2016:         if ($udom) {
                   2017:             my $uname = &get_domainconfiguser($udom); 
                   2018:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2019:         }
                   2020:     }
                   2021: }
                   2022: 
1.1172.2.146.  .4(raebu 2023:22): sub store_dom {
                   2024:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2025:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2026:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2027:22):     my $namevalue='';
                   2028:22):     foreach my $key (keys(%{$storehash})) {
                   2029:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2030:22):     }
                   2031:22):     $namevalue=~s/\&$//;
                   2032:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2033:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2034:22):     } else {
                   2035:22):         if ($namespace eq 'private') {
                   2036:22):             return 'refused';
                   2037:22):         } elsif ($encrypt) {
                   2038:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2039:22):         } else {
                   2040:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2041:22):         }
                   2042:22):     }
                   2043:22): }
                   2044:22): 
                   2045:22): sub restore_dom {
                   2046:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2047:22):     my $answer;
                   2048:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2049:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2050:22):     } elsif ($namespace ne 'private') {
                   2051:22):         if ($encrypt) {
                   2052:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2053:22):         } else {
                   2054:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2055:22):         }
                   2056:22):     }
                   2057:22):     my %returnhash=();
                   2058:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2059:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2060:22):         foreach my $line (split(/\&/,$answer)) {
                   2061:22):             my ($name,$value)=split(/\=/,$line);
                   2062:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2063:22):         }
                   2064:22):         my $version;
                   2065:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2066:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2067:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2068:22):             }
                   2069:22):         }
                   2070:22):     }
                   2071:22):     return %returnhash;
                   2072:22): }
                   2073:22): 
1.1023    raeburn  2074: # ----------------------------------construct domainconfig user for a domain 
                   2075: sub get_domainconfiguser {
                   2076:     my ($udom) = @_;
                   2077:     return $udom.'-domainconfig';
                   2078: }
                   2079: 
1.837     raeburn  2080: sub retrieve_inst_usertypes {
                   2081:     my ($udom) = @_;
                   2082:     my (%returnhash,@order);
1.989     raeburn  2083:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2084:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2085:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2086:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2087:     } else {
                   2088:         if (defined(&domain($udom,'primary'))) {
                   2089:             my $uhome=&domain($udom,'primary');
                   2090:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2091:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2092:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2093:                 return (\%returnhash,\@order);
                   2094:             }
                   2095:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2096:             my @pairs=split(/\&/,$hashitems);
                   2097:             foreach my $item (@pairs) {
                   2098:                 my ($key,$value)=split(/=/,$item,2);
                   2099:                 $key = &unescape($key);
                   2100:                 next if ($key =~ /^error: 2 /);
                   2101:                 $returnhash{$key}=&thaw_unescape($value);
                   2102:             }
                   2103:             my @esc_order = split(/\&/,$orderitems);
                   2104:             foreach my $item (@esc_order) {
                   2105:                 push(@order,&unescape($item));
                   2106:             }
                   2107:         } else {
1.1172.2.44  raeburn  2108:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2109:         }
1.1172.2.44  raeburn  2110:         return (\%returnhash,\@order);
1.837     raeburn  2111:     }
                   2112: }
                   2113: 
1.868     raeburn  2114: sub is_domainimage {
                   2115:     my ($url) = @_;
1.1172.2.142  raeburn  2116:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2117:         if (&domain($1) ne '') {
                   2118:             return '1';
                   2119:         }
                   2120:     }
                   2121:     return;
                   2122: }
                   2123: 
1.899     raeburn  2124: sub inst_directory_query {
                   2125:     my ($srch) = @_;
                   2126:     my $udom = $srch->{'srchdomain'};
                   2127:     my %results;
                   2128:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2129:     my $outcome;
1.899     raeburn  2130:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2131:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2132:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2133:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2134:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2135:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2136:                     (($major == 2) && ($minor < 11)) ||
                   2137:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2138:                     return;
                   2139:                 }
                   2140:             }
                   2141:         }
1.904     albertel 2142: 	my $queryid=&reply("querysend:instdirsearch:".
                   2143: 			   &escape($srch->{'srchby'}).':'.
                   2144: 			   &escape($srch->{'srchterm'}).':'.
                   2145: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2146: 	my $host=&hostname($homeserver);
                   2147: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2148: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2149: 	    return;
                   2150: 	}
                   2151: 	my $response = &get_query_reply($queryid);
                   2152: 	my $maxtries = 5;
                   2153: 	my $tries = 1;
                   2154: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2155: 	    $response = &get_query_reply($queryid);
                   2156: 	    $tries ++;
                   2157: 	}
                   2158: 
                   2159:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2160:             if ($response eq 'unavailable') {
                   2161:                 $outcome = $response;
                   2162:             } else {
                   2163:                 $outcome = 'ok';
                   2164:                 my @matches = split(/\n/,$response);
                   2165:                 foreach my $match (@matches) {
                   2166:                     my ($key,$value) = split(/=/,$match);
                   2167:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2168:                 }
1.899     raeburn  2169:             }
                   2170:         }
                   2171:     }
1.909     raeburn  2172:     return ($outcome,%results);
1.899     raeburn  2173: }
                   2174: 
                   2175: sub usersearch {
                   2176:     my ($srch) = @_;
                   2177:     my $dom = $srch->{'srchdomain'};
                   2178:     my %results;
                   2179:     my %libserv = &all_library();
                   2180:     my $query = 'usersearch';
                   2181:     foreach my $tryserver (keys(%libserv)) {
                   2182:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2183:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2184:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2185:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2186:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2187:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2188:                              (($major == 2) && ($minor < 11)) ||
                   2189:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2190:                 }
                   2191:             }
1.899     raeburn  2192:             my $host=&hostname($tryserver);
                   2193:             my $queryid=
1.911     raeburn  2194:                 &reply("querysend:".&escape($query).':'.
                   2195:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2196:                        &escape($srch->{'srchtype'}).':'.
                   2197:                        &escape($srch->{'srchterm'}),$tryserver);
                   2198:             if ($queryid !~/^\Q$host\E\_/) {
                   2199:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2200:                 next;
1.899     raeburn  2201:             }
                   2202:             my $reply = &get_query_reply($queryid);
                   2203:             my $maxtries = 1;
                   2204:             my $tries = 1;
                   2205:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2206:                 $reply = &get_query_reply($queryid);
                   2207:                 $tries ++;
                   2208:             }
                   2209:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2210:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2211:             } else {
1.911     raeburn  2212:                 my @matches;
                   2213:                 if ($reply =~ /\n/) {
                   2214:                     @matches = split(/\n/,$reply);
                   2215:                 } else {
                   2216:                     @matches = split(/\&/,$reply);
                   2217:                 }
1.899     raeburn  2218:                 foreach my $match (@matches) {
                   2219:                     my ($uname,$udom,%userhash);
1.911     raeburn  2220:                     foreach my $entry (split(/:/,$match)) {
                   2221:                         my ($key,$value) =
                   2222:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2223:                         $userhash{$key} = $value;
                   2224:                         if ($key eq 'username') {
                   2225:                             $uname = $value;
                   2226:                         } elsif ($key eq 'domain') {
                   2227:                             $udom = $value;
1.911     raeburn  2228:                         }
1.899     raeburn  2229:                     }
                   2230:                     $results{$uname.':'.$udom} = \%userhash;
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return %results;
                   2236: }
                   2237: 
1.912     raeburn  2238: sub get_instuser {
                   2239:     my ($udom,$uname,$id) = @_;
                   2240:     my $homeserver = &domain($udom,'primary');
                   2241:     my ($outcome,%results);
                   2242:     if ($homeserver ne '') {
                   2243:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2244:                            &escape($id).':'.&escape($udom),$homeserver);
                   2245:         my $host=&hostname($homeserver);
                   2246:         if ($queryid !~/^\Q$host\E\_/) {
                   2247:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2248:             return;
                   2249:         }
                   2250:         my $response = &get_query_reply($queryid);
                   2251:         my $maxtries = 5;
                   2252:         my $tries = 1;
                   2253:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2254:             $response = &get_query_reply($queryid);
                   2255:             $tries ++;
                   2256:         }
                   2257:         if (!&error($response) && $response ne 'refused') {
                   2258:             if ($response eq 'unavailable') {
                   2259:                 $outcome = $response;
                   2260:             } else {
                   2261:                 $outcome = 'ok';
                   2262:                 my @matches = split(/\n/,$response);
                   2263:                 foreach my $match (@matches) {
                   2264:                     my ($key,$value) = split(/=/,$match);
                   2265:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2266:                 }
                   2267:             }
                   2268:         }
                   2269:     }
                   2270:     my %userinfo;
                   2271:     if (ref($results{$uname}) eq 'HASH') {
                   2272:         %userinfo = %{$results{$uname}};
                   2273:     } 
                   2274:     return ($outcome,%userinfo);
                   2275: }
                   2276: 
1.1172.2.69  raeburn  2277: sub get_multiple_instusers {
                   2278:     my ($udom,$users,$caller) = @_;
                   2279:     my ($outcome,$results);
                   2280:     if (ref($users) eq 'HASH') {
                   2281:         my $count = keys(%{$users});
                   2282:         my $requested = &freeze_escape($users);
                   2283:         my $homeserver = &domain($udom,'primary');
                   2284:         if ($homeserver ne '') {
                   2285:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2286:             my $host=&hostname($homeserver);
                   2287:             if ($queryid !~/^\Q$host\E\_/) {
                   2288:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2289:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2290:                 return ($outcome,$results);
                   2291:             }
                   2292:             my $response = &get_query_reply($queryid);
                   2293:             my $maxtries = 5;
                   2294:             if ($count > 100) {
                   2295:                 $maxtries = 1+int($count/20);
                   2296:             }
                   2297:             my $tries = 1;
                   2298:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2299:                 $response = &get_query_reply($queryid);
                   2300:                 $tries ++;
                   2301:             }
                   2302:             if ($response eq '') {
                   2303:                 $results = {};
                   2304:                 foreach my $key (keys(%{$users})) {
                   2305:                     my ($uname,$id);
                   2306:                     if ($caller eq 'id') {
                   2307:                         $id = $key;
                   2308:                     } else {
                   2309:                         $uname = $key;
                   2310:                     }
                   2311:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2312:                     $outcome = $resp;
                   2313:                     if ($resp eq 'ok') {
                   2314:                         %{$results} = (%{$results}, %info);
                   2315:                     } else {
                   2316:                         last;
                   2317:                     }
                   2318:                 }
                   2319:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2320:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2321:                     $outcome = $response;
                   2322:                 } else {
                   2323:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2324:                     if ($outcome eq 'ok') {
                   2325:                         $results = &thaw_unescape($userdata);
                   2326:                     }
                   2327:                 }
                   2328:             }
                   2329:         }
                   2330:     }
                   2331:     return ($outcome,$results);
                   2332: }
                   2333: 
1.912     raeburn  2334: sub inst_rulecheck {
1.923     raeburn  2335:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2336:     my %returnhash;
                   2337:     if ($udom ne '') {
                   2338:         if (ref($rules) eq 'ARRAY') {
                   2339:             @{$rules} = map {&escape($_);} (@{$rules});
                   2340:             my $rulestr = join(':',@{$rules});
                   2341:             my $homeserver=&domain($udom,'primary');
                   2342:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2343:                 my $response;
                   2344:                 if ($item eq 'username') {                
                   2345:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2346:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2347:                                               $homeserver));
1.923     raeburn  2348:                 } elsif ($item eq 'id') {
                   2349:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2350:                                               ':'.&escape($id).':'.$rulestr,
                   2351:                                               $homeserver));
1.1172.2.146.  .5(raebu 2352:22):                 } elsif ($item eq 'unamemap') {
                   2353:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2354:22):                                                &escape($udom).':'.&escape($uname).
                   2355:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2356:                 } elsif ($item eq 'selfcreate') {
                   2357:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2358:                                                &escape($udom).':'.&escape($uname).
                   2359:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2360:                 }
1.912     raeburn  2361:                 if ($response ne 'refused') {
                   2362:                     my @pairs=split(/\&/,$response);
                   2363:                     foreach my $item (@pairs) {
                   2364:                         my ($key,$value)=split(/=/,$item,2);
                   2365:                         $key = &unescape($key);
                   2366:                         next if ($key =~ /^error: 2 /);
                   2367:                         $returnhash{$key}=&thaw_unescape($value);
                   2368:                     }
                   2369:                 }
                   2370:             }
                   2371:         }
                   2372:     }
                   2373:     return %returnhash;
                   2374: }
                   2375: 
                   2376: sub inst_userrules {
1.923     raeburn  2377:     my ($udom,$check) = @_;
1.912     raeburn  2378:     my (%ruleshash,@ruleorder);
                   2379:     if ($udom ne '') {
                   2380:         my $homeserver=&domain($udom,'primary');
                   2381:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2382:             my $response;
                   2383:             if ($check eq 'id') {
                   2384:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2385:                                  $homeserver);
1.943     raeburn  2386:             } elsif ($check eq 'email') {
                   2387:                 $response=&reply('instemailrules:'.&escape($udom),
                   2388:                                  $homeserver);
1.1172.2.146.  .5(raebu 2389:22):             } elsif ($check eq 'unamemap') {
                   2390:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2391:22):                                  $homeserver);
1.923     raeburn  2392:             } else {
                   2393:                 $response=&reply('instuserrules:'.&escape($udom),
                   2394:                                  $homeserver);
                   2395:             }
1.912     raeburn  2396:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2397:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2398:                 ($response ne 'no_such_host')) {
                   2399:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2400:                 my @pairs=split(/\&/,$hashitems);
                   2401:                 foreach my $item (@pairs) {
                   2402:                     my ($key,$value)=split(/=/,$item,2);
                   2403:                     $key = &unescape($key);
                   2404:                     next if ($key =~ /^error: 2 /);
                   2405:                     $ruleshash{$key}=&thaw_unescape($value);
                   2406:                 }
                   2407:                 my @esc_order = split(/\&/,$orderitems);
                   2408:                 foreach my $item (@esc_order) {
                   2409:                     push(@ruleorder,&unescape($item));
                   2410:                 }
                   2411:             }
                   2412:         }
                   2413:     }
                   2414:     return (\%ruleshash,\@ruleorder);
                   2415: }
                   2416: 
1.976     raeburn  2417: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2418: 
                   2419: sub get_domain_defaults {
1.1172.2.35  raeburn  2420:     my ($domain,$ignore_cache) = @_;
                   2421:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2422:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2423:     unless ($ignore_cache) {
                   2424:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2425:         if (defined($cached)) {
                   2426:             if (ref($result) eq 'HASH') {
                   2427:                 return %{$result};
                   2428:             }
1.943     raeburn  2429:         }
                   2430:     }
                   2431:     my %domdefaults;
                   2432:     my %domconfig =
1.989     raeburn  2433:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2434:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2435:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2436:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2437:                                   'coursecategories','autoenroll',
1.1172.2.146.  .4(raebu 2438:22):                                   'helpsettings','wafproxy','ltisec'],$domain);
1.1172.2.41  raeburn  2439:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2440:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2441:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2442:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2443:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2444:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2445:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2446:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2447:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2448:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2449:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2450:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2451:     } else {
                   2452:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2453:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2454:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2455:     }
1.976     raeburn  2456:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2457:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2458:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2459:         } else {
                   2460:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2461:         }
1.1172.2.6  raeburn  2462:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2463:         foreach my $item (@usertools) {
                   2464:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2465:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2466:             }
                   2467:         }
1.1172.2.29  raeburn  2468:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2469:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2470:         }
1.976     raeburn  2471:     }
1.985     raeburn  2472:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2473:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2474:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2475:         }
                   2476:     }
1.1172.2.9  raeburn  2477:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2478:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2479:     }
1.989     raeburn  2480:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2481:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2482:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2483:         }
                   2484:     }
1.1047    raeburn  2485:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2486:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2487:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2488:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2489:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2490:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2491:         }
1.1172.2.41  raeburn  2492:         foreach my $type (@coursetypes) {
                   2493:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2494:                 unless ($type eq 'community') {
                   2495:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2496:                 }
                   2497:             }
                   2498:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2499:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2500:             }
1.1172.2.60  raeburn  2501:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2502:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2503:                     $domdefaults{$type.'postsubtimeout'} =
                   2504:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2505:                 }
                   2506:             }
1.1172.2.30  raeburn  2507:         }
1.1172.2.67  raeburn  2508:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2509:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2510:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2511:                 if (@clonecodes) {
                   2512:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2513:                 }
                   2514:             }
                   2515:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2516:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2517:         }
1.1172.2.103  raeburn  2518:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2519:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2520:         }
1.1172.2.146.  .3(raebu 2521:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2522:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2523:22):         }
1.1047    raeburn  2524:     }
1.1073    raeburn  2525:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2526:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2527:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2528:         }
                   2529:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2530:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2531:         }
1.1172.2.62  raeburn  2532:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2533:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2534:         }
1.1172.2.137  raeburn  2535:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2536:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2537:         }
1.1073    raeburn  2538:     }
1.1172.2.41  raeburn  2539:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2540:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2541:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2542:                             'approval','limit');
                   2543:             foreach my $type (@coursetypes) {
                   2544:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2545:                     my @mgrdc = ();
                   2546:                     foreach my $item (@settings) {
                   2547:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2548:                             push(@mgrdc,$item);
                   2549:                         }
                   2550:                     }
                   2551:                     if (@mgrdc) {
                   2552:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2553:                     }
                   2554:                 }
                   2555:             }
                   2556:         }
                   2557:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2558:             foreach my $type (@coursetypes) {
                   2559:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2560:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2561:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2562:                     }
                   2563:                 }
                   2564:             }
                   2565:         }
                   2566:     }
1.1172.2.46  raeburn  2567:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2568:         $domdefaults{'catauth'} = 'std';
                   2569:         $domdefaults{'catunauth'} = 'std';
                   2570:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2571:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2572:         }
                   2573:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2574:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2575:         }
                   2576:     }
1.1172.2.76  raeburn  2577:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2578:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2579:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2580:     }
1.1172.2.89  raeburn  2581:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2582:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2583:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2584:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2585:         }
                   2586:     }
1.1172.2.142  raeburn  2587:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2588:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2589:             if ($domconfig{'wafproxy'}{$item}) {
                   2590:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2591:             }
                   2592:         }
                   2593:     }
1.1172.2.146.  .4(raebu 2594:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2595:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2596:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2597:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2598:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2599:22):         }
                   2600:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2601:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2602:22):                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2603:22):             }
                   2604:22):         }
                   2605:22):     }
1.1172.2.23  raeburn  2606:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2607:     return %domdefaults;
                   2608: }
                   2609: 
1.1172.2.106  raeburn  2610: sub get_dom_cats {
                   2611:     my ($dom) = @_;
                   2612:     return unless (&domain($dom));
                   2613:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2614:     unless (defined($cached)) {
                   2615:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2616:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2617:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2618:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2619:             } else {
                   2620:                 $cats = {};
                   2621:             }
                   2622:         } else {
                   2623:             $cats = {};
                   2624:         }
                   2625:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2626:     }
                   2627:     return $cats;
                   2628: }
                   2629: 
                   2630: sub get_dom_instcats {
                   2631:     my ($dom) = @_;
                   2632:     return unless (&domain($dom));
                   2633:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2634:     unless (defined($cached)) {
                   2635:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2636:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2637:         if ($totcodes > 0) {
                   2638:             my $caller = 'global';
                   2639:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2640:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2641:                 $instcats = {
                   2642:                                 codes => \%codes,
                   2643:                                 codetitles => \@codetitles,
                   2644:                                 cat_titles => \%cat_titles,
                   2645:                                 cat_order => \%cat_order,
                   2646:                             };
                   2647:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2648:             }
                   2649:         }
                   2650:     }
                   2651:     return $instcats;
                   2652: }
                   2653: 
                   2654: sub retrieve_instcodes {
                   2655:     my ($coursecodes,$dom) = @_;
                   2656:     my $totcodes;
                   2657:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2658:     foreach my $course (keys(%courses)) {
                   2659:         if (ref($courses{$course}) eq 'HASH') {
                   2660:             if ($courses{$course}{'inst_code'} ne '') {
                   2661:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2662:                 $totcodes ++;
                   2663:             }
                   2664:         }
                   2665:     }
                   2666:     return $totcodes;
                   2667: }
                   2668: 
1.1172.2.113  raeburn  2669: # --------------------------------------------- Get domain config for passwords
                   2670: 
                   2671: sub get_passwdconf {
                   2672:     my ($dom) = @_;
                   2673:     my (%passwdconf,$gotconf,$lookup);
                   2674:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2675:     if (defined($cached)) {
                   2676:         if (ref($result) eq 'HASH') {
                   2677:             %passwdconf = %{$result};
                   2678:             $gotconf = 1;
                   2679:         }
                   2680:     }
                   2681:     unless ($gotconf) {
                   2682:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2683:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2684:             %passwdconf = %{$domconfig{'passwords'}};
                   2685:         }
                   2686:         my $cachetime = 24*60*60;
                   2687:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2688:     }
                   2689:     return %passwdconf;
                   2690: }
                   2691: 
1.1172.2.146.  .1(raebu 2692:22): sub course_portal_url {
                   2693:22):     my ($cnum,$cdom,$r) = @_;
                   2694:22):     my $chome = &homeserver($cnum,$cdom);
                   2695:22):     my $hostname = &hostname($chome);
                   2696:22):     my $protocol = $protocol{$chome};
                   2697:22):     $protocol = 'http' if ($protocol ne 'https');
                   2698:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2699:22):     my $firsturl;
                   2700:22):     if ($domdefaults{'portal_def'}) {
                   2701:22):         $firsturl = $domdefaults{'portal_def'};
                   2702:22):     } else {
                   2703:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2704:22):         $hostname = $alias if ($alias ne '');
                   2705:22):         $firsturl = $protocol.'://'.$hostname;
                   2706:22):     }
                   2707:22):     return $firsturl;
                   2708:22): }
                   2709:22): 
1.344     www      2710: # --------------------------------------------------- Assign a key to a student
                   2711: 
                   2712: sub assign_access_key {
1.364     www      2713: #
                   2714: # a valid key looks like uname:udom#comments
                   2715: # comments are being appended
                   2716: #
1.498     www      2717:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2718:     $kdom=
1.620     albertel 2719:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2720:     $knum=
1.620     albertel 2721:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2722:     $cdom=
1.620     albertel 2723:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2724:     $cnum=
1.620     albertel 2725:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2726:     $udom=$env{'user.name'} unless (defined($udom));
                   2727:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2728:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2729:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2730:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2731:                                                   # assigned to this person
                   2732:                                                   # - this should not happen,
1.345     www      2733:                                                   # unless something went wrong
                   2734:                                                   # the first time around
                   2735: # ready to assign
1.364     www      2736:         $logentry=$1.'; '.$logentry;
1.496     www      2737:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2738:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2739: # key now belongs to user
1.346     www      2740: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2741:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2742:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2743:                 return 'ok';
                   2744:             } else {
                   2745:                 return 
                   2746:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2747: 	    }
                   2748:         } else {
                   2749:             return 'error: Could not assign key, try again later.';
                   2750:         }
1.364     www      2751:     } elsif (!$existing{$ckey}) {
1.345     www      2752: # the key does not exist
                   2753: 	return 'error: The key does not exist';
                   2754:     } else {
                   2755: # the key is somebody else's
                   2756: 	return 'error: The key is already in use';
                   2757:     }
1.344     www      2758: }
                   2759: 
1.364     www      2760: # ------------------------------------------ put an additional comment on a key
                   2761: 
                   2762: sub comment_access_key {
                   2763: #
                   2764: # a valid key looks like uname:udom#comments
                   2765: # comments are being appended
                   2766: #
                   2767:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2768:     $cdom=
1.620     albertel 2769:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2770:     $cnum=
1.620     albertel 2771:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2772:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2773:     if ($existing{$ckey}) {
                   2774:         $existing{$ckey}.='; '.$logentry;
                   2775: # ready to assign
1.367     www      2776:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2777:                                                  $cdom,$cnum) eq 'ok') {
                   2778: 	    return 'ok';
                   2779:         } else {
                   2780: 	    return 'error: Count not store comment.';
                   2781:         }
                   2782:     } else {
                   2783: # the key does not exist
                   2784: 	return 'error: The key does not exist';
                   2785:     }
                   2786: }
                   2787: 
1.344     www      2788: # ------------------------------------------------------ Generate a set of keys
                   2789: 
                   2790: sub generate_access_keys {
1.364     www      2791:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2792:     $cdom=
1.620     albertel 2793:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2794:     $cnum=
1.620     albertel 2795:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2796:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2797:     unless (($cdom) && ($cnum)) { return 0; }
                   2798:     if ($number>10000) { return 0; }
                   2799:     sleep(2); # make sure don't get same seed twice
                   2800:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2801:     my $total=0;
                   2802:     for (my $i=1;$i<=$number;$i++) {
                   2803:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2804:                   sprintf("%lx",int(100000*rand)).'-'.
                   2805:                   sprintf("%lx",int(100000*rand));
                   2806:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2807:        $newkey=~s/0/h/g; # and also 0 and O
                   2808:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2809:        if ($existing{$newkey}) {
                   2810:            $i--;
                   2811:        } else {
1.364     www      2812: 	  if (&put('accesskeys',
                   2813:               { $newkey => '# generated '.localtime().
1.620     albertel 2814:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2815:                            '; '.$logentry },
                   2816: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2817:               $total++;
                   2818: 	  }
                   2819:        }
                   2820:     }
1.620     albertel 2821:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2822:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2823:     return $total;
                   2824: }
                   2825: 
                   2826: # ------------------------------------------------------- Validate an accesskey
                   2827: 
                   2828: sub validate_access_key {
                   2829:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2830:     $cdom=
1.620     albertel 2831:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2832:     $cnum=
1.620     albertel 2833:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2834:     $udom=$env{'user.domain'} unless (defined($udom));
                   2835:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2836:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2837:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2838: }
                   2839: 
                   2840: # ------------------------------------- Find the section of student in a course
1.652     albertel 2841: sub devalidate_getsection_cache {
                   2842:     my ($udom,$unam,$courseid)=@_;
                   2843:     my $hashid="$udom:$unam:$courseid";
                   2844:     &devalidate_cache_new('getsection',$hashid);
                   2845: }
1.298     matthew  2846: 
1.815     albertel 2847: sub courseid_to_courseurl {
                   2848:     my ($courseid) = @_;
                   2849:     #already url style courseid
                   2850:     return $courseid if ($courseid =~ m{^/});
                   2851: 
                   2852:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2853: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2854: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2855: 	return "/$cdom/$cnum";
                   2856:     }
                   2857: 
                   2858:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2859:     if (exists($courseinfo{'num'})) {
                   2860: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2861:     }
                   2862: 
                   2863:     return undef;
                   2864: }
                   2865: 
1.298     matthew  2866: sub getsection {
                   2867:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2868:     my $cachetime=1800;
1.551     albertel 2869: 
                   2870:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2871:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2872:     if (defined($cached)) { return $result; }
                   2873: 
1.298     matthew  2874:     my %Pending; 
                   2875:     my %Expired;
                   2876:     #
                   2877:     # Each role can either have not started yet (pending), be active, 
                   2878:     #    or have expired.
                   2879:     #
                   2880:     # If there is an active role, we are done.
                   2881:     #
                   2882:     # If there is more than one role which has not started yet, 
                   2883:     #     choose the one which will start sooner
                   2884:     # If there is one role which has not started yet, return it.
                   2885:     #
                   2886:     # If there is more than one expired role, choose the one which ended last.
                   2887:     # If there is a role which has expired, return it.
                   2888:     #
1.815     albertel 2889:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2890:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2891:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2892:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2893:         my $section=$1;
                   2894:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2895:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2896:         my $now=time;
1.548     albertel 2897:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2898:             $Expired{$end}=$section;
                   2899:             next;
                   2900:         }
1.548     albertel 2901:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2902:             $Pending{$start}=$section;
                   2903:             next;
                   2904:         }
1.599     albertel 2905:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2906:     }
                   2907:     #
                   2908:     # Presumedly there will be few matching roles from the above
                   2909:     # loop and the sorting time will be negligible.
                   2910:     if (scalar(keys(%Pending))) {
                   2911:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2912:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2913:     } 
                   2914:     if (scalar(keys(%Expired))) {
                   2915:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2916:         my $time = pop(@sorted);
1.599     albertel 2917:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2918:     }
1.599     albertel 2919:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2920: }
1.70      www      2921: 
1.599     albertel 2922: sub save_cache {
                   2923:     &purge_remembered();
1.722     albertel 2924:     #&Apache::loncommon::validate_page();
1.620     albertel 2925:     undef(%env);
1.780     albertel 2926:     undef($env_loaded);
1.599     albertel 2927: }
1.452     albertel 2928: 
1.599     albertel 2929: my $to_remember=-1;
                   2930: my %remembered;
                   2931: my %accessed;
                   2932: my $kicks=0;
                   2933: my $hits=0;
1.849     albertel 2934: sub make_key {
                   2935:     my ($name,$id) = @_;
1.872     albertel 2936:     if (length($id) > 65 
                   2937: 	&& length(&escape($id)) > 200) {
                   2938: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2939:     }
1.849     albertel 2940:     return &escape($name.':'.$id);
                   2941: }
                   2942: 
1.599     albertel 2943: sub devalidate_cache_new {
                   2944:     my ($name,$id,$debug) = @_;
                   2945:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2946:     my $remembered_id=$name.':'.$id;
1.849     albertel 2947:     $id=&make_key($name,$id);
1.599     albertel 2948:     $memcache->delete($id);
1.1172.2.81  raeburn  2949:     delete($remembered{$remembered_id});
                   2950:     delete($accessed{$remembered_id});
1.599     albertel 2951: }
                   2952: 
                   2953: sub is_cached_new {
                   2954:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2955:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2956:                                      # keys in %remembered hash, which persists for
                   2957:                                      # duration of request (no restriction on key length).
                   2958:     if (exists($remembered{$remembered_id})) {
                   2959: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2960: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2961: 	$hits++;
1.1172.2.81  raeburn  2962: 	return ($remembered{$remembered_id},1);
1.599     albertel 2963:     }
1.1172.2.81  raeburn  2964:     $id=&make_key($name,$id);
1.599     albertel 2965:     my $value = $memcache->get($id);
                   2966:     if (!(defined($value))) {
                   2967: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2968: 	return (undef,undef);
1.416     albertel 2969:     }
1.599     albertel 2970:     if ($value eq '__undef__') {
                   2971: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2972: 	$value=undef;
                   2973:     }
1.1172.2.81  raeburn  2974:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2975:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2976:     return ($value,1);
                   2977: }
                   2978: 
                   2979: sub do_cache_new {
                   2980:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2981:     my $remembered_id=$name.':'.$id;
1.849     albertel 2982:     $id=&make_key($name,$id);
1.599     albertel 2983:     my $setvalue=$value;
                   2984:     if (!defined($setvalue)) {
                   2985: 	$setvalue='__undef__';
                   2986:     }
1.623     albertel 2987:     if (!defined($time) ) {
                   2988: 	$time=600;
                   2989:     }
1.599     albertel 2990:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2991:     my $result = $memcache->set($id,$setvalue,$time);
                   2992:     if (! $result) {
1.872     albertel 2993: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2994: 	$memcache->disconnect_all();
1.872     albertel 2995:     }
1.600     albertel 2996:     # need to make a copy of $value
1.1172.2.81  raeburn  2997:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2998:     return $value;
                   2999: }
                   3000: 
                   3001: sub make_room {
1.1172.2.81  raeburn  3002:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3003: 
1.1172.2.81  raeburn  3004:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3005:                                     : $value;
1.599     albertel 3006:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3007:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3008:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3009:     my $to_kick;
                   3010:     my $max_time=0;
                   3011:     foreach my $other (keys(%accessed)) {
                   3012: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3013: 	    $to_kick=$other;
                   3014: 	    $max_time=&tv_interval($accessed{$other});
                   3015: 	}
                   3016:     }
                   3017:     delete($remembered{$to_kick});
                   3018:     delete($accessed{$to_kick});
                   3019:     $kicks++;
                   3020:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3021:     return;
                   3022: }
                   3023: 
1.599     albertel 3024: sub purge_remembered {
1.604     albertel 3025:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3026:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3027:     undef(%remembered);
                   3028:     undef(%accessed);
1.428     albertel 3029: }
1.70      www      3030: # ------------------------------------- Read an entry from a user's environment
                   3031: 
                   3032: sub userenvironment {
                   3033:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3034:     my $items;
                   3035:     foreach my $item (@what) {
                   3036:         $items.=&escape($item).'&';
                   3037:     }
                   3038:     $items=~s/\&$//;
1.70      www      3039:     my %returnhash=();
1.1009    raeburn  3040:     my $uhome = &homeserver($unam,$udom);
                   3041:     unless ($uhome eq 'no_host') {
                   3042:         my @answer=split(/\&/, 
                   3043:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3044:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3045:             return %returnhash;
                   3046:         }
1.1009    raeburn  3047:         my $i;
                   3048:         for ($i=0;$i<=$#what;$i++) {
                   3049: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3050:         }
1.70      www      3051:     }
                   3052:     return %returnhash;
1.1       albertel 3053: }
                   3054: 
1.617     albertel 3055: # ---------------------------------------------------------- Get a studentphoto
                   3056: sub studentphoto {
                   3057:     my ($udom,$unam,$ext) = @_;
                   3058:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3059:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3060:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3061:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3062:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3063:             } else {
                   3064:                 my ($result,$perm_reqd)=
1.707     albertel 3065: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3066:                 if ($result eq 'ok') {
                   3067:                     if (!($perm_reqd eq 'yes')) {
                   3068:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3069:                     }
                   3070:                 }
                   3071:             }
                   3072:         }
                   3073:     } else {
                   3074:         my ($result,$perm_reqd) = 
1.707     albertel 3075: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3076:         if ($result eq 'ok') {
                   3077:             if (!($perm_reqd eq 'yes')) {
                   3078:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3079:             }
                   3080:         }
                   3081:     }
                   3082:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3083: }
                   3084: 
                   3085: sub retrievestudentphoto {
                   3086:     my ($udom,$unam,$ext,$type) = @_;
                   3087:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3088:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3089:     if ($ret eq 'ok') {
                   3090:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3091:         if ($type eq 'thumbnail') {
                   3092:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3093:         }
                   3094:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3095:         return $tokenurl;
                   3096:     } else {
                   3097:         if ($type eq 'thumbnail') {
                   3098:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3099:         } else { 
                   3100:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3101:         }
1.617     albertel 3102:     }
                   3103: }
                   3104: 
1.263     www      3105: # -------------------------------------------------------------------- New chat
                   3106: 
                   3107: sub chatsend {
1.724     raeburn  3108:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3109:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3110:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3111:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3112:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3113: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3114: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3115: }
                   3116: 
                   3117: # ------------------------------------------ Find current version of a resource
                   3118: 
                   3119: sub getversion {
                   3120:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3121:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3122:     return &currentversion(&filelocation('',$fname));
                   3123: }
                   3124: 
                   3125: sub currentversion {
                   3126:     my $fname=shift;
                   3127:     my $author=$fname;
                   3128:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3129:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3130:     my $home=&homeserver($uname,$udom);
1.292     www      3131:     if ($home eq 'no_host') { 
                   3132:         return -1; 
                   3133:     }
1.1112    www      3134:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3135:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3136: 	return -1;
                   3137:     }
1.1112    www      3138:     return $answer;
1.263     www      3139: }
                   3140: 
1.1111    www      3141: #
                   3142: # Return special version number of resource if set by override, empty otherwise
                   3143: #
                   3144: sub usedversion {
                   3145:     my $fname=shift;
                   3146:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3147:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3148:     if ($urlversion) { return $urlversion; }
                   3149:     return '';
                   3150: }
                   3151: 
1.1       albertel 3152: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3153: 
1.1       albertel 3154: sub subscribe {
                   3155:     my $fname=shift;
1.761     raeburn  3156:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3157:     $fname=~s/[\n\r]//g;
1.1       albertel 3158:     my $author=$fname;
                   3159:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3160:     my ($udom,$uname)=split(/\//,$author);
                   3161:     my $home=homeserver($uname,$udom);
1.335     albertel 3162:     if ($home eq 'no_host') {
                   3163:         return 'not_found';
1.1       albertel 3164:     }
                   3165:     my $answer=reply("sub:$fname",$home);
1.64      www      3166:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3167: 	$answer.=' by '.$home;
                   3168:     }
1.1       albertel 3169:     return $answer;
                   3170: }
                   3171:     
1.8       www      3172: # -------------------------------------------------------------- Replicate file
                   3173: 
                   3174: sub repcopy {
                   3175:     my $filename=shift;
1.23      www      3176:     $filename=~s/\/+/\//g;
1.1142    raeburn  3177:     my $londocroot = $perlvar{'lonDocRoot'};
                   3178:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3179:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3180:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3181: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3182: 	return &repcopy_userfile($filename);
                   3183:     }
1.532     albertel 3184:     $filename=~s/[\n\r]//g;
1.8       www      3185:     my $transname="$filename.in.transfer";
1.828     www      3186: # FIXME: this should flock
1.607     raeburn  3187:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3188:     my $remoteurl=subscribe($filename);
1.64      www      3189:     if ($remoteurl =~ /^con_lost by/) {
                   3190: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3191:            return 'unavailable';
1.8       www      3192:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3193: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3194: 	   return 'not_found';
1.64      www      3195:     } elsif ($remoteurl =~ /^rejected by/) {
                   3196: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3197:            return 'forbidden';
1.20      www      3198:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3199:            return 'ok';
1.8       www      3200:     } else {
1.290     www      3201:         my $author=$filename;
                   3202:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3203:         my ($udom,$uname)=split(/\//,$author);
                   3204:         my $home=homeserver($uname,$udom);
                   3205:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3206:            my @parts=split(/\//,$filename);
                   3207:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3208:            if ($path ne "$londocroot/res") {
1.8       www      3209:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3210: 	       return 'bad_request';
1.8       www      3211:            }
                   3212:            my $count;
                   3213:            for ($count=5;$count<$#parts;$count++) {
                   3214:                $path.="/$parts[$count]";
                   3215:                if ((-e $path)!=1) {
                   3216: 		   mkdir($path,0777);
                   3217:                }
                   3218:            }
                   3219:            my $ua=new LWP::UserAgent;
                   3220:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3221:            my $response=$ua->request($request,$transname);
                   3222:            if ($response->is_error()) {
                   3223: 	       unlink($transname);
                   3224:                my $message=$response->status_line;
1.672     albertel 3225:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3226:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3227:                return 'unavailable';
1.8       www      3228:            } else {
1.16      www      3229: 	       if ($remoteurl!~/\.meta$/) {
                   3230:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3231:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3232:                   if ($mresponse->is_error()) {
                   3233: 		      unlink($filename.'.meta');
                   3234:                       &logthis(
1.672     albertel 3235:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3236:                   }
                   3237: 	       }
1.8       www      3238:                rename($transname,$filename);
1.607     raeburn  3239:                return 'ok';
1.8       www      3240:            }
1.290     www      3241:        }
1.8       www      3242:     }
1.330     www      3243: }
                   3244: 
1.1172.2.124  raeburn  3245: # ------------------------------------------------- Unsubscribe from a resource
                   3246: 
                   3247: sub unsubscribe {
                   3248:     my ($fname) = @_;
                   3249:     my $answer;
                   3250:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3251:     $fname=~s/[\n\r]//g;
                   3252:     my $author=$fname;
                   3253:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3254:     my ($udom,$uname)=split(/\//,$author);
                   3255:     my $home=homeserver($uname,$udom);
                   3256:     if ($home eq 'no_host') {
                   3257:         $answer = 'no_host';
                   3258:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3259:         $answer = 'home';
                   3260:     } else {
1.1172.2.125  raeburn  3261:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3262:     }
                   3263:     return $answer;
                   3264: }
                   3265: 
1.330     www      3266: # ------------------------------------------------ Get server side include body
                   3267: sub ssi_body {
1.381     albertel 3268:     my ($filelink,%form)=@_;
1.606     matthew  3269:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3270:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3271:     }
1.953     www      3272:     my $output='';
                   3273:     my $response;
1.980     raeburn  3274:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3275:        ($output,$response)=&externalssi($filelink);
1.953     www      3276:     } else {
1.1004    droeschl 3277:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3278:        $filelink .= 'inhibitmenu=yes';
1.953     www      3279:        ($output,$response)=&ssi($filelink,%form);
                   3280:     }
1.778     albertel 3281:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3282:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3283:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3284:     if (wantarray) {
                   3285:         return ($output, $response);
                   3286:     } else {
                   3287:         return $output;
                   3288:     }
1.8       www      3289: }
                   3290: 
1.15      www      3291: # --------------------------------------------------------- Server Side Include
                   3292: 
1.782     albertel 3293: sub absolute_url {
1.1172.2.145  raeburn  3294:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3295:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3296:     if ($host_name eq '') {
                   3297: 	$host_name = $ENV{'SERVER_NAME'};
                   3298:     }
1.1172.2.145  raeburn  3299:     if ($unalias) {
                   3300:         my $alias = &get_proxy_alias();
                   3301:         if ($alias eq $host_name) {
                   3302:             my $lonhost = $perlvar{'lonHostID'};
                   3303:             my $hostname = &hostname($lonhost);
                   3304:             my $lcproto;
                   3305:             if (($keep_proto) || ($hostname eq '')) {
                   3306:                 $lcproto = $protocol;
                   3307:             } else {
                   3308:                 $lcproto = $protocol{$lonhost};
                   3309:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3310:                 $lcproto .= '://';
                   3311:             }
                   3312:             unless ($hostname eq '') {
                   3313:                 return $lcproto.$hostname;
                   3314:             }
                   3315:         }
                   3316:     } 
1.782     albertel 3317:     return $protocol.$host_name;
                   3318: }
                   3319: 
1.942     foxr     3320: #
                   3321: #   Server side include.
                   3322: # Parameters:
                   3323: #  fn     Possibly encrypted resource name/id.
                   3324: #  form   Hash that describes how the rendering should be done
                   3325: #         and other things.
1.944     foxr     3326: # Returns:
1.950     raeburn  3327: #   Scalar context: The content of the response.
                   3328: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3329: #     
1.15      www      3330: sub ssi {
                   3331: 
1.944     foxr     3332:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3333:     my ($host,$request,$response);
                   3334:     $host = &absolute_url('',1);
1.711     albertel 3335: 
                   3336:     $form{'no_update_last_known'}=1;
1.895     albertel 3337:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3338:     if (%form) {
1.1172.2.145  raeburn  3339:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3340:       $request->content(join('&',map {
                   3341:             my $name = escape($_);
                   3342:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3343:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3344:             : &escape($form{$_}) );
                   3345:         } keys(%form)));
1.23      www      3346:     } else {
1.1172.2.145  raeburn  3347:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3348:     }
                   3349: 
1.15      www      3350:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3351: 
1.1172.2.101  raeburn  3352:     if (($env{'request.course.id'}) &&
                   3353:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3354:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3355:         ($form{'grade_symb'} ne '') &&
                   3356:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3357:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3358:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3359:             my $ua=new LWP::UserAgent;
                   3360:             $ua->local_address('127.0.0.1');
                   3361:             $response = $ua->request($request);
                   3362:         } else {
                   3363:             {
                   3364:                 require LWP::Protocol::http;
                   3365:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3366:                 my $ua=new LWP::UserAgent;
                   3367:                 $response = $ua->request($request);
                   3368:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3369:             }
                   3370:         }
                   3371:     } else {
                   3372:         my $ua=new LWP::UserAgent;
                   3373:         $response = $ua->request($request);
                   3374:     }
1.944     foxr     3375:     if (wantarray) {
1.1172.2.3  raeburn  3376: 	return ($response->content, $response);
1.944     foxr     3377:     } else {
1.1172.2.3  raeburn  3378: 	return $response->content;
1.942     foxr     3379:     }
1.324     www      3380: }
                   3381: 
                   3382: sub externalssi {
                   3383:     my ($url)=@_;
                   3384:     my $ua=new LWP::UserAgent;
                   3385:     my $request=new HTTP::Request('GET',$url);
                   3386:     my $response=$ua->request($request);
1.954     raeburn  3387:     if (wantarray) {
                   3388:         return ($response->content, $response);
                   3389:     } else {
                   3390:         return $response->content;
                   3391:     }
1.15      www      3392: }
1.254     www      3393: 
1.1172.2.98  raeburn  3394: # If the local copy of a replicated resource is outdated, trigger a
                   3395: # connection from the homeserver to flush the delayed queue. If no update
                   3396: # happens, remove local copies of outdated resource (and corresponding
                   3397: # metadata file).
                   3398: 
                   3399: sub remove_stale_resfile {
                   3400:     my ($url) = @_;
                   3401:     my $removed;
                   3402:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3403:         my $audom = $1;
                   3404:         my $auname = $2;
                   3405:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3406:             my $homeserver = &homeserver($auname,$audom);
                   3407:             unless (($homeserver eq 'no_host') ||
                   3408:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3409:                 my $fname = &filelocation('',$url);
                   3410:                 if (-e $fname) {
                   3411:                     my $hostname = &hostname($homeserver);
                   3412:                     if ($hostname) {
1.1172.2.120  raeburn  3413:                         my $protocol = $protocol{$homeserver};
                   3414:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3415:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3416:                         my $ua=new LWP::UserAgent;
                   3417:                         $ua->timeout(5);
1.1172.2.98  raeburn  3418:                         my $request=new HTTP::Request('HEAD',$uri);
                   3419:                         my $response=$ua->request($request);
                   3420:                         if ($response->is_success()) {
                   3421:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3422:                             my $locmodtime = (stat($fname))[9];
                   3423:                             if ($locmodtime < $remmodtime) {
                   3424:                                 my $stale;
                   3425:                                 my $answer = &reply('pong',$homeserver);
                   3426:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3427:                                     sleep(0.2);
                   3428:                                     $locmodtime = (stat($fname))[9];
                   3429:                                     if ($locmodtime < $remmodtime) {
                   3430:                                         my $posstransfer = $fname.'.in.transfer';
                   3431:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3432:                                             $removed = 1;
                   3433:                                         } else {
                   3434:                                             $stale = 1;
                   3435:                                         }
                   3436:                                     } else {
                   3437:                                         $removed = 1;
                   3438:                                     }
                   3439:                                 } else {
                   3440:                                     $stale = 1;
                   3441:                                 }
                   3442:                                 if ($stale) {
1.1172.2.124  raeburn  3443:                                     if (unlink($fname)) {
                   3444:                                         if ($uri!~/\.meta$/) {
                   3445:                                             if (-e $fname.'.meta') {
                   3446:                                                 unlink($fname.'.meta');
                   3447:                                             }
                   3448:                                         }
                   3449:                                         my $unsubresult = &unsubscribe($fname);
                   3450:                                         unless ($unsubresult eq 'ok') {
                   3451:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3452:                                         }
                   3453:                                         $removed = 1;
1.1172.2.98  raeburn  3454:                                     }
                   3455:                                 }
                   3456:                             }
                   3457:                         }
                   3458:                     }
                   3459:                 }
                   3460:             }
                   3461:         }
                   3462:     }
                   3463:     return $removed;
                   3464: }
                   3465: 
1.492     albertel 3466: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3467: 
                   3468: sub allowuploaded {
                   3469:     my ($srcurl,$url)=@_;
                   3470:     $url=&clutter(&declutter($url));
                   3471:     my $dir=$url;
                   3472:     $dir=~s/\/[^\/]+$//;
                   3473:     my %httpref=();
                   3474:     my $httpurl=&hreflocation('',$url);
                   3475:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3476:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3477: }
1.477     raeburn  3478: 
1.1172.2.13  raeburn  3479: #
                   3480: # Determine if the current user should be able to edit a particular resource,
                   3481: # when viewing in course context.
                   3482: # (a) When viewing resource used to determine if "Edit" item is included in
                   3483: #     Functions.
                   3484: # (b) When displaying folder contents in course editor, used to determine if
                   3485: #     "Edit" link will be displayed alongside resource.
                   3486: #
                   3487: #  input: six args -- filename (decluttered), course number, course domain,
                   3488: #                   url, symb (if registered) and group (if this is a group
                   3489: #                   item -- e.g., bulletin board, group page etc.).
                   3490: #  output: array of five scalars --
                   3491: #          $cfile -- url for file editing if editable on current server
                   3492: #          $home -- homeserver of resource (i.e., for author if published,
                   3493: #                                           or course if uploaded.).
                   3494: #          $switchserver --  1 if server switch will be needed.
                   3495: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3496: #          $forceview -- 1 if icon/link should be to go to view mode
                   3497: #
                   3498: 
                   3499: sub can_edit_resource {
                   3500:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3501:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3502: #
                   3503: # For aboutme pages user can only edit his/her own.
                   3504: #
                   3505:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3506:         my ($sdom,$sname) = ($1,$2);
                   3507:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3508:             $home = $env{'user.home'};
                   3509:             $cfile = $resurl;
                   3510:             if ($env{'form.forceedit'}) {
                   3511:                 $forceview = 1;
                   3512:             } else {
                   3513:                 $forceedit = 1;
                   3514:             }
                   3515:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3516:         } else {
                   3517:             return;
                   3518:         }
                   3519:     }
                   3520: 
                   3521:     if ($env{'request.course.id'}) {
                   3522:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3523:         if ($group ne '') {
                   3524: # if this is a group homepage or group bulletin board, check group privs
                   3525:             my $allowed = 0;
                   3526:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3527:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3528:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3529:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3530:                     $allowed = 1;
                   3531:                 }
                   3532:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3533:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3534:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3535:                     $allowed = 1;
                   3536:                 }
                   3537:             }
                   3538:             if ($allowed) {
                   3539:                 $home=&homeserver($cnum,$cdom);
                   3540:                 if ($env{'form.forceedit'}) {
                   3541:                     $forceview = 1;
                   3542:                 } else {
                   3543:                     $forceedit = 1;
                   3544:                 }
                   3545:                 $cfile = $resurl;
                   3546:             } else {
                   3547:                 return;
                   3548:             }
                   3549:         } else {
1.1172.2.15  raeburn  3550:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3551:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3552:                     return;
                   3553:                 }
                   3554:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3555: #
                   3556: # No edit allowed where CC has switched to student role.
                   3557: #
                   3558:                 return;
                   3559:             }
                   3560:         }
                   3561:     }
                   3562: 
                   3563:     if ($file ne '') {
                   3564:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3565:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3566:                 $uploaded = 1;
                   3567:                 $incourse = 1;
                   3568:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3569:                     $cfile = &hreflocation('',$file);
                   3570:                     if ($env{'form.forceedit'}) {
                   3571:                         $forceview = 1;
                   3572:                     } else {
                   3573:                         $forceedit = 1;
                   3574:                     }
                   3575:                 }
                   3576:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3577:                 $incourse = 1;
                   3578:                 if ($env{'form.forceedit'}) {
                   3579:                     $forceview = 1;
                   3580:                 } else {
                   3581:                     $forceedit = 1;
                   3582:                 }
                   3583:                 $cfile = $resurl;
                   3584:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3585:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3586:                     $incourse = 1;
                   3587:                     if ($env{'form.forceedit'}) {
                   3588:                         $forceview = 1;
                   3589:                     } else {
                   3590:                         $forceedit = 1;
                   3591:                     }
                   3592:                     $cfile = $resurl;
                   3593:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3594:                     $incourse = 1;
                   3595:                     $cfile = $resurl.'/smpedit';
                   3596:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3597:                     $incourse = 1;
                   3598:                     if ($env{'form.forceedit'}) {
                   3599:                         $forceview = 1;
                   3600:                     } else {
                   3601:                         $forceedit = 1;
                   3602:                     }
                   3603:                     $cfile = $resurl;
1.1172.2.122  raeburn  3604:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3605:                     my ($map,$id,$res) = &decode_symb($symb);
                   3606:                     if ($map =~ /\.page$/) {
                   3607:                         $incourse = 1;
                   3608:                         if ($env{'form.forceedit'}) {
                   3609:                             $forceview = 1;
                   3610:                             $cfile = $map;
                   3611:                         } else {
                   3612:                             $forceedit = 1;
                   3613:                             $cfile =  '/adm/wrapper'.$resurl;
                   3614:                         }
                   3615:                     }
1.1172.2.146.  .1(raebu 3616:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3617:22):                     $incourse = 1;
                   3618:22):                     if ($env{'form.forceedit'}) {
                   3619:22):                         $forceview = 1;
                   3620:22):                     } else {
                   3621:22):                         $forceedit = 1;
                   3622:22):                     }
                   3623:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3624:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3625:                     $incourse = 1;
                   3626:                     if ($env{'form.forceedit'}) {
                   3627:                         $forceview = 1;
                   3628:                     } else {
                   3629:                         $forceedit = 1;
                   3630:                     }
                   3631:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3632:                 }
                   3633:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3634:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3635:                 if (&is_on_map($template)) {
                   3636:                     $incourse = 1;
                   3637:                     $forceview = 1;
                   3638:                     $cfile = $template;
                   3639:                 }
                   3640:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3641:                 $incourse = 1;
                   3642:                 if ($env{'form.forceedit'}) {
                   3643:                     $forceview = 1;
                   3644:                 } else {
                   3645:                     $forceedit = 1;
                   3646:                 }
                   3647:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3648:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3649:22):                 $incourse = 1;
                   3650:22):                 if ($env{'form.forceedit'}) {
                   3651:22):                     $forceview = 1;
                   3652:22):                 } else {
                   3653:22):                     $forceedit = 1;
                   3654:22):                 }
                   3655:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3656:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3657:                 $incourse = 1;
                   3658:                 $forceview = 1;
                   3659:                 if ($symb) {
                   3660:                     my ($map,$id,$res)=&decode_symb($symb);
                   3661:                     $env{'request.symb'} = $symb;
                   3662:                     $cfile = &clutter($res);
                   3663:                 } else {
                   3664:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3665:22):                     my $escfile = &unescape($cfile);
                   3666:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3667:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3668:22):                     } else {
                   3669:22):                         $escfile =~ s{^http://}{};
                   3670:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3671:22):                     }
1.1172.2.13  raeburn  3672:                 }
1.1172.2.31  raeburn  3673:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3674:                 if ($env{'form.forceedit'}) {
                   3675:                     $forceview = 1;
                   3676:                 } else {
                   3677:                     $forceedit = 1;
                   3678:                 }
                   3679:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3680:             }
                   3681:         }
                   3682:         if ($uploaded || $incourse) {
                   3683:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3684:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3685:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3686:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3687:             # Check that the user has permission to edit this resource
                   3688:             my $setpriv = 1;
                   3689:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3690:             if (defined($cfudom)) {
                   3691:                 $home=&homeserver($cfuname,$cfudom);
                   3692:                 $cfile=$file;
                   3693:             }
                   3694:         }
                   3695:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3696:             (($home ne '') && ($home ne 'no_host'))) {
                   3697:             my @ids=&current_machine_ids();
                   3698:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3699:                 $switchserver=1;
                   3700:             }
                   3701:         }
                   3702:     }
                   3703:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3704: }
                   3705: 
                   3706: sub is_course_upload {
                   3707:     my ($file,$cnum,$cdom) = @_;
                   3708:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3709:     $uploadpath =~ s{^\/}{};
                   3710:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3711:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3712:         return 1;
                   3713:     }
                   3714:     return;
                   3715: }
                   3716: 
                   3717: sub in_course {
                   3718:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3719:     if ($hideprivileged) {
                   3720:         my $skipuser;
1.1172.2.23  raeburn  3721:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3722:         my @possdoms = ($cdom);
                   3723:         if ($coursehash{'checkforpriv'}) {
                   3724:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3725:         }
                   3726:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3727:             $skipuser = 1;
                   3728:             if ($coursehash{'nothideprivileged'}) {
                   3729:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3730:                     my $user;
                   3731:                     if ($item =~ /:/) {
                   3732:                         $user = $item;
                   3733:                     } else {
                   3734:                         $user = join(':',split(/[\@]/,$item));
                   3735:                     }
                   3736:                     if ($user eq $uname.':'.$udom) {
                   3737:                         undef($skipuser);
                   3738:                         last;
                   3739:                     }
                   3740:                 }
                   3741:             }
                   3742:             if ($skipuser) {
                   3743:                 return 0;
                   3744:             }
                   3745:         }
                   3746:     }
                   3747:     $type ||= 'any';
                   3748:     if (!defined($cdom) || !defined($cnum)) {
                   3749:         my $cid  = $env{'request.course.id'};
                   3750:         $cdom = $env{'course.'.$cid.'.domain'};
                   3751:         $cnum = $env{'course.'.$cid.'.num'};
                   3752:     }
                   3753:     my $typesref;
                   3754:     if (($type eq 'any') || ($type eq 'all')) {
                   3755:         $typesref = ['active','previous','future'];
                   3756:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3757:         $typesref = [$type];
                   3758:     }
                   3759:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3760:                               $typesref,undef,[$cdom]);
                   3761:     my ($tmp) = keys(%roles);
                   3762:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3763:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3764:     if (@course_roles > 0) {
                   3765:         return 1;
                   3766:     }
                   3767:     return 0;
                   3768: }
                   3769: 
1.478     albertel 3770: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3771: # input: action, courseID, current domain, intended
1.637     raeburn  3772: #        path to file, source of file, instruction to parse file for objects,
                   3773: #        ref to hash for embedded objects,
                   3774: #        ref to hash for codebase of java objects.
1.1095    raeburn  3775: #        reference to scalar to accommodate mime type determined
                   3776: #          from File::MMagic if $parser = parse.
1.637     raeburn  3777: #
1.485     raeburn  3778: # output: url to file (if action was uploaddoc), 
                   3779: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3780: #
1.478     albertel 3781: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3782: # course.
1.477     raeburn  3783: #
1.478     albertel 3784: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3785: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3786: #          course's home server.
1.477     raeburn  3787: #
1.478     albertel 3788: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3789: #          be copied from $source (current location) to 
                   3790: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3791: #         and will then be copied to
                   3792: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3793: #         course's home server.
1.485     raeburn  3794: #
1.481     raeburn  3795: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3796: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3797: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3798: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3799: #         in course's home server.
1.637     raeburn  3800: #
1.477     raeburn  3801: 
                   3802: sub process_coursefile {
1.1095    raeburn  3803:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3804:         $mimetype)=@_;
1.477     raeburn  3805:     my $fetchresult;
1.638     albertel 3806:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3807:     if ($action eq 'propagate') {
1.638     albertel 3808:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3809: 			     $home);
1.481     raeburn  3810:     } else {
1.477     raeburn  3811:         my $fpath = '';
                   3812:         my $fname = $file;
1.478     albertel 3813:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3814:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3815:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3816:         if ($action eq 'copy') {
                   3817:             if ($source eq '') {
                   3818:                 $fetchresult = 'no source file';
                   3819:                 return $fetchresult;
                   3820:             } else {
                   3821:                 my $destination = $filepath.'/'.$fname;
                   3822:                 rename($source,$destination);
                   3823:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3824:                                  $home);
1.481     raeburn  3825:             }
                   3826:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3827:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3828:             print $fh $env{'form.'.$source};
1.481     raeburn  3829:             close($fh);
1.637     raeburn  3830:             if ($parser eq 'parse') {
1.1024    raeburn  3831:                 my $mm = new File::MMagic;
1.1095    raeburn  3832:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3833:                 if ($type eq 'text/html') {
1.1024    raeburn  3834:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3835:                     unless ($parse_result eq 'ok') {
                   3836:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3837:                     }
1.637     raeburn  3838:                 }
1.1095    raeburn  3839:                 if (ref($mimetype)) {
                   3840:                     $$mimetype = $type;
                   3841:                 } 
1.637     raeburn  3842:             }
1.477     raeburn  3843:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3844:                                  $home);
1.481     raeburn  3845:             if ($fetchresult eq 'ok') {
                   3846:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3847:             } else {
                   3848:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3849:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3850:                 return '/adm/notfound.html';
                   3851:             }
1.477     raeburn  3852:         }
                   3853:     }
1.485     raeburn  3854:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3855:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3856:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3857:     }
                   3858:     return $fetchresult;
                   3859: }
                   3860: 
1.637     raeburn  3861: sub build_filepath {
                   3862:     my ($fpath) = @_;
                   3863:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3864:     unless ($fpath eq '') {
                   3865:         my @parts=split('/',$fpath);
                   3866:         foreach my $part (@parts) {
                   3867:             $filepath.= '/'.$part;
                   3868:             if ((-e $filepath)!=1) {
                   3869:                 mkdir($filepath,0777);
                   3870:             }
                   3871:         }
                   3872:     }
                   3873:     return $filepath;
                   3874: }
                   3875: 
                   3876: sub store_edited_file {
1.638     albertel 3877:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3878:     my $file = $primary_url;
                   3879:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3880:     my $fpath = '';
                   3881:     my $fname = $file;
                   3882:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3883:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3884:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3885:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3886:     print $fh $content;
                   3887:     close($fh);
1.638     albertel 3888:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3889:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3890: 			  $home);
1.637     raeburn  3891:     if ($$fetchresult eq 'ok') {
                   3892:         return '/uploaded/'.$fpath.'/'.$fname;
                   3893:     } else {
1.638     albertel 3894:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3895: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3896:         return '/adm/notfound.html';
                   3897:     }
                   3898: }
                   3899: 
1.531     albertel 3900: sub clean_filename {
1.831     albertel 3901:     my ($fname,$args)=@_;
1.315     www      3902: # Replace Windows backslashes by forward slashes
1.257     www      3903:     $fname=~s/\\/\//g;
1.831     albertel 3904:     if (!$args->{'keep_path'}) {
                   3905:         # Get rid of everything but the actual filename
                   3906: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3907:     }
1.315     www      3908: # Replace spaces by underscores
                   3909:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3910: # Transliterate non-ascii text to ascii
                   3911:     my $lang = &Apache::lonlocal::current_language();
                   3912:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3913: # Replace all other weird characters by nothing
1.831     albertel 3914:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3915: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3916: # numbers
                   3917:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3918: # Replace three or more adjacent underscores with one for consistency
                   3919: # with loncfile::filename_check() so complete url can be extracted by
                   3920: # lonnet::decode_symb()
                   3921:     $fname=~s/_{3,}/_/g;
1.531     albertel 3922:     return $fname;
                   3923: }
1.1172.2.110  raeburn  3924: 
1.1051    raeburn  3925: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3926: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3927: # image with the same aspect ratio as the original, but with dimensions which do 
                   3928: # not exceed $resizewidth and $resizeheight.
                   3929:  
1.984     neumanie 3930: sub resizeImage {
1.1051    raeburn  3931:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3932:     my $ima = Image::Magick->new;
                   3933:     my $resized;
                   3934:     if (-e $img_path) {
                   3935:         $ima->Read($img_path);
                   3936:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3937:             my $width = $ima->Get('width');
                   3938:             my $height = $ima->Get('height');
                   3939:             if ($width > $resizewidth) {
                   3940: 	        my $factor = $width/$resizewidth;
                   3941:                 my $newheight = $height/$factor;
                   3942:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3943:                 $resized = 1;
                   3944:             }
                   3945:         }
                   3946:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3947:             my $width = $ima->Get('width');
                   3948:             my $height = $ima->Get('height');
                   3949:             if ($height > $resizeheight) {
                   3950:                 my $factor = $height/$resizeheight;
                   3951:                 my $newwidth = $width/$factor;
                   3952:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3953:                 $resized = 1;
                   3954:             }
                   3955:         }
                   3956:         if ($resized) {
                   3957:             $ima->Write($img_path);
                   3958:         }
                   3959:     }
                   3960:     return;
1.977     amueller 3961: }
                   3962: 
1.608     albertel 3963: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3964: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3965: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3966: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3967: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3968: #                   if 'coursedoc': upload to the current course
                   3969: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3970: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3971: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3972: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3973: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3974: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3975: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3976: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3977: #        $allfiles - reference to hash for embedded objects
                   3978: #        $codebase - reference to hash for codebase of java objects
                   3979: #        $desuname - username for permanent storage of uploaded file
                   3980: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3981: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3982: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3983: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3984: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3985: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3986: #                    from File::MMagic.
1.858     raeburn  3987: # 
1.686     albertel 3988: # output: url of file in userspace, or error: <message> 
                   3989: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3990: 
1.531     albertel 3991: sub userfileupload {
1.1090    raeburn  3992:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3993:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3994:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3995:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3996:     $fname=&clean_filename($fname);
1.1090    raeburn  3997:     # See if there is anything left
1.257     www      3998:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3999:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4000:     if ($fname =~ /^\./) {
                   4001:         my ($s,$usec) = &gettimeofday();
                   4002:         while (length($usec) < 6) {
                   4003:             $usec = '0'.$usec;
                   4004:         }
                   4005:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4006:     }
1.1090    raeburn  4007:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4008:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4009:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4010:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4011:         my $now = time;
1.1090    raeburn  4012:         my $filepath;
1.1095    raeburn  4013:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4014:              $filepath = 'tmp/helprequests/'.$now;
                   4015:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4016:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4017:                          '_'.$env{'user.domain'}.'/pending';
                   4018:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4019:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4020:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4021:                 $docudom = $destudom;
                   4022:             } else {
                   4023:                 $docudom = $env{'user.domain'};
                   4024:             }
1.1172.2.96  raeburn  4025:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4026:                 $docuname = $destuname;
                   4027:             } else {
                   4028:                 $docuname = $env{'user.name'};
                   4029:             }
                   4030:             if (exists($env{'form.group'})) {
                   4031:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4032:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4033:             }
                   4034:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4035:             if ($context eq 'canceloverwrite') {
                   4036:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4037:                 if (-e  $tempfile) {
                   4038:                     my @info = stat($tempfile);
                   4039:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4040:                         unlink($tempfile);
                   4041:                     }
                   4042:                 }
                   4043:                 return;
1.523     raeburn  4044:             }
                   4045:         }
1.1090    raeburn  4046:         # Create the directory if not present
1.741     raeburn  4047:         my @parts=split(/\//,$filepath);
                   4048:         my $fullpath = $perlvar{'lonDaemons'};
                   4049:         for (my $i=0;$i<@parts;$i++) {
                   4050:             $fullpath .= '/'.$parts[$i];
                   4051:             if ((-e $fullpath)!=1) {
                   4052:                 mkdir($fullpath,0777);
                   4053:             }
                   4054:         }
1.1172.2.96  raeburn  4055:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4056:         print $fh $env{'form.'.$formname};
                   4057:         close($fh);
1.1090    raeburn  4058:         if ($context eq 'existingfile') {
                   4059:             my @info = stat($fullpath.'/'.$fname);
                   4060:             return ($fullpath.'/'.$fname,$info[9]);
                   4061:         } else {
                   4062:             return $fullpath.'/'.$fname;
                   4063:         }
1.523     raeburn  4064:     }
1.995     raeburn  4065:     if ($subdir eq 'scantron') {
                   4066:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4067:     } else {
1.995     raeburn  4068:         $fname="$subdir/$fname";
                   4069:     }
1.1090    raeburn  4070:     if ($context eq 'coursedoc') {
1.638     albertel 4071: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4072: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4073:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4074:             return &finishuserfileupload($docuname,$docudom,
                   4075: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4076: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4077:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4078:         } else {
1.1172.2.21  raeburn  4079:             if ($env{'form.folder'}) {
                   4080:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4081:             }
1.638     albertel 4082:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4083: 				       $fname,$formname,$parser,
1.1095    raeburn  4084: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4085:         }
1.719     banghart 4086:     } elsif (defined($destuname)) {
                   4087:         my $docuname=$destuname;
                   4088:         my $docudom=$destudom;
1.860     raeburn  4089: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4090: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4091:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4092:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4093:     } else {
1.638     albertel 4094:         my $docuname=$env{'user.name'};
                   4095:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4096:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4097:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4098:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4099:         }
1.860     raeburn  4100: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4101: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4102:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4103:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4104:     }
1.271     www      4105: }
                   4106: 
                   4107: sub finishuserfileupload {
1.860     raeburn  4108:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4109:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4110:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4111:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4112:   
1.860     raeburn  4113:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4114:     $file=$fname;
                   4115:     if ($fname=~m|/|) {
                   4116:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4117: 	$path.=$fnamepath.'/';
                   4118:     }
1.259     www      4119:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4120:     my $count;
                   4121:     for ($count=4;$count<=$#parts;$count++) {
                   4122:         $filepath.="/$parts[$count]";
                   4123:         if ((-e $filepath)!=1) {
                   4124: 	    mkdir($filepath,0777);
                   4125:         }
                   4126:     }
1.984     neumanie 4127: 
1.258     www      4128: # Save the file
                   4129:     {
1.1172.2.96  raeburn  4130: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4131: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4132: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4133: 	    return '/adm/notfound.html';
                   4134: 	}
1.1090    raeburn  4135:         if ($context eq 'overwrite') {
1.1117    foxr     4136:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4137:             my $target = $filepath.'/'.$file;
                   4138:             if (-e $source) {
                   4139:                 my @info = stat($source);
                   4140:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4141:                     unless (&File::Copy::move($source,$target)) {
                   4142:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4143:                         return "Moving from $source failed";
                   4144:                     }
                   4145:                 } else {
                   4146:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4147:                 }
                   4148:             } else {
                   4149:                 return "Temporary file: $source missing";
                   4150:             }
                   4151:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4152: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4153: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4154: 	    return '/adm/notfound.html';
                   4155: 	}
1.570     albertel 4156: 	close(FH);
1.1051    raeburn  4157:         if ($resizewidth && $resizeheight) {
                   4158:             my $mm = new File::MMagic;
                   4159:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4160:             if ($mime_type =~ m{^image/}) {
                   4161: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4162:             }  
1.977     amueller 4163: 	}
1.258     www      4164:     }
1.1152    raeburn  4165:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4166:         if (ref($mimetype)) {
                   4167:             if ($$mimetype eq '') {
                   4168:                 my $mm = new File::MMagic;
                   4169:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4170:                 $$mimetype = $type;
                   4171:             }
                   4172:         }
                   4173:     }
1.1172.2.109  raeburn  4174:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4175:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4176:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4177:                                                        $allfiles,$codebase);
                   4178:             unless ($parse_result eq 'ok') {
                   4179:                 &logthis('Failed to parse '.$filepath.$file.
                   4180: 	   	         ' for embedded media: '.$parse_result); 
                   4181:             }
1.637     raeburn  4182:         }
1.1172.2.109  raeburn  4183:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4184:         my $format = $env{'form.scantron_format'};
                   4185:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4186:     }
1.860     raeburn  4187:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4188:         my $input = $filepath.'/'.$file;
                   4189:         my $output = $filepath.'/'.'tn-'.$file;
                   4190:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4191:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4192:         system({$args[0]} @args);
1.860     raeburn  4193:         if (-e $filepath.'/'.'tn-'.$file) {
                   4194:             $fetchthumb  = 1; 
                   4195:         }
                   4196:     }
1.858     raeburn  4197:  
1.259     www      4198: # Notify homeserver to grep it
                   4199: #
1.984     neumanie 4200:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4201:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4202:     if ($fetchresult eq 'ok') {
1.860     raeburn  4203:         if ($fetchthumb) {
                   4204:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4205:             if ($thumbresult ne 'ok') {
                   4206:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4207:                          $docuhome.': '.$thumbresult);
                   4208:             }
                   4209:         }
1.259     www      4210: #
1.258     www      4211: # Return the URL to it
1.494     albertel 4212:         return '/uploaded/'.$path.$file;
1.263     www      4213:     } else {
1.494     albertel 4214:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4215: 		 ': '.$fetchresult);
1.263     www      4216:         return '/adm/notfound.html';
1.858     raeburn  4217:     }
1.493     albertel 4218: }
                   4219: 
1.637     raeburn  4220: sub extract_embedded_items {
1.961     raeburn  4221:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4222:     my @state = ();
1.1164    raeburn  4223:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4224:     my %javafiles = (
                   4225:                       codebase => '',
                   4226:                       code => '',
                   4227:                       archive => ''
                   4228:                     );
                   4229:     my %mediafiles = (
                   4230:                       src => '',
                   4231:                       movie => '',
                   4232:                      );
1.648     raeburn  4233:     my $p;
                   4234:     if ($content) {
                   4235:         $p = HTML::LCParser->new($content);
                   4236:     } else {
1.961     raeburn  4237:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4238:     }
1.641     albertel 4239:     while (my $t=$p->get_token()) {
1.640     albertel 4240: 	if ($t->[0] eq 'S') {
                   4241: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4242: 	    push(@state, $tagname);
1.648     raeburn  4243:             if (lc($tagname) eq 'allow') {
                   4244:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4245:             }
1.640     albertel 4246: 	    if (lc($tagname) eq 'img') {
                   4247: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4248: 	    }
1.886     albertel 4249: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4250:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4251: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4252:                 }
1.886     albertel 4253: 	    }
1.645     raeburn  4254:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4255:                 my $src;
1.645     raeburn  4256:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4257:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4258:                 } else {
1.1164    raeburn  4259:                     if ($attr->{'src'} ne '') {
                   4260:                         $src = $attr->{'src'};
                   4261:                         &add_filetype($allfiles,$src,'src');
                   4262:                     }
                   4263:                 }
                   4264:                 my $text = $p->get_trimmed_text();
                   4265:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4266:                     my @swfargs = split(/,/,$1);
                   4267:                     foreach my $item (@swfargs) {
                   4268:                         $item =~ s/["']//g;
                   4269:                         $item =~ s/^\s+//;
                   4270:                         $item =~ s/\s+$//;
                   4271:                     }
                   4272:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4273:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4274:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4275:                         } else {
                   4276:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4277:                         }
                   4278:                     }
1.645     raeburn  4279:                 }
                   4280:             }
                   4281:             if (lc($tagname) eq 'link') {
                   4282:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4283:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4284:                 }
                   4285:             }
1.640     albertel 4286: 	    if (lc($tagname) eq 'object' ||
                   4287: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4288: 		foreach my $item (keys(%javafiles)) {
                   4289: 		    $javafiles{$item} = '';
                   4290: 		}
1.1164    raeburn  4291:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4292:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4293:                 }
1.640     albertel 4294: 	    }
                   4295: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4296: 		my $name = lc($attr->{'name'});
                   4297: 		foreach my $item (keys(%javafiles)) {
                   4298: 		    if ($name eq $item) {
                   4299: 			$javafiles{$item} = $attr->{'value'};
                   4300: 			last;
                   4301: 		    }
                   4302: 		}
1.1164    raeburn  4303:                 my $pathfrom;
1.640     albertel 4304: 		foreach my $item (keys(%mediafiles)) {
                   4305: 		    if ($name eq $item) {
1.1164    raeburn  4306:                         $pathfrom = $attr->{'value'};
                   4307:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4308: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4309: 			last;
                   4310: 		    }
                   4311: 		}
1.1164    raeburn  4312:                 if ($name eq 'flashvars') {
                   4313:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4314:                 }
                   4315:                 if ($pathfrom ne '') {
                   4316:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4317:                                          $pathfrom);
                   4318:                 }
1.640     albertel 4319: 	    }
                   4320: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4321: 		foreach my $item (keys(%javafiles)) {
                   4322: 		    if ($attr->{$item}) {
                   4323: 			$javafiles{$item} = $attr->{$item};
                   4324: 			last;
                   4325: 		    }
                   4326: 		}
                   4327: 		foreach my $item (keys(%mediafiles)) {
                   4328: 		    if ($attr->{$item}) {
                   4329: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4330: 			last;
                   4331: 		    }
                   4332: 		}
1.1164    raeburn  4333:                 if (lc($tagname) eq 'embed') {
                   4334:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4335:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4336:                                              $attr->{'src'});
                   4337:                     }
                   4338:                 }
1.640     albertel 4339: 	    }
1.1172.2.35  raeburn  4340:             if (lc($tagname) eq 'iframe') {
                   4341:                 my $src = $attr->{'src'} ;
                   4342:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4343:                     &add_filetype($allfiles,$src,'src');
                   4344:                 } elsif ($src =~ m{^/}) {
                   4345:                     if ($env{'request.course.id'}) {
                   4346:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4347:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4348:                         my $url = &hreflocation('',$fullpath);
                   4349:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4350:                             my $relpath = $1;
                   4351:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4352:                                 &add_filetype($allfiles,$1,'src');
                   4353:                             }
                   4354:                         }
                   4355:                     }
                   4356:                 }
                   4357:             }
1.1164    raeburn  4358:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4359:                 pop(@state);
1.1164    raeburn  4360:             }
1.640     albertel 4361: 	} elsif ($t->[0] eq 'E') {
                   4362: 	    my ($tagname) = ($t->[1]);
                   4363: 	    if ($javafiles{'codebase'} ne '') {
                   4364: 		$javafiles{'codebase'} .= '/';
                   4365: 	    }  
                   4366: 	    if (lc($tagname) eq 'applet' ||
                   4367: 		lc($tagname) eq 'object' ||
                   4368: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4369: 		) {
                   4370: 		foreach my $item (keys(%javafiles)) {
                   4371: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4372: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4373: 			&add_filetype($allfiles,$file,$item);
                   4374: 		    }
                   4375: 		}
                   4376: 	    } 
                   4377: 	    pop @state;
                   4378: 	}
                   4379:     }
1.1164    raeburn  4380:     foreach my $id (sort(keys(%flashvars))) {
                   4381:         if ($shockwave{$id} ne '') {
                   4382:             my @pairs = split(/\&/,$flashvars{$id});
                   4383:             foreach my $pair (@pairs) {
                   4384:                 my ($key,$value) = split(/\=/,$pair);
                   4385:                 if ($key eq 'thumb') {
                   4386:                     &add_filetype($allfiles,$value,$key);
                   4387:                 } elsif ($key eq 'content') {
                   4388:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4389:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4390:                     if ($ext ne '') {
                   4391:                         &add_filetype($allfiles,$path.$value,$ext);
                   4392:                     }
                   4393:                 }
                   4394:             }
                   4395:         }
                   4396:     }
1.637     raeburn  4397:     return 'ok';
                   4398: }
                   4399: 
1.639     albertel 4400: sub add_filetype {
                   4401:     my ($allfiles,$file,$type)=@_;
                   4402:     if (exists($allfiles->{$file})) {
                   4403: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4404: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4405: 	}
                   4406:     } else {
                   4407: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4408:     }
                   4409: }
                   4410: 
1.1164    raeburn  4411: sub embedded_dependency {
                   4412:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4413:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4414:         if (($identifier ne '') &&
                   4415:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4416:             ($pathfrom ne '')) {
                   4417:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4418:             foreach my $dep (@{$related->{$identifier}}) {
                   4419:                 &add_filetype($allfiles,$path.$dep,'object');
                   4420:             }
                   4421:         }
                   4422:     }
                   4423:     return;
                   4424: }
                   4425: 
1.1172.2.109  raeburn  4426: sub bubblesheet_converter {
                   4427:     my ($cdom,$fullpath,$config,$format) = @_;
                   4428:     if ((&domain($cdom) ne '') &&
                   4429:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4430:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4431:         my (%csvcols,%csvoptions);
                   4432:         if (ref($config->{'fields'}) eq 'HASH') {
                   4433:             %csvcols = %{$config->{'fields'}};
                   4434:         }
                   4435:         if (ref($config->{'options'}) eq 'HASH') {
                   4436:             %csvoptions = %{$config->{'options'}};
                   4437:         }
                   4438:         my %csvbynum = reverse(%csvcols);
                   4439:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4440:         if (keys(%scantronconf)) {
                   4441:             my %bynum = (
                   4442:                           $scantronconf{CODEstart} => 'CODEstart',
                   4443:                           $scantronconf{IDstart}   => 'IDstart',
                   4444:                           $scantronconf{PaperID}   => 'PaperID',
                   4445:                           $scantronconf{FirstName} => 'FirstName',
                   4446:                           $scantronconf{LastName}  => 'LastName',
                   4447:                           $scantronconf{Qstart}    => 'Qstart',
                   4448:                         );
                   4449:             my @ordered;
                   4450:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4451:                 push(@ordered,$bynum{$item});
                   4452:             }
                   4453:             my %mapstart = (
                   4454:                               CODEstart => 'CODE',
                   4455:                               IDstart   => 'ID',
                   4456:                               PaperID   => 'PaperID',
                   4457:                               FirstName => 'FirstName',
                   4458:                               LastName  => 'LastName',
                   4459:                               Qstart    => 'FirstQuestion',
                   4460:                            );
                   4461:             my %maplength = (
                   4462:                               CODEstart => 'CODElength',
                   4463:                               IDstart   => 'IDlength',
                   4464:                               PaperID   => 'PaperIDlength',
                   4465:                               FirstName => 'FirstNamelength',
                   4466:                               LastName  => 'LastNamelength',
                   4467:             );
                   4468:             if (open(my $fh,'<',$fullpath)) {
                   4469:                 my $output;
                   4470:                 my %lettdig = &letter_to_digits();
                   4471:                 my %diglett = reverse(%lettdig);
                   4472:                 my $numletts = scalar(keys(%lettdig));
                   4473:                 my $num = 0;
                   4474:                 while (my $line=<$fh>) {
                   4475:                     $num ++;
                   4476:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4477:                     $line =~ s{[\r\n]+$}{};
                   4478:                     my %found;
1.1172.2.143  raeburn  4479:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4480:                     my ($qstart,$record);
                   4481:                     for (my $i=0; $i<@values; $i++) {
                   4482:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4483:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4484:                             if ($values[$i] eq '') {
                   4485:                                 $values[$i] = $scantronconf{'Qoff'};
                   4486:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4487:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4488:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4489:                                 }
                   4490:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4491:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4492:                                     $values[$i] = $diglett{$values[$i]};
                   4493:                                 }
                   4494:                             } else {
                   4495:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4496:                                     my $digit;
                   4497:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4498:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4499:                                         if ($values[$i] eq 'J') {
                   4500:                                             $digit += $numletts;
                   4501:                                         }
                   4502:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4503:                                         $digit = $values[$i]-1;
                   4504:                                         if ($values[$i] eq '0') {
                   4505:                                             $digit += $numletts;
                   4506:                                         }
                   4507:                                     }
                   4508:                                     my $qval='';
                   4509:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4510:                                         if ($j == $digit) {
                   4511:                                             $qval .= $scantronconf{'Qon'};
                   4512:                                         } else {
                   4513:                                             $qval .= $scantronconf{'Qoff'};
                   4514:                                         }
                   4515:                                     }
                   4516:                                     $values[$i] = $qval;
                   4517:                                 }
                   4518:                             }
                   4519:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4520:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4521:                             }
                   4522:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4523:                             if ($numblank > 0) {
                   4524:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4525:                             }
                   4526:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4527:                                 $qstart = $i;
                   4528:                                 $found{$csvbynum{$i}} = $values[$i];
                   4529:                             } else {
                   4530:                                 $found{'FirstQuestion'} .= $values[$i];
                   4531:                             }
                   4532:                         } elsif (exists($csvbynum{$i})) {
                   4533:                             if ($csvoptions{'rem'}) {
                   4534:                                 $values[$i] =~ s/^\s+//;
                   4535:                             }
                   4536:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4537:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4538:                                     $values[$i] = '0'.$values[$i];
                   4539:                                 }
                   4540:                             }
                   4541:                             $found{$csvbynum{$i}} = $values[$i];
                   4542:                         }
                   4543:                     }
                   4544:                     foreach my $item (@ordered) {
                   4545:                         my $currlength = 1+length($record);
                   4546:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4547:                         if ($numspaces > 0) {
                   4548:                             $record .= (' ' x $numspaces);
                   4549:                         }
                   4550:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4551:                             unless ($item eq 'Qstart') {
                   4552:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4553:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4554:                                 }
                   4555:                             }
                   4556:                             $record .= $found{$mapstart{$item}};
                   4557:                         }
                   4558:                     }
                   4559:                     $output .= "$record\n";
                   4560:                 }
                   4561:                 close($fh);
                   4562:                 if ($output) {
                   4563:                     if (open(my $fh,'>',$fullpath)) {
                   4564:                         print $fh $output;
                   4565:                         close($fh);
                   4566:                     }
                   4567:                 }
                   4568:             }
                   4569:         }
                   4570:         return;
                   4571:     }
                   4572: }
                   4573: 
                   4574: sub letter_to_digits {
                   4575:     my %lettdig = (
                   4576:                     A => 1,
                   4577:                     B => 2,
                   4578:                     C => 3,
                   4579:                     D => 4,
                   4580:                     E => 5,
                   4581:                     F => 6,
                   4582:                     G => 7,
                   4583:                     H => 8,
                   4584:                     I => 9,
                   4585:                     J => 0,
                   4586:                   );
                   4587:     return %lettdig;
                   4588: }
                   4589: 
                   4590: sub get_scantron_config {
                   4591:     my ($which,$cdom) = @_;
                   4592:     my @lines = &get_scantronformat_file($cdom);
                   4593:     my %config;
                   4594:     #FIXME probably should move to XML it has already gotten a bit much now
                   4595:     foreach my $line (@lines) {
                   4596:         my ($name,$descrip)=split(/:/,$line);
                   4597:         if ($name ne $which ) { next; }
                   4598:         chomp($line);
                   4599:         my @config=split(/:/,$line);
                   4600:         $config{'name'}=$config[0];
                   4601:         $config{'description'}=$config[1];
                   4602:         $config{'CODElocation'}=$config[2];
                   4603:         $config{'CODEstart'}=$config[3];
                   4604:         $config{'CODElength'}=$config[4];
                   4605:         $config{'IDstart'}=$config[5];
                   4606:         $config{'IDlength'}=$config[6];
                   4607:         $config{'Qstart'}=$config[7];
                   4608:         $config{'Qlength'}=$config[8];
                   4609:         $config{'Qoff'}=$config[9];
                   4610:         $config{'Qon'}=$config[10];
                   4611:         $config{'PaperID'}=$config[11];
                   4612:         $config{'PaperIDlength'}=$config[12];
                   4613:         $config{'FirstName'}=$config[13];
                   4614:         $config{'FirstNamelength'}=$config[14];
                   4615:         $config{'LastName'}=$config[15];
                   4616:         $config{'LastNamelength'}=$config[16];
                   4617:         $config{'BubblesPerRow'}=$config[17];
                   4618:         last;
                   4619:     }
                   4620:     return %config;
                   4621: }
                   4622: 
                   4623: sub get_scantronformat_file {
                   4624:     my ($cdom) = @_;
                   4625:     if ($cdom eq '') {
                   4626:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4627:     }
                   4628:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4629:     my $gottab = 0;
                   4630:     my @lines;
                   4631:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4632:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4633:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4634:             if ($formatfile ne '-1') {
                   4635:                 @lines = split("\n",$formatfile,-1);
                   4636:                 $gottab = 1;
                   4637:             }
                   4638:         }
                   4639:     }
                   4640:     if (!$gottab) {
                   4641:         my $confname = $cdom.'-domainconfig';
                   4642:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4643:         my $formatfile = &getfile($default);
                   4644:         if ($formatfile ne '-1') {
                   4645:             @lines = split("\n",$formatfile,-1);
                   4646:             $gottab = 1;
                   4647:         }
                   4648:     }
                   4649:     if (!$gottab) {
                   4650:         my @domains = &current_machine_domains();
                   4651:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4652:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4653:                 @lines = <$fh>;
                   4654:                 close($fh);
                   4655:             }
                   4656:         } else {
                   4657:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4658:                 @lines = <$fh>;
                   4659:                 close($fh);
                   4660:             }
                   4661:         }
                   4662:     }
                   4663:     return @lines;
                   4664: }
                   4665: 
1.493     albertel 4666: sub removeuploadedurl {
1.984     neumanie 4667:     my ($url)=@_;	
                   4668:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4669:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4670: }
                   4671: 
                   4672: sub removeuserfile {
                   4673:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4674:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4675:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4676:     if ($result eq 'ok') {	
1.798     raeburn  4677:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4678:             my $metafile = $fname.'.meta';
                   4679:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4680: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4681:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4682:             my $sqlresult = 
1.823     albertel 4683:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4684:                                         'portfolio_metadata',$group,
                   4685:                                         'delete');
1.798     raeburn  4686:         }
                   4687:     }
                   4688:     return $result;
1.257     www      4689: }
1.15      www      4690: 
1.530     albertel 4691: sub mkdiruserfile {
                   4692:     my ($docuname,$docudom,$dir)=@_;
                   4693:     my $home=&homeserver($docuname,$docudom);
                   4694:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4695: }
                   4696: 
1.531     albertel 4697: sub renameuserfile {
                   4698:     my ($docuname,$docudom,$old,$new)=@_;
                   4699:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4700:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4701:                         &escape("$old").':'.&escape("$new"),$home);
                   4702:     if ($result eq 'ok') {
                   4703:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4704:             my $oldmeta = $old.'.meta';
                   4705:             my $newmeta = $new.'.meta';
                   4706:             my $metaresult = 
                   4707:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4708: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4709:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4710:             my $sqlresult = 
1.823     albertel 4711:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4712:                                         'portfolio_metadata',$group,
                   4713:                                         'delete');
1.798     raeburn  4714:         }
                   4715:     }
                   4716:     return $result;
1.531     albertel 4717: }
                   4718: 
1.14      www      4719: # ------------------------------------------------------------------------- Log
                   4720: 
                   4721: sub log {
                   4722:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4723:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4724: }
                   4725: 
                   4726: # ------------------------------------------------------------------ Course Log
1.352     www      4727: #
                   4728: # This routine flushes several buffers of non-mission-critical nature
                   4729: #
1.157     www      4730: 
                   4731: sub flushcourselogs {
1.352     www      4732:     &logthis('Flushing log buffers');
                   4733: #
                   4734: # course logs
                   4735: # This is a log of all transactions in a course, which can be used
                   4736: # for data mining purposes
                   4737: #
                   4738: # It also collects the courseid database, which lists last transaction
                   4739: # times and course titles for all courseids
                   4740: #
                   4741:     my %courseidbuffer=();
1.921     raeburn  4742:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4743:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4744: 		          &escape($courselogs{$crsid}),
                   4745: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4746: 	    delete $courselogs{$crsid};
                   4747:         } else {
                   4748:             &logthis('Failed to flush log buffer for '.$crsid);
                   4749:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4750:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4751:                         " exceeded maximum size, deleting.</font>");
                   4752:                delete $courselogs{$crsid};
                   4753:             }
1.352     www      4754:         }
1.920     raeburn  4755:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4756:             'description' => $coursedescrbuf{$crsid},
                   4757:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4758:             'type'        => $coursetypebuf{$crsid},
                   4759:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4760:         };
1.191     harris41 4761:     }
1.352     www      4762: #
                   4763: # Write course id database (reverse lookup) to homeserver of courses 
                   4764: # Is used in pickcourse
                   4765: #
1.840     albertel 4766:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4767:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4768:                                     $courseidbuffer{$crs_home},
                   4769:                                     $crs_home,'timeonly');
1.352     www      4770:     }
                   4771: #
                   4772: # File accesses
                   4773: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4774: #
1.449     matthew  4775:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4776:         if ($entry =~ /___count$/) {
                   4777:             my ($dom,$name);
1.807     albertel 4778:             ($dom,$name,undef)=
1.811     albertel 4779: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4780:             if (! defined($dom) || $dom eq '' || 
                   4781:                 ! defined($name) || $name eq '') {
1.620     albertel 4782:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4783: #
                   4784: # FIXME 11/29/2021
                   4785: # Typo in rev. 1.458 (2003/12/09)??
                   4786: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4787: #
                   4788: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4789: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4790: # in a nohist_accesscount.db file for the user rather than the course.
                   4791: #
                   4792: # That said there is a lot of noise in the data being stored.
                   4793: # So counts for prtspool/  and adm/ etc. are recorded.
                   4794: #
                   4795: # A review of which items ending '___count' are written to %accesshash should likely be
                   4796: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4797: #
                   4798: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4799: # accesses for things which are not published resources, regardless of course, and
                   4800: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4801: # anyone in the course for things which are not published resources.
                   4802: #
                   4803: # For an author, nohist_accesscount.db ends up having records for other items
                   4804: # mixed up with the legitimate access counts for the author's published resources.
                   4805: #
1.620     albertel 4806:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4807:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4808:             }
1.450     matthew  4809:             my $value = $accesshash{$entry};
                   4810:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4811:             my %temphash=($url => $value);
1.449     matthew  4812:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4813:             if ($result eq 'ok') {
                   4814:                 delete $accesshash{$entry};
                   4815:             }
                   4816:         } else {
1.811     albertel 4817:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4818:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4819:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4820:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4821:                 delete $accesshash{$entry};
                   4822:             }
1.185     www      4823:         }
1.191     harris41 4824:     }
1.352     www      4825: #
                   4826: # Roles
                   4827: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4828: #
1.800     albertel 4829:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4830:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4831: 	    split(/\:/,$entry);
                   4832:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4833:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4834:                 $rudom,$runame) eq 'ok') {
                   4835: 	    delete $userrolehash{$entry};
                   4836:         }
                   4837:     }
1.662     raeburn  4838: #
1.1172.2.90  raeburn  4839: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4840: #
                   4841:     my %domrolebuffer = ();
1.1000    raeburn  4842:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4843:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4844:         if ($domrolebuffer{$rudom}) {
                   4845:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4846:                       '='.&escape($domainrolehash{$entry});
                   4847:         } else {
                   4848:             $domrolebuffer{$rudom}.=&escape($entry).
                   4849:                       '='.&escape($domainrolehash{$entry});
                   4850:         }
                   4851:         delete $domainrolehash{$entry};
                   4852:     }
                   4853:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4854:         my %servers;
                   4855:         if (defined(&domain($dom,'primary'))) {
                   4856:             my $primary=&domain($dom,'primary');
                   4857:             my $hostname=&hostname($primary);
                   4858:             $servers{$primary} = $hostname;
                   4859:         } else {
                   4860:             %servers = &get_servers($dom,'library');
                   4861:         }
1.841     albertel 4862: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4863: 	    if (&reply('domroleput:'.$dom.':'.
                   4864: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4865: 	        last;
                   4866: 	    } else {
1.841     albertel 4867: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4868: 	    }
1.662     raeburn  4869:         }
                   4870:     }
1.186     www      4871:     $dumpcount++;
1.157     www      4872: }
                   4873: 
                   4874: sub courselog {
                   4875:     my $what=shift;
1.158     www      4876:     $what=time.':'.$what;
1.620     albertel 4877:     unless ($env{'request.course.id'}) { return ''; }
                   4878:     $coursedombuf{$env{'request.course.id'}}=
                   4879:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4880:     $coursenumbuf{$env{'request.course.id'}}=
                   4881:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4882:     $coursehombuf{$env{'request.course.id'}}=
                   4883:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4884:     $coursedescrbuf{$env{'request.course.id'}}=
                   4885:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4886:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4887:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4888:     $courseownerbuf{$env{'request.course.id'}}=
                   4889:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4890:     $coursetypebuf{$env{'request.course.id'}}=
                   4891:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4892:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4893: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4894:     } else {
1.620     albertel 4895: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4896:     }
1.620     albertel 4897:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4898: 	&flushcourselogs();
                   4899:     }
1.158     www      4900: }
                   4901: 
                   4902: sub courseacclog {
                   4903:     my $fnsymb=shift;
1.620     albertel 4904:     unless ($env{'request.course.id'}) { return ''; }
                   4905:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4906:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4907:         $what.=':POST';
1.583     matthew  4908:         # FIXME: Probably ought to escape things....
1.800     albertel 4909: 	foreach my $key (keys(%env)) {
                   4910:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4911:                 my $formitem = $1;
                   4912:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4913:                     $what.=':'.$formitem.'='.$env{$key};
                   4914:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4915:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4916:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4917:                     } else {
                   4918:                         $what.=':'.$formitem.'='.$env{$key};
                   4919:                     }
1.975     raeburn  4920:                 }
1.158     www      4921:             }
1.191     harris41 4922:         }
1.583     matthew  4923:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4924:         # FIXME: We should not be depending on a form parameter that someone
                   4925:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4926:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4927:             $what.= ':POST';
                   4928:             # FIXME: Probably ought to escape things....
                   4929:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4930:                                  'crsdiscuss') {
1.620     albertel 4931:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4932:             }
                   4933:         }
1.158     www      4934:     }
                   4935:     &courselog($what);
1.149     www      4936: }
                   4937: 
1.185     www      4938: sub countacc {
                   4939:     my $url=&declutter(shift);
1.458     matthew  4940:     return if (! defined($url) || $url eq '');
1.620     albertel 4941:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4942: #
                   4943: # Mark that this url was used in this course
                   4944: #
1.620     albertel 4945:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4946: #
                   4947: # Increase the access count for this resource in this child process
                   4948: #
1.281     www      4949:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4950:     $accesshash{$key}++;
1.185     www      4951: }
1.349     www      4952: 
1.361     www      4953: sub linklog {
                   4954:     my ($from,$to)=@_;
                   4955:     $from=&declutter($from);
                   4956:     $to=&declutter($to);
                   4957:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4958:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4959: }
1.1160    www      4960: 
                   4961: sub statslog {
                   4962:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4963:     if ($users<2) { return; }
                   4964:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4965:             'course'       => $env{'request.course.id'},
                   4966:             'sections'     => '"all"',
                   4967:             'num_students' => $users,
                   4968:             'part'         => $part,
                   4969:             'symb'         => $symb,
                   4970:             'mean_tries'   => $av_attempts,
                   4971:             'deg_of_diff'  => $degdiff});
                   4972:     foreach my $key (keys(%dynstore)) {
                   4973:         $accesshash{$key}=$dynstore{$key};
                   4974:     }
                   4975: }
1.361     www      4976:   
1.349     www      4977: sub userrolelog {
                   4978:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4979:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4980:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4981:        $userrolehash
                   4982:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4983:                     =$tend.':'.$tstart;
1.662     raeburn  4984:     }
1.1169    droeschl 4985:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4986:        $userrolehash
                   4987:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4988:                     =$tend.':'.$tstart;
                   4989:     }
1.1172.2.90  raeburn  4990:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4991:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4992:        $domainrolehash
                   4993:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4994:                     = $tend.':'.$tstart;
                   4995:     }
1.351     www      4996: }
                   4997: 
1.957     raeburn  4998: sub courserolelog {
                   4999:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5000:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5001:         my $cdom = $1;
                   5002:         my $cnum = $2;
                   5003:         my $sec = $3;
                   5004:         my $namespace = 'rolelog';
                   5005:         my %storehash = (
                   5006:                            role    => $trole,
                   5007:                            start   => $tstart,
                   5008:                            end     => $tend,
                   5009:                            selfenroll => $selfenroll,
                   5010:                            context    => $context,
                   5011:                         );
                   5012:         if ($trole eq 'gr') {
                   5013:             $namespace = 'groupslog';
                   5014:             $storehash{'group'} = $sec;
                   5015:         } else {
                   5016:             $storehash{'section'} = $sec;
                   5017:         }
                   5018:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5019:                    $domain,$cnum,$cdom);
                   5020:         if (($trole ne 'st') || ($sec ne '')) {
                   5021:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5022:         }
                   5023:     }
                   5024:     return;
                   5025: }
                   5026: 
1.1172.2.9  raeburn  5027: sub domainrolelog {
                   5028:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5029:     if ($area =~ m{^/($match_domain)/$}) {
                   5030:         my $cdom = $1;
                   5031:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5032:         my $namespace = 'rolelog';
                   5033:         my %storehash = (
                   5034:                            role    => $trole,
                   5035:                            start   => $tstart,
                   5036:                            end     => $tend,
                   5037:                            context => $context,
                   5038:                         );
                   5039:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5040:                    $domain,$domconfiguser,$cdom);
                   5041:     }
                   5042:     return;
                   5043: 
                   5044: }
                   5045: 
                   5046: sub coauthorrolelog {
                   5047:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5048:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5049:         my $audom = $1;
                   5050:         my $auname = $2;
                   5051:         my $namespace = 'rolelog';
                   5052:         my %storehash = (
                   5053:                            role    => $trole,
                   5054:                            start   => $tstart,
                   5055:                            end     => $tend,
                   5056:                            context => $context,
                   5057:                         );
                   5058:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5059:                    $domain,$auname,$audom);
                   5060:     }
                   5061:     return;
                   5062: }
                   5063: 
1.351     www      5064: sub get_course_adv_roles {
1.948     raeburn  5065:     my ($cid,$codes) = @_;
1.620     albertel 5066:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5067:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5068:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5069:     my %nothide=();
1.800     albertel 5070:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5071:         if ($user !~ /:/) {
                   5072: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5073:         } else {
                   5074:             $nothide{$user}=1;
                   5075:         }
1.470     www      5076:     }
1.1172.2.23  raeburn  5077:     my @possdoms = ($coursehash{'domain'});
                   5078:     if ($coursehash{'checkforpriv'}) {
                   5079:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5080:     }
1.351     www      5081:     my %returnhash=();
                   5082:     my %dumphash=
                   5083:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5084:     my $now=time;
1.997     raeburn  5085:     my %privileged;
1.1000    raeburn  5086:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5087: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5088:         if (($tstart) && ($tstart<0)) { next; }
                   5089:         if (($tend) && ($tend<$now)) { next; }
                   5090:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5091:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5092: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5093:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5094:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5095: 	if ($role eq 'cr') { next; }
1.948     raeburn  5096:         if ($codes) {
                   5097:             if ($section) { $role .= ':'.$section; }
                   5098:             if ($returnhash{$role}) {
                   5099:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5100:             } else {
                   5101:                 $returnhash{$role}=$username.':'.$domain;
                   5102:             }
1.351     www      5103:         } else {
1.988     raeburn  5104:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5105:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5106:             if ($returnhash{$key}) {
                   5107: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5108:             } else {
                   5109:                 $returnhash{$key}=$username.':'.$domain;
                   5110:             }
1.351     www      5111:         }
1.948     raeburn  5112:     }
1.400     www      5113:     return %returnhash;
                   5114: }
                   5115: 
                   5116: sub get_my_roles {
1.937     raeburn  5117:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5118:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5119:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5120:     my (%dumphash,%nothide);
1.1086    raeburn  5121:     if ($context eq 'userroles') {
1.1166    raeburn  5122:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5123:     } else {
1.1172.2.23  raeburn  5124:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5125:         if ($hidepriv) {
                   5126:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5127:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5128:                 if ($user !~ /:/) {
                   5129:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5130:                 } else {
                   5131:                     $nothide{$user} = 1;
                   5132:                 }
                   5133:             }
                   5134:         }
1.858     raeburn  5135:     }
1.400     www      5136:     my %returnhash=();
                   5137:     my $now=time;
1.999     raeburn  5138:     my %privileged;
1.800     albertel 5139:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5140:         my ($role,$tend,$tstart);
                   5141:         if ($context eq 'userroles') {
1.1149    raeburn  5142:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5143: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5144:         } else {
                   5145:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5146:         }
1.400     www      5147:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5148:         my $status = 'active';
1.939     raeburn  5149:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5150:             $status = 'previous';
                   5151:         } 
                   5152:         if (($tstart) && ($now<$tstart)) {
                   5153:             $status = 'future';
                   5154:         }
                   5155:         if (ref($types) eq 'ARRAY') {
                   5156:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5157:                 next;
                   5158:             } 
                   5159:         } else {
                   5160:             if ($status ne 'active') {
                   5161:                 next;
                   5162:             }
                   5163:         }
1.867     raeburn  5164:         my ($rolecode,$username,$domain,$section,$area);
                   5165:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5166:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5167:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5168:         } else {
                   5169:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5170:         }
1.832     raeburn  5171:         if (ref($roledoms) eq 'ARRAY') {
                   5172:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5173:                 next;
                   5174:             }
                   5175:         }
                   5176:         if (ref($roles) eq 'ARRAY') {
                   5177:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5178:                 if ($role =~ /^cr\//) {
                   5179:                     if (!grep(/^cr$/,@{$roles})) {
                   5180:                         next;
                   5181:                     }
1.1104    raeburn  5182:                 } elsif ($role =~ /^gr\//) {
                   5183:                     if (!grep(/^gr$/,@{$roles})) {
                   5184:                         next;
                   5185:                     }
1.922     raeburn  5186:                 } else {
                   5187:                     next;
                   5188:                 }
1.832     raeburn  5189:             }
1.867     raeburn  5190:         }
1.937     raeburn  5191:         if ($hidepriv) {
1.1172.2.23  raeburn  5192:             my @privroles = ('dc','su');
1.999     raeburn  5193:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5194:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5195:             } else {
1.1172.2.23  raeburn  5196:                 my $possdoms = [$domain];
                   5197:                 if (ref($roledoms) eq 'ARRAY') {
                   5198:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5199:                 }
1.1172.2.23  raeburn  5200:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5201:                     if (!$nothide{$username.':'.$domain}) {
                   5202:                         next;
                   5203:                     }
                   5204:                 }
1.937     raeburn  5205:             }
                   5206:         }
1.933     raeburn  5207:         if ($withsec) {
                   5208:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5209:                 $tstart.':'.$tend;
                   5210:         } else {
                   5211:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5212:         }
1.832     raeburn  5213:     }
1.373     www      5214:     return %returnhash;
1.399     www      5215: }
                   5216: 
1.1172.2.89  raeburn  5217: sub get_all_adhocroles {
                   5218:     my ($dom) = @_;
                   5219:     my @roles_by_num = ();
                   5220:     my %domdefaults = &get_domain_defaults($dom);
                   5221:     my (%description,%access_in_dom,%access_info);
                   5222:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5223:         my $count = 0;
                   5224:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5225:         my %ordered;
                   5226:         foreach my $role (sort(keys(%domcurrent))) {
                   5227:             my ($order,$desc,$access_in_dom);
                   5228:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5229:                 $order = $domcurrent{$role}{'order'};
                   5230:                 $desc = $domcurrent{$role}{'desc'};
                   5231:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5232:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5233:             }
                   5234:             if ($order eq '') {
                   5235:                 $order = $count;
                   5236:             }
                   5237:             $ordered{$order} = $role;
                   5238:             if ($desc ne '') {
                   5239:                 $description{$role} = $desc;
                   5240:             } else {
                   5241:                 $description{$role}= $role;
                   5242:             }
                   5243:             $count++;
                   5244:         }
                   5245:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5246:             push(@roles_by_num,$ordered{$item});
                   5247:         }
                   5248:     }
                   5249:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5250: }
                   5251: 
                   5252: sub get_my_adhocroles {
                   5253:     my ($cid,$checkreg) = @_;
                   5254:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5255:     if ($env{'request.course.id'} eq $cid) {
                   5256:         $cdom = $env{'course.'.$cid.'.domain'};
                   5257:         $cnum = $env{'course.'.$cid.'.num'};
                   5258:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5259:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5260:         $cdom = $1;
                   5261:         $cnum = $2;
                   5262:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5263:                                      $cdom,$cnum);
                   5264:     }
                   5265:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5266:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5267:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5268:         if ($rosterhash{$user} ne '') {
                   5269:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5270:             return ([],{}) if ($type eq 'auto');
                   5271:         }
                   5272:     }
                   5273:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5274:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5275:             my $then=$env{'user.login.time'};
                   5276:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5277:             if (!$update) {
                   5278:                 $update = $then;
                   5279:             }
                   5280:             my @liveroles;
                   5281:             foreach my $role ('dh','da') {
                   5282:                 if ($env{"user.role.$role./$cdom/"}) {
                   5283:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5284:                     my $limit = $update;
                   5285:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5286:                         $limit = $then;
                   5287:                     }
                   5288:                     my $activerole = 1;
                   5289:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5290:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5291:                     if ($activerole) {
                   5292:                         push(@liveroles,$role);
                   5293:                     }
                   5294:                 }
                   5295:             }
                   5296:             if (@liveroles) {
1.1172.2.89  raeburn  5297:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5298:                     my ($accessref,$accessinfo,%access_in_dom);
                   5299:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5300:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5301:                         if (@{$roles_by_num}) {
                   5302:                             my %settings;
                   5303:                             if ($env{'request.course.id'} eq $cid) {
                   5304:                                 foreach my $envkey (keys(%env)) {
                   5305:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5306:                                         $settings{$1} = $env{$envkey};
                   5307:                                     }
                   5308:                                 }
                   5309:                             } else {
                   5310:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5311:                             }
                   5312:                             my %setincrs;
                   5313:                             if ($settings{'internal.adhocaccess'}) {
                   5314:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5315:                             }
                   5316:                             my @statuses;
                   5317:                             if ($env{'environment.inststatus'}) {
                   5318:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5319:                             }
                   5320:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5321:                             if (ref($accessref) eq 'HASH') {
                   5322:                                 %access_in_dom = %{$accessref};
                   5323:                             }
                   5324:                             foreach my $role (@{$roles_by_num}) {
                   5325:                                 my ($curraccess,@okstatus,@personnel);
                   5326:                                 if ($setincrs{$role}) {
                   5327:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5328:                                     if ($curraccess eq 'status') {
                   5329:                                         @okstatus = split(/\&/,$rest);
                   5330:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5331:                                         @personnel = split(/\&/,$rest);
                   5332:                                     }
                   5333:                                 } else {
                   5334:                                     $curraccess = $access_in_dom{$role};
                   5335:                                     if (ref($accessinfo) eq 'HASH') {
                   5336:                                         if ($curraccess eq 'status') {
                   5337:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5338:                                                 @okstatus = @{$accessinfo->{$role}};
                   5339:                                             }
                   5340:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5341:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5342:                                                 @personnel = @{$accessinfo->{$role}};
                   5343:                                             }
                   5344:                                         }
                   5345:                                     }
                   5346:                                 }
                   5347:                                 if ($curraccess eq 'none') {
                   5348:                                     next;
                   5349:                                 } elsif ($curraccess eq 'all') {
                   5350:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5351:                                 } elsif ($curraccess eq 'dh') {
                   5352:                                     if (grep(/^dh$/,@liveroles)) {
                   5353:                                         push(@possroles,$role);
                   5354:                                     } else {
                   5355:                                         next;
                   5356:                                     }
                   5357:                                 } elsif ($curraccess eq 'da') {
                   5358:                                     if (grep(/^da$/,@liveroles)) {
                   5359:                                         push(@possroles,$role);
                   5360:                                     } else {
                   5361:                                         next;
                   5362:                                     }
1.1172.2.89  raeburn  5363:                                 } elsif ($curraccess eq 'status') {
                   5364:                                     if (@okstatus) {
                   5365:                                         if (!@statuses) {
                   5366:                                             if (grep(/^default$/,@okstatus)) {
                   5367:                                                 push(@possroles,$role);
                   5368:                                             }
                   5369:                                         } else {
                   5370:                                             foreach my $status (@okstatus) {
                   5371:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5372:                                                     push(@possroles,$role);
                   5373:                                                     last;
                   5374:                                                 }
                   5375:                                             }
                   5376:                                         }
                   5377:                                     }
                   5378:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5379:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5380:                                         if ($curraccess eq 'exc') {
                   5381:                                             push(@possroles,$role);
                   5382:                                         }
                   5383:                                     } elsif ($curraccess eq 'inc') {
                   5384:                                         push(@possroles,$role);
                   5385:                                     }
                   5386:                                 }
                   5387:                             }
                   5388:                         }
                   5389:                     }
                   5390:                 }
                   5391:             }
                   5392:         }
                   5393:     }
                   5394:     unless (ref($description) eq 'HASH') {
                   5395:         if (ref($roles_by_num) eq 'ARRAY') {
                   5396:             my %desc;
                   5397:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5398:             $description = \%desc;
                   5399:         } else {
                   5400:             $description = {};
                   5401:         }
                   5402:     }
                   5403:     return (\@possroles,$description);
                   5404: }
                   5405: 
1.399     www      5406: # ----------------------------------------------------- Frontpage Announcements
                   5407: #
                   5408: #
                   5409: 
                   5410: sub postannounce {
                   5411:     my ($server,$text)=@_;
1.844     albertel 5412:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5413:     unless ($text=~/\w/) { $text=''; }
                   5414:     return &reply('setannounce:'.&escape($text),$server);
                   5415: }
                   5416: 
                   5417: sub getannounce {
1.448     albertel 5418: 
1.1172.2.96  raeburn  5419:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5420: 	my $announcement='';
1.800     albertel 5421: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5422: 	close($fh);
1.399     www      5423: 	if ($announcement=~/\w/) { 
                   5424: 	    return 
                   5425:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5426:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5427: 	} else {
                   5428: 	    return '';
                   5429: 	}
                   5430:     } else {
                   5431: 	return '';
                   5432:     }
1.351     www      5433: }
1.353     www      5434: 
                   5435: # ---------------------------------------------------------- Course ID routines
                   5436: # Deal with domain's nohist_courseid.db files
                   5437: #
                   5438: 
                   5439: sub courseidput {
1.921     raeburn  5440:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5441:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5442:     my $outcome;
                   5443:     if ($caller eq 'timeonly') {
                   5444:         my $cids = '';
                   5445:         foreach my $item (keys(%$storehash)) {
                   5446:             $cids.=&escape($item).'&';
                   5447:         }
                   5448:         $cids=~s/\&$//;
                   5449:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5450:                           $coursehome);       
                   5451:     } else {
                   5452:         my $items = '';
                   5453:         foreach my $item (keys(%$storehash)) {
                   5454:             $items.= &escape($item).'='.
                   5455:                      &freeze_escape($$storehash{$item}).'&';
                   5456:         }
                   5457:         $items=~s/\&$//;
                   5458:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5459:                           $coursehome);
1.918     raeburn  5460:     }
                   5461:     if ($outcome eq 'unknown_cmd') {
                   5462:         my $what;
                   5463:         foreach my $cid (keys(%$storehash)) {
                   5464:             $what .= &escape($cid).'=';
1.921     raeburn  5465:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5466:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5467:             }
                   5468:             $what =~ s/\:$/&/;
                   5469:         }
                   5470:         $what =~ s/\&$//;  
                   5471:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5472:     } else {
                   5473:         return $outcome;
                   5474:     }
1.353     www      5475: }
                   5476: 
                   5477: sub courseiddump {
1.921     raeburn  5478:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5479:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5480:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5481:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5482:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5483:     my $as_hash = 1;
                   5484:     my %returnhash;
                   5485:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5486:     my %libserv = &all_library();
                   5487:     foreach my $tryserver (keys(%libserv)) {
                   5488:         if ( (  $hostidflag == 1 
                   5489: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5490: 	     || (!defined($hostidflag)) ) {
                   5491: 
1.918     raeburn  5492: 	    if (($domfilter eq '') ||
                   5493: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5494:                 my $rep;
                   5495:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5496:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5497:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5498:                                 &escape($descfilter), &escape($instcodefilter),
                   5499:                                 &escape($ownerfilter), &escape($coursefilter),
                   5500:                                 &escape($typefilter), &escape($regexp_ok),
                   5501:                                 $as_hash, &escape($selfenrollonly),
                   5502:                                 &escape($catfilter), $showhidden, $caller,
                   5503:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5504:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5505:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5506:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5507:                 } else {
                   5508:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5509:                              $sincefilter.':'.&escape($descfilter).':'.
                   5510:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5511:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5512:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5513:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5514:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5515:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5516:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5517:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5518:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5519:                 }
                   5520: 
1.918     raeburn  5521:                 my @pairs=split(/\&/,$rep);
                   5522:                 foreach my $item (@pairs) {
                   5523:                     my ($key,$value)=split(/\=/,$item,2);
                   5524:                     $key = &unescape($key);
                   5525:                     next if ($key =~ /^error: 2 /);
                   5526:                     my $result = &thaw_unescape($value);
                   5527:                     if (ref($result) eq 'HASH') {
                   5528:                         $returnhash{$key}=$result;
                   5529:                     } else {
1.921     raeburn  5530:                         my @responses = split(/:/,$value);
                   5531:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5532:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5533:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5534:                         }
1.1008    raeburn  5535:                     }
1.353     www      5536:                 }
                   5537:             }
                   5538:         }
                   5539:     }
                   5540:     return %returnhash;
                   5541: }
                   5542: 
1.1055    raeburn  5543: sub courselastaccess {
                   5544:     my ($cdom,$cnum,$hostidref) = @_;
                   5545:     my %returnhash;
                   5546:     if ($cdom && $cnum) {
                   5547:         my $chome = &homeserver($cnum,$cdom);
                   5548:         if ($chome ne 'no_host') {
                   5549:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5550:             &extract_lastaccess(\%returnhash,$rep);
                   5551:         }
                   5552:     } else {
                   5553:         if (!$cdom) { $cdom=''; }
                   5554:         my %libserv = &all_library();
                   5555:         foreach my $tryserver (keys(%libserv)) {
                   5556:             if (ref($hostidref) eq 'ARRAY') {
                   5557:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5558:             } 
                   5559:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5560:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5561:                 &extract_lastaccess(\%returnhash,$rep);
                   5562:             }
                   5563:         }
                   5564:     }
                   5565:     return %returnhash;
                   5566: }
                   5567: 
                   5568: sub extract_lastaccess {
                   5569:     my ($returnhash,$rep) = @_;
                   5570:     if (ref($returnhash) eq 'HASH') {
                   5571:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5572:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5573:                  $rep eq '') {
                   5574:             my @pairs=split(/\&/,$rep);
                   5575:             foreach my $item (@pairs) {
                   5576:                 my ($key,$value)=split(/\=/,$item,2);
                   5577:                 $key = &unescape($key);
                   5578:                 next if ($key =~ /^error: 2 /);
                   5579:                 $returnhash->{$key} = &thaw_unescape($value);
                   5580:             }
                   5581:         }
                   5582:     }
                   5583:     return;
                   5584: }
                   5585: 
1.658     raeburn  5586: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5587: 
                   5588: sub dcmailput {
1.685     raeburn  5589:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5590:     my $status = &Apache::lonnet::critical(
1.740     www      5591:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5592:        &escape($message),$server);
1.662     raeburn  5593:     return $status;
                   5594: }
                   5595: 
1.658     raeburn  5596: sub dcmaildump {
                   5597:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5598:     my %returnhash=();
1.846     albertel 5599: 
                   5600:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5601:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5602:                                                          &escape($enddate).':';
                   5603: 	my @esc_senders=map { &escape($_)} @$senders;
                   5604: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5605: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5606:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5607:             if (($key) && ($value)) {
                   5608:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5609:             }
                   5610:         }
                   5611:     }
                   5612:     return %returnhash;
                   5613: }
1.662     raeburn  5614: # ---------------------------------------------------------- Domain roles
                   5615: 
                   5616: sub get_domain_roles {
                   5617:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5618:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5619:         $startdate = '.';
                   5620:     }
1.1018    raeburn  5621:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5622:         $enddate = '.';
                   5623:     }
1.922     raeburn  5624:     my $rolelist;
                   5625:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5626:         $rolelist = join('&',@{$roles});
1.922     raeburn  5627:     }
1.662     raeburn  5628:     my %personnel = ();
1.841     albertel 5629: 
                   5630:     my %servers = &get_servers($dom,'library');
                   5631:     foreach my $tryserver (keys(%servers)) {
                   5632: 	%{$personnel{$tryserver}}=();
                   5633: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5634: 					    &escape($startdate).':'.
                   5635: 					    &escape($enddate).':'.
                   5636: 					    &escape($rolelist), $tryserver))) {
                   5637: 	    my ($key,$value) = split(/\=/,$line,2);
                   5638: 	    if (($key) && ($value)) {
                   5639: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5640: 	    }
                   5641: 	}
1.662     raeburn  5642:     }
                   5643:     return %personnel;
                   5644: }
1.658     raeburn  5645: 
1.1172.2.89  raeburn  5646: sub get_active_domroles {
                   5647:     my ($dom,$roles) = @_;
                   5648:     return () unless (ref($roles) eq 'ARRAY');
                   5649:     my $now = time;
                   5650:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5651:     my %domroles;
                   5652:     foreach my $server (keys(%dompersonnel)) {
                   5653:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5654:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5655:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5656:         }
                   5657:     }
                   5658:     return %domroles;
                   5659: }
                   5660: 
1.1057    www      5661: # ----------------------------------------------------------- Interval timing 
1.149     www      5662: 
1.1153    www      5663: {
                   5664: # Caches needed for speedup of navmaps
                   5665: # We don't want to cache this for very long at all (5 seconds at most)
                   5666: # 
                   5667: # The user for whom we cache
                   5668: my $cachedkey='';
                   5669: # The cached times for this user
                   5670: my %cachedtimes=();
                   5671: # When this was last done
1.1172.2.66  raeburn  5672: my $cachedtime='';
1.1153    www      5673: 
                   5674: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5675:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5676:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5677:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5678:22):         (!$ignorecache)) {
1.1154    raeburn  5679:         return;
                   5680:     }
                   5681:     $cachedtime=time;
                   5682:     $cachedkey=$uname.':'.$udom;
                   5683:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5684: }
                   5685: 
1.504     albertel 5686: sub get_first_access {
1.1172.2.146.  .1(raebu 5687:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5688:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5689:     if ($argsymb) { $symb=$argsymb; }
                   5690:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5691:     if ($argmap) { $map = $argmap; }
1.926     albertel 5692:     if ($type eq 'course') {
                   5693: 	$res='course';
                   5694:     } elsif ($type eq 'map') {
1.588     albertel 5695: 	$res=&symbread($map);
                   5696:     } else {
                   5697: 	$res=$symb;
                   5698:     }
1.1172.2.146.  .1(raebu 5699:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5700:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5701: }
                   5702: 
                   5703: sub set_first_access {
1.1162    raeburn  5704:     my ($type,$interval)=@_;
1.790     albertel 5705:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5706:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5707:     if ($type eq 'course') {
                   5708: 	$res='course';
                   5709:     } elsif ($type eq 'map') {
1.588     albertel 5710: 	$res=&symbread($map);
                   5711:     } else {
                   5712: 	$res=$symb;
                   5713:     }
1.1153    www      5714:     $cachedkey='';
1.1162    raeburn  5715:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5716:     if ($firstaccess) {
                   5717:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5718:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5719:                  "in $courseid");
                   5720:         return 'already_set';
                   5721:     } else {
1.1162    raeburn  5722:         my $start = time;
                   5723: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5724:                           $udom,$uname);
                   5725:         if ($putres eq 'ok') {
                   5726:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5727:                  $udom,$uname); 
                   5728:             &appenv(
                   5729:                      {
                   5730:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5731:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5732:                      }
                   5733:                   );
1.1172.2.97  raeburn  5734:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5735:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5736:             }
1.1172.2.102  raeburn  5737:         } elsif ($putres ne 'refused') {
                   5738:             &logthis("Result: $putres when attempting to set first access time ".
                   5739:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5740:         }
                   5741:         return $putres;
1.505     albertel 5742:     }
                   5743:     return 'already_set';
1.504     albertel 5744: }
1.1153    www      5745: }
1.1172.2.32  raeburn  5746: 
                   5747: sub checkout {
                   5748:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5749:     my $now=time;
                   5750:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5751:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5752:     my $infostr=&escape(
                   5753:                  'CHECKOUTTOKEN&'.
                   5754:                  $tuname.'&'.
                   5755:                  $tudom.'&'.
                   5756:                  $tcrsid.'&'.
                   5757:                  $symb.'&'.
1.1172.2.134  raeburn  5758:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5759:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5760:     if ($token=~/^error\:/) {
                   5761:         &logthis("<font color=\"blue\">WARNING: ".
                   5762:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5763:                  "</font>");
                   5764:         return '';
                   5765:     }
                   5766: 
                   5767:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5768:     $token=~tr/a-z/A-Z/;
                   5769: 
                   5770:     my %infohash=('resource.0.outtoken' => $token,
                   5771:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5772:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5773: 
                   5774:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5775:        return '';
                   5776:     } else {
                   5777:         &logthis("<font color=\"blue\">WARNING: ".
                   5778:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5779:                  "</font>");
                   5780:     }
                   5781: 
                   5782:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5783:                          &escape('Checkout '.$infostr.' - '.
                   5784:                                                  $token)) ne 'ok') {
                   5785:         return '';
                   5786:     } else {
                   5787:         &logthis("<font color=\"blue\">WARNING: ".
                   5788:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5789:                  "</font>");
                   5790:     }
                   5791:     return $token;
                   5792: }
                   5793: 
                   5794: # ------------------------------------------------------------ Check in an item
                   5795: 
                   5796: sub checkin {
                   5797:     my $token=shift;
                   5798:     my $now=time;
                   5799:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5800:     $lonhost=~tr/A-Z/a-z/;
                   5801:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5802:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5803:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5804:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5805:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5806: 
                   5807:     unless (($tuname) && ($tudom)) {
                   5808:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5809:         return '';
                   5810:     }
                   5811: 
                   5812:     unless (&allowed('mgr',$tcrsid)) {
                   5813:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5814:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5815:         return '';
                   5816:     }
                   5817: 
                   5818:     my %infohash=('resource.0.intoken' => $token,
                   5819:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5820:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5821: 
                   5822:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5823:        return '';
                   5824:     }
                   5825: 
                   5826:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5827:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5828:         return '';
                   5829:     }
                   5830: 
                   5831:     return ($symb,$tuname,$tudom,$tcrsid);
                   5832: }
                   5833: 
1.110     www      5834: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5835: 
                   5836: sub expirespread {
                   5837:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5838:     my $cid=$env{'request.course.id'}; 
1.110     www      5839:     if ($cid) {
                   5840:        my $now=time;
                   5841:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5842:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5843:                             $env{'course.'.$cid.'.num'}.
1.110     www      5844: 	        	    ':nohist_expirationdates:'.
                   5845:                             &escape($key).'='.$now,
1.620     albertel 5846:                             $env{'course.'.$cid.'.home'})
1.110     www      5847:     }
                   5848:     return 'ok';
1.14      www      5849: }
                   5850: 
1.109     www      5851: # ----------------------------------------------------- Devalidate Spreadsheets
                   5852: 
                   5853: sub devalidate {
1.325     www      5854:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5855:     my $cid=$env{'request.course.id'}; 
1.109     www      5856:     if ($cid) {
1.391     matthew  5857:         # delete the stored spreadsheets for
                   5858:         # - the student level sheet of this user in course's homespace
                   5859:         # - the assessment level sheet for this resource 
                   5860:         #   for this user in user's homespace
1.553     albertel 5861: 	# - current conditional state info
1.325     www      5862: 	my $key=$uname.':'.$udom.':';
1.109     www      5863:         my $status=
1.299     matthew  5864: 	    &del('nohist_calculatedsheets',
1.391     matthew  5865: 		 [$key.'studentcalc:'],
1.620     albertel 5866: 		 $env{'course.'.$cid.'.domain'},
                   5867: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5868: 		.' '.
                   5869: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5870: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5871:         unless ($status eq 'ok ok') {
                   5872:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5873:                     $uname.' at '.$udom.' for '.
1.109     www      5874: 		    $symb.': '.$status);
1.133     albertel 5875:         }
1.553     albertel 5876: 	&delenv('user.state.'.$cid);
1.109     www      5877:     }
                   5878: }
                   5879: 
1.265     albertel 5880: sub get_scalar {
                   5881:     my ($string,$end) = @_;
                   5882:     my $value;
                   5883:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5884: 	$value = $1;
                   5885:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5886: 	$value = $1;
                   5887:     }
                   5888:     return &unescape($value);
                   5889: }
                   5890: 
                   5891: sub array2str {
                   5892:   my (@array) = @_;
                   5893:   my $result=&arrayref2str(\@array);
                   5894:   $result=~s/^__ARRAY_REF__//;
                   5895:   $result=~s/__END_ARRAY_REF__$//;
                   5896:   return $result;
                   5897: }
                   5898: 
1.204     albertel 5899: sub arrayref2str {
                   5900:   my ($arrayref) = @_;
1.265     albertel 5901:   my $result='__ARRAY_REF__';
1.204     albertel 5902:   foreach my $elem (@$arrayref) {
1.265     albertel 5903:     if(ref($elem) eq 'ARRAY') {
                   5904:       $result.=&arrayref2str($elem).'&';
                   5905:     } elsif(ref($elem) eq 'HASH') {
                   5906:       $result.=&hashref2str($elem).'&';
                   5907:     } elsif(ref($elem)) {
                   5908:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5909:     } else {
                   5910:       $result.=&escape($elem).'&';
                   5911:     }
                   5912:   }
                   5913:   $result=~s/\&$//;
1.265     albertel 5914:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5915:   return $result;
                   5916: }
                   5917: 
1.168     albertel 5918: sub hash2str {
1.204     albertel 5919:   my (%hash) = @_;
                   5920:   my $result=&hashref2str(\%hash);
1.265     albertel 5921:   $result=~s/^__HASH_REF__//;
                   5922:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5923:   return $result;
                   5924: }
                   5925: 
                   5926: sub hashref2str {
                   5927:   my ($hashref)=@_;
1.265     albertel 5928:   my $result='__HASH_REF__';
1.800     albertel 5929:   foreach my $key (sort(keys(%$hashref))) {
                   5930:     if (ref($key) eq 'ARRAY') {
                   5931:       $result.=&arrayref2str($key).'=';
                   5932:     } elsif (ref($key) eq 'HASH') {
                   5933:       $result.=&hashref2str($key).'=';
                   5934:     } elsif (ref($key)) {
1.265     albertel 5935:       $result.='=';
1.800     albertel 5936:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5937:     } else {
1.1132    raeburn  5938: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5939:     }
                   5940: 
1.800     albertel 5941:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5942:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5943:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5944:       $result.=&hashref2str($hashref->{$key}).'&';
                   5945:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5946:        $result.='&';
1.800     albertel 5947:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5948:     } else {
1.800     albertel 5949:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5950:     }
                   5951:   }
1.168     albertel 5952:   $result=~s/\&$//;
1.265     albertel 5953:   $result .= '__END_HASH_REF__';
1.168     albertel 5954:   return $result;
                   5955: }
                   5956: 
                   5957: sub str2hash {
1.265     albertel 5958:     my ($string)=@_;
                   5959:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5960:     return %$hash;
                   5961: }
                   5962: 
                   5963: sub str2hashref {
1.168     albertel 5964:   my ($string) = @_;
1.265     albertel 5965: 
                   5966:   my %hash;
                   5967: 
                   5968:   if($string !~ /^__HASH_REF__/) {
                   5969:       if (! ($string eq '' || !defined($string))) {
                   5970: 	  $hash{'error'}='Not hash reference';
                   5971:       }
                   5972:       return (\%hash, $string);
                   5973:   }
                   5974: 
                   5975:   $string =~ s/^__HASH_REF__//;
                   5976: 
                   5977:   while($string !~ /^__END_HASH_REF__/) {
                   5978:       #key
                   5979:       my $key='';
                   5980:       if($string =~ /^__HASH_REF__/) {
                   5981:           ($key, $string)=&str2hashref($string);
                   5982:           if(defined($key->{'error'})) {
                   5983:               $hash{'error'}='Bad data';
                   5984:               return (\%hash, $string);
                   5985:           }
                   5986:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5987:           ($key, $string)=&str2arrayref($string);
                   5988:           if($key->[0] eq 'Array reference error') {
                   5989:               $hash{'error'}='Bad data';
                   5990:               return (\%hash, $string);
                   5991:           }
                   5992:       } else {
                   5993:           $string =~ s/^(.*?)=//;
1.267     albertel 5994: 	  $key=&unescape($1);
1.265     albertel 5995:       }
                   5996:       $string =~ s/^=//;
                   5997: 
                   5998:       #value
                   5999:       my $value='';
                   6000:       if($string =~ /^__HASH_REF__/) {
                   6001:           ($value, $string)=&str2hashref($string);
                   6002:           if(defined($value->{'error'})) {
                   6003:               $hash{'error'}='Bad data';
                   6004:               return (\%hash, $string);
                   6005:           }
                   6006:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6007:           ($value, $string)=&str2arrayref($string);
                   6008:           if($value->[0] eq 'Array reference error') {
                   6009:               $hash{'error'}='Bad data';
                   6010:               return (\%hash, $string);
                   6011:           }
                   6012:       } else {
                   6013: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6014:       }
                   6015:       $string =~ s/^&//;
                   6016: 
                   6017:       $hash{$key}=$value;
1.204     albertel 6018:   }
1.265     albertel 6019: 
                   6020:   $string =~ s/^__END_HASH_REF__//;
                   6021: 
                   6022:   return (\%hash, $string);
1.204     albertel 6023: }
                   6024: 
                   6025: sub str2array {
1.265     albertel 6026:     my ($string)=@_;
                   6027:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6028:     return @$array;
                   6029: }
                   6030: 
                   6031: sub str2arrayref {
1.204     albertel 6032:   my ($string) = @_;
1.265     albertel 6033:   my @array;
                   6034: 
                   6035:   if($string !~ /^__ARRAY_REF__/) {
                   6036:       if (! ($string eq '' || !defined($string))) {
                   6037: 	  $array[0]='Array reference error';
                   6038:       }
                   6039:       return (\@array, $string);
                   6040:   }
                   6041: 
                   6042:   $string =~ s/^__ARRAY_REF__//;
                   6043: 
                   6044:   while($string !~ /^__END_ARRAY_REF__/) {
                   6045:       my $value='';
                   6046:       if($string =~ /^__HASH_REF__/) {
                   6047:           ($value, $string)=&str2hashref($string);
                   6048:           if(defined($value->{'error'})) {
                   6049:               $array[0] ='Array reference error';
                   6050:               return (\@array, $string);
                   6051:           }
                   6052:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6053:           ($value, $string)=&str2arrayref($string);
                   6054:           if($value->[0] eq 'Array reference error') {
                   6055:               $array[0] ='Array reference error';
                   6056:               return (\@array, $string);
                   6057:           }
                   6058:       } else {
                   6059: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6060:       }
                   6061:       $string =~ s/^&//;
                   6062: 
                   6063:       push(@array, $value);
1.191     harris41 6064:   }
1.265     albertel 6065: 
                   6066:   $string =~ s/^__END_ARRAY_REF__//;
                   6067: 
                   6068:   return (\@array, $string);
1.168     albertel 6069: }
                   6070: 
1.167     albertel 6071: # -------------------------------------------------------------------Temp Store
                   6072: 
1.168     albertel 6073: sub tmpreset {
                   6074:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6075:   if (!$symb) {
                   6076:     $symb=&symbread();
1.620     albertel 6077:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6078:   }
                   6079:   $symb=escape($symb);
                   6080: 
1.620     albertel 6081:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6082:   $namespace=~s/\//\_/g;
                   6083:   $namespace=~s/\W//g;
                   6084: 
1.620     albertel 6085:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6086:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6087:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6088:       $stuname=&get_requestor_ip();
1.591     albertel 6089:   }
1.1117    foxr     6090:   my $path=LONCAPA::tempdir();
1.168     albertel 6091:   my %hash;
                   6092:   if (tie(%hash,'GDBM_File',
                   6093: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6094: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6095:     foreach my $key (keys(%hash)) {
1.180     albertel 6096:       if ($key=~ /:$symb/) {
1.168     albertel 6097: 	delete($hash{$key});
                   6098:       }
                   6099:     }
                   6100:   }
                   6101: }
                   6102: 
1.167     albertel 6103: sub tmpstore {
1.168     albertel 6104:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6105: 
                   6106:   if (!$symb) {
                   6107:     $symb=&symbread();
1.620     albertel 6108:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6109:   }
                   6110:   $symb=escape($symb);
                   6111: 
                   6112:   if (!$namespace) {
                   6113:     # I don't think we would ever want to store this for a course.
                   6114:     # it seems this will only be used if we don't have a course.
1.620     albertel 6115:     #$namespace=$env{'request.course.id'};
1.168     albertel 6116:     #if (!$namespace) {
1.620     albertel 6117:       $namespace=$env{'request.state'};
1.168     albertel 6118:     #}
                   6119:   }
                   6120:   $namespace=~s/\//\_/g;
                   6121:   $namespace=~s/\W//g;
1.620     albertel 6122:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6123:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6124:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6125:       $stuname=&get_requestor_ip();
1.591     albertel 6126:   }
1.168     albertel 6127:   my $now=time;
                   6128:   my %hash;
1.1117    foxr     6129:   my $path=LONCAPA::tempdir();
1.168     albertel 6130:   if (tie(%hash,'GDBM_File',
                   6131: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6132: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6133:     $hash{"version:$symb"}++;
                   6134:     my $version=$hash{"version:$symb"};
                   6135:     my $allkeys=''; 
                   6136:     foreach my $key (keys(%$storehash)) {
                   6137:       $allkeys.=$key.':';
1.591     albertel 6138:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6139:     }
                   6140:     $hash{"$version:$symb:timestamp"}=$now;
                   6141:     $allkeys.='timestamp';
                   6142:     $hash{"$version:keys:$symb"}=$allkeys;
                   6143:     if (untie(%hash)) {
                   6144:       return 'ok';
                   6145:     } else {
                   6146:       return "error:$!";
                   6147:     }
                   6148:   } else {
                   6149:     return "error:$!";
                   6150:   }
                   6151: }
1.167     albertel 6152: 
1.168     albertel 6153: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6154: 
1.168     albertel 6155: sub tmprestore {
                   6156:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6157: 
1.168     albertel 6158:   if (!$symb) {
                   6159:     $symb=&symbread();
1.620     albertel 6160:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6161:   }
                   6162:   $symb=escape($symb);
                   6163: 
1.620     albertel 6164:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6165: 
1.620     albertel 6166:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6167:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6168:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6169:       $stuname=&get_requestor_ip();
1.591     albertel 6170:   }
1.168     albertel 6171:   my %returnhash;
                   6172:   $namespace=~s/\//\_/g;
                   6173:   $namespace=~s/\W//g;
                   6174:   my %hash;
1.1117    foxr     6175:   my $path=LONCAPA::tempdir();
1.168     albertel 6176:   if (tie(%hash,'GDBM_File',
                   6177: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6178: 	  &GDBM_READER(),0640)) {
1.168     albertel 6179:     my $version=$hash{"version:$symb"};
                   6180:     $returnhash{'version'}=$version;
                   6181:     my $scope;
                   6182:     for ($scope=1;$scope<=$version;$scope++) {
                   6183:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6184:       my @keys=split(/:/,$vkeys);
                   6185:       my $key;
                   6186:       $returnhash{"$scope:keys"}=$vkeys;
                   6187:       foreach $key (@keys) {
1.591     albertel 6188: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6189: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6190:       }
                   6191:     }
1.168     albertel 6192:     if (!(untie(%hash))) {
                   6193:       return "error:$!";
                   6194:     }
                   6195:   } else {
                   6196:     return "error:$!";
                   6197:   }
                   6198:   return %returnhash;
1.167     albertel 6199: }
                   6200: 
1.9       www      6201: # ----------------------------------------------------------------------- Store
                   6202: 
                   6203: sub store {
1.1172.2.64  raeburn  6204:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6205:     my $home='';
                   6206: 
1.168     albertel 6207:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6208: 
1.213     www      6209:     $symb=&symbclean($symb);
1.122     albertel 6210:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6211: 
1.620     albertel 6212:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6213:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6214: 
                   6215:     &devalidate($symb,$stuname,$domain);
1.109     www      6216: 
                   6217:     $symb=escape($symb);
1.187     www      6218:     if (!$namespace) { 
1.620     albertel 6219:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6220:           return ''; 
                   6221:        } 
                   6222:     }
1.620     albertel 6223:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6224: 
1.1172.2.138  raeburn  6225:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6226:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6227: 
1.12      www      6228:     my $namevalue='';
1.800     albertel 6229:     foreach my $key (keys(%$storehash)) {
                   6230:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6231:     }
1.12      www      6232:     $namevalue=~s/\&$//;
1.187     www      6233:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6234:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6235: }
                   6236: 
1.47      www      6237: # -------------------------------------------------------------- Critical Store
                   6238: 
                   6239: sub cstore {
1.1172.2.64  raeburn  6240:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6241:     my $home='';
                   6242: 
1.168     albertel 6243:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6244: 
1.213     www      6245:     $symb=&symbclean($symb);
1.122     albertel 6246:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6247: 
1.620     albertel 6248:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6249:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6250: 
                   6251:     &devalidate($symb,$stuname,$domain);
1.109     www      6252: 
                   6253:     $symb=escape($symb);
1.187     www      6254:     if (!$namespace) { 
1.620     albertel 6255:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6256:           return ''; 
                   6257:        } 
                   6258:     }
1.620     albertel 6259:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6260: 
1.1172.2.138  raeburn  6261:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6262:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6263: 
1.47      www      6264:     my $namevalue='';
1.800     albertel 6265:     foreach my $key (keys(%$storehash)) {
                   6266:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6267:     }
1.47      www      6268:     $namevalue=~s/\&$//;
1.187     www      6269:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6270:     return critical
1.1172.2.64  raeburn  6271:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6272: }
                   6273: 
1.9       www      6274: # --------------------------------------------------------------------- Restore
                   6275: 
                   6276: sub restore {
1.124     www      6277:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6278:     my $home='';
                   6279: 
1.168     albertel 6280:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6281: 
1.122     albertel 6282:     if (!$symb) {
1.1172.2.26  raeburn  6283:         return if ($namespace eq 'courserequests');
                   6284:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6285:     } else {
1.1172.2.26  raeburn  6286:         unless ($namespace eq 'courserequests') {
                   6287:             $symb=&escape(&symbclean($symb));
                   6288:         }
1.122     albertel 6289:     }
1.188     www      6290:     if (!$namespace) { 
1.620     albertel 6291:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6292:           return ''; 
                   6293:        } 
                   6294:     }
1.620     albertel 6295:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6296:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6297:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6298:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6299: 
1.12      www      6300:     my %returnhash=();
1.800     albertel 6301:     foreach my $line (split(/\&/,$answer)) {
                   6302: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6303:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6304:     }
1.75      www      6305:     my $version;
                   6306:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6307:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6308:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6309:        }
1.75      www      6310:     }
1.13      www      6311:     return %returnhash;
1.34      www      6312: }
                   6313: 
                   6314: # ---------------------------------------------------------- Course Description
1.1118    foxr     6315: #
                   6316: #  
1.34      www      6317: 
                   6318: sub coursedescription {
1.731     albertel 6319:     my ($courseid,$args)=@_;
1.34      www      6320:     $courseid=~s/^\///;
1.49      www      6321:     $courseid=~s/\_/\//g;
1.34      www      6322:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6323:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6324:     my $normalid=$cdomain.'_'.$cnum;
                   6325:     # need to always cache even if we get errors otherwise we keep 
                   6326:     # trying and trying and trying to get the course description.
                   6327:     my %envhash=();
                   6328:     my %returnhash=();
1.731     albertel 6329:     
                   6330:     my $expiretime=600;
                   6331:     if ($env{'request.course.id'} eq $normalid) {
                   6332: 	$expiretime=120;
                   6333:     }
                   6334: 
                   6335:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6336:     if (!$args->{'freshen_cache'}
                   6337: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6338: 	foreach my $key (keys(%env)) {
                   6339: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6340: 	    my ($setting) = $1;
                   6341: 	    $returnhash{$setting} = $env{$key};
                   6342: 	}
                   6343: 	return %returnhash;
                   6344:     }
                   6345: 
1.1118    foxr     6346:     # get the data again
                   6347: 
1.731     albertel 6348:     if (!$args->{'one_time'}) {
                   6349: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6350:     }
1.811     albertel 6351: 
1.34      www      6352:     if ($chome ne 'no_host') {
1.302     albertel 6353:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6354:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6355: 	   my $username = $env{'user.name'}; # Defult username
                   6356: 	   if(defined $args->{'user'}) {
                   6357: 	       $username = $args->{'user'};
                   6358: 	   }
1.129     albertel 6359:            $returnhash{'home'}= $chome;
                   6360: 	   $returnhash{'domain'} = $cdomain;
                   6361: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6362:            if (!defined($returnhash{'type'})) {
                   6363:                $returnhash{'type'} = 'Course';
                   6364:            }
1.130     albertel 6365:            while (my ($name,$value) = each %returnhash) {
1.53      www      6366:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6367:            }
1.270     www      6368:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6369:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6370: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6371:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6372:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6373:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6374:        }
                   6375:     }
1.731     albertel 6376:     if (!$args->{'one_time'}) {
1.949     raeburn  6377: 	&appenv(\%envhash);
1.731     albertel 6378:     }
1.302     albertel 6379:     return %returnhash;
1.461     www      6380: }
                   6381: 
1.1080    raeburn  6382: sub update_released_required {
                   6383:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6384:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6385:         $cid = $env{'request.course.id'};
                   6386:         $cdom = $env{'course.'.$cid.'.domain'};
                   6387:         $cnum = $env{'course.'.$cid.'.num'};
                   6388:         $chome = $env{'course.'.$cid.'.home'};
                   6389:     }
                   6390:     if ($needsrelease) {
                   6391:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6392:         my $needsupdate;
                   6393:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6394:             $needsupdate = 1;
                   6395:         } else {
                   6396:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6397:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6398:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6399:                 $needsupdate = 1;
                   6400:             }
                   6401:         }
                   6402:         if ($needsupdate) {
                   6403:             my %needshash = (
                   6404:                              'internal.releaserequired' => $needsrelease,
                   6405:                             );
                   6406:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6407:             if ($putresult eq 'ok') {
                   6408:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6409:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6410:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6411:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6412:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6413:                 }
                   6414:             }
                   6415:         }
                   6416:     }
                   6417:     return;
                   6418: }
                   6419: 
1.461     www      6420: # -------------------------------------------------See if a user is privileged
                   6421: 
                   6422: sub privileged {
1.1172.2.23  raeburn  6423:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6424:     my $now = time;
1.1172.2.23  raeburn  6425:     my $roles;
                   6426:     if (ref($possroles) eq 'ARRAY') {
                   6427:         $roles = $possroles;
                   6428:     } else {
                   6429:         $roles = ['dc','su'];
                   6430:     }
                   6431:     if (ref($possdomains) eq 'ARRAY') {
                   6432:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6433:         foreach my $dom (@{$possdomains}) {
                   6434:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6435:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6436:                 foreach my $role (@{$roles}) {
                   6437:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6438:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6439:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6440:                             return 1 unless (($end && $end < $now) ||
                   6441:                                              ($start && $start > $now));
                   6442:                         }
                   6443:                     }
                   6444:                 }
                   6445:             }
                   6446:         }
                   6447:     } else {
                   6448:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6449:         my $now = time;
1.1170    droeschl 6450: 
1.1172.2.58  raeburn  6451:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6452:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6453:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6454:                 return 1 unless ($tend && $tend < $now)
                   6455:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6456:             }
1.1172.2.23  raeburn  6457:         }
                   6458:     }
1.461     www      6459:     return 0;
1.9       www      6460: }
1.1       albertel 6461: 
1.1172.2.23  raeburn  6462: sub privileged_by_domain {
                   6463:     my ($domains,$roles) = @_;
                   6464:     my %privileged = ();
                   6465:     my $cachetime = 60*60*24;
                   6466:     my $now = time;
                   6467:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6468:         return %privileged;
                   6469:     }
                   6470:     foreach my $dom (@{$domains}) {
                   6471:         next if (ref($privileged{$dom}) eq 'HASH');
                   6472:         my $needroles;
                   6473:         foreach my $role (@{$roles}) {
                   6474:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6475:             if (defined($cached)) {
                   6476:                 if (ref($result) eq 'HASH') {
                   6477:                     $privileged{$dom}{$role} = $result;
                   6478:                 }
                   6479:             } else {
                   6480:                 $needroles = 1;
                   6481:             }
                   6482:         }
                   6483:         if ($needroles) {
                   6484:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6485:             $privileged{$dom} = {};
                   6486:             foreach my $server (keys(%dompersonnel)) {
                   6487:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6488:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6489:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6490:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6491:                         next if ($end && $end < $now);
                   6492:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6493:                             $dompersonnel{$server}{$item};
                   6494:                     }
                   6495:                 }
                   6496:             }
                   6497:             if (ref($privileged{$dom}) eq 'HASH') {
                   6498:                 foreach my $role (@{$roles}) {
                   6499:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6500:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6501:                     } else {
                   6502:                         my %hash = ();
                   6503:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6504:                     }
                   6505:                 }
                   6506:             }
                   6507:         }
                   6508:     }
                   6509:     return %privileged;
                   6510: }
                   6511: 
1.103     harris41 6512: # -------------------------------------------------------- Get user privileges
1.11      www      6513: 
                   6514: sub rolesinit {
1.1169    droeschl 6515:     my ($domain, $username) = @_;
                   6516:     my %userroles = ('user.login.time' => time);
                   6517:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6518: 
                   6519:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6520:     # also, blocking can be triggered by an activating timer
                   6521:     # it's saved in the user's %env.
                   6522:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6523:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6524:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6525:         %timerintchk, %timerintenv);
                   6526: 
1.1162    raeburn  6527:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6528:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6529:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6530:     }
1.1169    droeschl 6531: 
1.1162    raeburn  6532:     foreach my $key (keys(%timerinterval)) {
                   6533:         my ($cid,$rest) = split(/\0/,$key);
                   6534:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6535:     }
1.1169    droeschl 6536: 
1.11      www      6537:     my %allroles=();
1.1162    raeburn  6538:     my %allgroups=();
1.11      www      6539: 
1.1172.2.58  raeburn  6540:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6541:         my $role = $rolesdump{$area};
                   6542:         $area =~ s/\_\w\w$//;
                   6543: 
                   6544:         my ($trole, $tend, $tstart, $group_privs);
                   6545: 
                   6546:         if ($role =~ /^cr/) {
                   6547:         # Custom role, defined by a user 
                   6548:         # e.g., user.role.cr/msu/smith/mynewrole
                   6549:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6550:                 $trole = $1;
                   6551:                 ($tend, $tstart) = split('_', $2);
                   6552:             } else {
                   6553:                 $trole = $role;
                   6554:             }
                   6555:         } elsif ($role =~ m|^gr/|) {
                   6556:         # Role of member in a group, defined within a course/community
                   6557:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6558:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6559:             next if $tstart eq '-1';
                   6560:             ($trole, $group_privs) = split(/\//, $trole);
                   6561:             $group_privs = &unescape($group_privs);
                   6562:         } else {
                   6563:         # Just a normal role, defined in roles.tab
                   6564:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6565:         }
                   6566: 
                   6567:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6568:                  $username);
                   6569:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6570: 
                   6571:         # role expired or not available yet?
                   6572:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6573:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6574: 
                   6575:         next if $area eq '' or $trole eq '';
                   6576: 
                   6577:         my $spec = "$trole.$area";
                   6578:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6579: 
                   6580:         if ($trole =~ /^cr\//) {
                   6581:         # Custom role, defined by a user
                   6582:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6583:         } elsif ($trole eq 'gr') {
                   6584:         # Role of a member in a group, defined within a course/community
                   6585:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6586:             next;
                   6587:         } else {
                   6588:         # Normal role, defined in roles.tab
                   6589:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6590:         }
                   6591: 
                   6592:         my $cid = $tdomain.'_'.$trest;
                   6593:         unless ($firstaccchk{$cid}) {
                   6594:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6595:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6596:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6597:                         $coursetimerstarts{$cid}{$item}; 
                   6598:                 }
                   6599:             }
                   6600:             $firstaccchk{$cid} = 1;
                   6601:         }
                   6602:         unless ($timerintchk{$cid}) {
                   6603:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6604:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6605:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6606:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6607:                 }
1.12      www      6608:             }
1.1169    droeschl 6609:             $timerintchk{$cid} = 1;
1.191     harris41 6610:         }
1.11      www      6611:     }
1.1169    droeschl 6612: 
1.1172.2.91  raeburn  6613:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6614:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6615:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6616:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6617: 
1.1162    raeburn  6618:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6619: }
                   6620: 
1.567     raeburn  6621: sub set_arearole {
1.1172.2.19  raeburn  6622:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6623:     unless ($nolog) {
1.567     raeburn  6624: # log the associated role with the area
1.1172.2.19  raeburn  6625:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6626:     }
1.743     albertel 6627:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6628: }
                   6629: 
                   6630: sub custom_roleprivs {
                   6631:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6632:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6633:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6634:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6635:         my ($rdummy,$roledef)=
                   6636:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6637:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6638:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6639:             if (defined($syspriv)) {
1.1043    raeburn  6640:                 if ($trest =~ /^$match_community$/) {
                   6641:                     $syspriv =~ s/bre\&S//; 
                   6642:                 }
1.567     raeburn  6643:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6644:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6645:             }
                   6646:             if ($tdomain ne '') {
                   6647:                 if (defined($dompriv)) {
                   6648:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6649:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6650:                 }
                   6651:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6652:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6653:                         my $rolename = $1;
                   6654:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6655:                     }
1.567     raeburn  6656:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6657:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6658:                 }
                   6659:             }
                   6660:         }
                   6661:     }
                   6662: }
                   6663: 
1.1172.2.89  raeburn  6664: sub course_adhocrole_privs {
                   6665:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6666:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6667:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6668:         my (%currprivs,%storeprivs);
                   6669:         foreach my $item (split(/:/,$coursepriv)) {
                   6670:             my ($priv,$restrict) = split(/\&/,$item);
                   6671:             $currprivs{$priv} = $restrict;
                   6672:         }
                   6673:         my (%possadd,%possremove,%full);
                   6674:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6675:             my ($priv,$restrict)=split(/\&/,$item);
                   6676:             $full{$priv} = $restrict;
                   6677:         }
                   6678:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6679:22):             next if ($item eq '');
                   6680:22):             my ($rule,$rest) = split(/=/,$item);
                   6681:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6682:22):             foreach my $priv (split(/:/,$rest)) {
                   6683:22):                 if ($priv ne '') {
                   6684:22):                     if ($rule eq 'off') {
                   6685:22):                         $possremove{$priv} = 1;
                   6686:22):                     } else {
                   6687:22):                         $possadd{$priv} = 1;
                   6688:22):                     }
                   6689:22):                 }
                   6690:22):             }
                   6691:22):         }
                   6692:22):         foreach my $priv (sort(keys(%full))) {
                   6693:22):             if (exists($currprivs{$priv})) {
                   6694:22):                 unless (exists($possremove{$priv})) {
                   6695:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6696:22):                 }
                   6697:22):             } elsif (exists($possadd{$priv})) {
                   6698:22):                 $storeprivs{$priv} = $full{$priv};
                   6699:22):             }
                   6700:22):         }
                   6701:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6702:22):     }
                   6703:22):     return $coursepriv;
1.1172.2.89  raeburn  6704: }
                   6705: 
1.678     raeburn  6706: sub group_roleprivs {
                   6707:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6708:     my $access = 1;
                   6709:     my $now = time;
                   6710:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6711:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6712:     if ($access) {
1.811     albertel 6713:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6714:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6715:     }
                   6716: }
1.567     raeburn  6717: 
                   6718: sub standard_roleprivs {
                   6719:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6720:     if (defined($pr{$trole.':s'})) {
                   6721:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6722:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6723:     }
                   6724:     if ($tdomain ne '') {
                   6725:         if (defined($pr{$trole.':d'})) {
                   6726:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6727:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6728:         }
                   6729:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6730:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6731:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6732:         }
                   6733:     }
                   6734: }
                   6735: 
                   6736: sub set_userprivs {
1.1064    raeburn  6737:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6738:     my $author=0;
                   6739:     my $adv=0;
1.1172.2.91  raeburn  6740:     my $rar=0;
1.678     raeburn  6741:     my %grouproles = ();
                   6742:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6743:         my @groupkeys; 
1.1000    raeburn  6744:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6745:             push(@groupkeys,$role);
                   6746:         }
                   6747:         if (ref($groups_roles) eq 'HASH') {
                   6748:             foreach my $key (keys(%{$groups_roles})) {
                   6749:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6750:                     push(@groupkeys,$key);
                   6751:                 }
                   6752:             }
                   6753:         }
                   6754:         if (@groupkeys > 0) {
                   6755:             foreach my $role (@groupkeys) {
                   6756:                 my ($trole,$area,$sec,$extendedarea);
                   6757:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6758:                     $trole = $1;
                   6759:                     $area = $2;
                   6760:                     $sec = $3;
                   6761:                     $extendedarea = $area.$sec;
                   6762:                     if (exists($$allgroups{$area})) {
                   6763:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6764:                             my $spec = $trole.'.'.$extendedarea;
                   6765:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6766:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6767:                         }
1.678     raeburn  6768:                     }
                   6769:                 }
                   6770:             }
                   6771:         }
                   6772:     }
1.800     albertel 6773:     foreach my $group (keys(%grouproles)) {
                   6774:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6775:     }
1.800     albertel 6776:     foreach my $role (keys(%{$allroles})) {
                   6777:         my %thesepriv;
1.941     raeburn  6778:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6779:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6780:             if ($item ne '') {
                   6781:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6782:                 if ($restrictions eq '') {
                   6783:                     $thesepriv{$privilege}='F';
                   6784:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6785:                     $thesepriv{$privilege}.=$restrictions;
                   6786:                 }
                   6787:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6788:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6789:             }
                   6790:         }
                   6791:         my $thesestr='';
1.1104    raeburn  6792:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6793: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6794: 	}
                   6795:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6796:     }
1.1172.2.91  raeburn  6797:     return ($author,$adv,$rar);
1.567     raeburn  6798: }
                   6799: 
1.994     raeburn  6800: sub role_status {
1.1104    raeburn  6801:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6802:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6803:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6804:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6805:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6806:             $$where = '/'.$two;
1.994     raeburn  6807:             $$trolecode=$$role.'.'.$$where;
                   6808:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6809:             $$tstatus='is';
1.1104    raeburn  6810:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6811:                 $$tstatus='future';
1.1034    raeburn  6812:                 if ($$tstart<$now) {
                   6813:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6814:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6815:                             my (%allroles,%allgroups,$group_privs,
                   6816:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6817:                             my %userroles = (
                   6818:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6819:                             );
1.1064    raeburn  6820:                             @rolecodes = ('cm'); 
1.1002    raeburn  6821:                             my $spec=$$role.'.'.$$where;
                   6822:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6823:                             if ($$role =~ /^cr\//) {
                   6824:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6825:                                 push(@rolecodes,'cr');
1.1002    raeburn  6826:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6827:                                 push(@rolecodes,$$role);
1.1002    raeburn  6828:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6829:                                                     $env{'user.name'});
1.1064    raeburn  6830:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6831:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6832:                                 $group_privs = &unescape($group_privs);
                   6833:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6834:                                 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  6835:                                 &get_groups_roles($tdomain,$trest,
                   6836:                                                   \%course_roles,\@rolecodes,
                   6837:                                                   \%groups_roles);
1.1002    raeburn  6838:                             } else {
1.1064    raeburn  6839:                                 push(@rolecodes,$$role);
1.1002    raeburn  6840:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6841:                             }
1.1172.2.91  raeburn  6842:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6843:                                                                    \%groups_roles);
1.1064    raeburn  6844:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6845:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6846:                         }
                   6847:                     }
1.1034    raeburn  6848:                     $$tstatus = 'is';
1.1002    raeburn  6849:                 }
1.994     raeburn  6850:             }
                   6851:             if ($$tend) {
1.1104    raeburn  6852:                 if ($$tend<$update) {
1.994     raeburn  6853:                     $$tstatus='expired';
                   6854:                 } elsif ($$tend<$now) {
                   6855:                     $$tstatus='will_not';
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
                   6860: }
                   6861: 
1.1104    raeburn  6862: sub get_groups_roles {
                   6863:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6864:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6865:                   (ref($rolecodes) eq 'ARRAY') && 
                   6866:                   (ref($groups_roles) eq 'HASH')); 
                   6867:     if (keys(%{$cdom_courseroles}) > 0) {
                   6868:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6869:         if ($cdom ne '' && $cnum ne '') {
                   6870:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6871:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6872:                     my $crsrole = $1;
                   6873:                     my $crssec = $2;
                   6874:                     if ($crsrole =~ /^cr/) {
                   6875:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6876:                             push(@{$rolecodes},'cr');
                   6877:                         }
                   6878:                     } else {
                   6879:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6880:                             push(@{$rolecodes},$crsrole);
                   6881:                         }
                   6882:                     }
                   6883:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6884:                     if ($crssec ne '') {
                   6885:                         $rolekey .= "/$crssec";
                   6886:                     }
                   6887:                     $rolekey .= './';
                   6888:                     $groups_roles->{$rolekey} = $rolecodes;
                   6889:                 }
                   6890:             }
                   6891:         }
                   6892:     }
                   6893:     return;
                   6894: }
                   6895: 
                   6896: sub delete_env_groupprivs {
                   6897:     my ($where,$courseroles,$possroles) = @_;
                   6898:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6899:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6900:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6901:         %{$courseroles->{$udom}} =
                   6902:             &get_my_roles('','','userroles',['active'],
                   6903:                           $possroles,[$udom],1);
                   6904:     }
                   6905:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6906:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6907:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6908:             my $area = '/'.$cdom.'/'.$cnum;
                   6909:             my $privkey = "user.priv.$crsrole.$area";
                   6910:             if ($crssec ne '') {
                   6911:                 $privkey .= '/'.$crssec;
                   6912:             }
                   6913:             $privkey .= ".$area/$group";
                   6914:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6915:         }
                   6916:     }
                   6917:     return;
                   6918: }
                   6919: 
1.994     raeburn  6920: sub check_adhoc_privs {
1.1172.2.86  raeburn  6921:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6922:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6923:     if ($sec) {
                   6924:         $cckey .= '/'.$sec;
                   6925:     }
1.1172.2.9  raeburn  6926:     my $setprivs;
1.994     raeburn  6927:     if ($env{$cckey}) {
                   6928:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6929:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6930:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6931:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6932:             $setprivs = 1;
1.994     raeburn  6933:         }
                   6934:     } else {
1.1172.2.87  raeburn  6935:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6936:         $setprivs = 1;
1.994     raeburn  6937:     }
1.1172.2.9  raeburn  6938:     return $setprivs;
1.994     raeburn  6939: }
                   6940: 
                   6941: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6942: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6943:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6944:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6945:     if ($sec ne '') {
                   6946:         $area .= '/'.$sec;
                   6947:     }
1.994     raeburn  6948:     my $spec = $role.'.'.$area;
                   6949:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6950:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6951:     my %rolehash = ();
1.1172.2.89  raeburn  6952:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6953:         my $rolename = $1;
1.1172.2.84  raeburn  6954:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6955:         my %domdef = &get_domain_defaults($dcdom);
                   6956:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6957:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6958:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6959:             }
                   6960:         }
1.1172.2.84  raeburn  6961:     } else {
                   6962:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6963:     }
1.1172.2.91  raeburn  6964:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6965:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6966:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6967:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6968:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6969:         &appenv( {'request.role'        => $spec,
                   6970:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6971:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6972:                  }
                   6973:                );
                   6974:         my $tadv=0;
                   6975:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6976:         &appenv({'request.role.adv'    => $tadv});
                   6977:     }
1.994     raeburn  6978: }
                   6979: 
1.12      www      6980: # --------------------------------------------------------------- get interface
                   6981: 
                   6982: sub get {
1.131     albertel 6983:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6984:    my $items='';
1.800     albertel 6985:    foreach my $item (@$storearr) {
                   6986:        $items.=&escape($item).'&';
1.191     harris41 6987:    }
1.12      www      6988:    $items=~s/\&$//;
1.620     albertel 6989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6990:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6991:    my $uhome=&homeserver($uname,$udomain);
                   6992: 
1.133     albertel 6993:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6994:    my @pairs=split(/\&/,$rep);
1.273     albertel 6995:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6996:      return @pairs;
                   6997:    }
1.15      www      6998:    my %returnhash=();
1.42      www      6999:    my $i=0;
1.800     albertel 7000:    foreach my $item (@$storearr) {
                   7001:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7002:       $i++;
1.191     harris41 7003:    }
1.15      www      7004:    return %returnhash;
1.27      www      7005: }
                   7006: 
                   7007: # --------------------------------------------------------------- del interface
                   7008: 
                   7009: sub del {
1.133     albertel 7010:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7011:    my $items='';
1.800     albertel 7012:    foreach my $item (@$storearr) {
                   7013:        $items.=&escape($item).'&';
1.191     harris41 7014:    }
1.984     neumanie 7015: 
1.27      www      7016:    $items=~s/\&$//;
1.620     albertel 7017:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7018:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7019:    my $uhome=&homeserver($uname,$udomain);
                   7020:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7021: }
                   7022: 
                   7023: # -------------------------------------------------------------- dump interface
                   7024: 
1.1172.2.22  raeburn  7025: sub unserialize {
                   7026:     my ($rep, $escapedkeys) = @_;
                   7027: 
                   7028:     return {} if $rep =~ /^error/;
                   7029: 
                   7030:     my %returnhash=();
                   7031:     foreach my $item (split(/\&/,$rep)) {
                   7032:         my ($key, $value) = split(/=/, $item, 2);
                   7033:         $key = unescape($key) unless $escapedkeys;
                   7034:         next if $key =~ /^error: 2 /;
                   7035:         $returnhash{$key} = &thaw_unescape($value);
                   7036:     }
                   7037:     return \%returnhash;
                   7038: }
                   7039: 
                   7040: # see Lond::dump_with_regexp
                   7041: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7042: sub dump {
1.1172.2.146.  .1(raebu 7043:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7044:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7045:     if (!$uname) { $uname=$env{'user.name'}; }
                   7046:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7047: 
1.1172.2.55  raeburn  7048:     if ($regexp) {
                   7049:         $regexp=&escape($regexp);
                   7050:     } else {
                   7051:         $regexp='.';
                   7052:     }
1.1172.2.22  raeburn  7053:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7054:         # user is hosted on this machine
1.1172.2.55  raeburn  7055:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7056:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7057:         return %{&unserialize($reply, $escapedkeys)};
                   7058:     }
1.1172.2.146.  .1(raebu 7059:22):     my $rep;
                   7060:22):     if ($encrypt) {
                   7061:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7062:22):     } else {
                   7063:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7064:22):     }
1.755     albertel 7065:     my @pairs=split(/\&/,$rep);
                   7066:     my %returnhash=();
1.1098    foxr     7067:     if (!($rep =~ /^error/ )) {
                   7068: 	foreach my $item (@pairs) {
                   7069: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7070:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7071: 	    next if ($key =~ /^error: 2 /);
                   7072: 	    $returnhash{$key}=&thaw_unescape($value);
                   7073: 	}
1.755     albertel 7074:     }
                   7075:     return %returnhash;
1.407     www      7076: }
                   7077: 
1.1098    foxr     7078: 
1.717     albertel 7079: # --------------------------------------------------------- dumpstore interface
                   7080: 
                   7081: sub dumpstore {
                   7082:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7083:    # same as dump but keys must be escaped. They may contain colon separated
                   7084:    # lists of values that may themself contain colons (e.g. symbs).
                   7085:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7086: }
                   7087: 
1.407     www      7088: # -------------------------------------------------------------- keys interface
                   7089: 
                   7090: sub getkeys {
                   7091:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7093:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7094:    my $uhome=&homeserver($uname,$udomain);
                   7095:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7096:    my @keyarray=();
1.800     albertel 7097:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7098:       next if ($key =~ /^error: 2 /);
1.800     albertel 7099:       push(@keyarray,&unescape($key));
1.407     www      7100:    }
                   7101:    return @keyarray;
1.318     matthew  7102: }
                   7103: 
1.319     matthew  7104: # --------------------------------------------------------------- currentdump
                   7105: sub currentdump {
1.328     matthew  7106:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7107:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7108:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7109:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7110:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7111:    my $rep;
                   7112: 
                   7113:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7114:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7115:                    $courseid)));
                   7116:    } else {
                   7117:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7118:    }
                   7119: 
1.318     matthew  7120:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7121:    #
1.318     matthew  7122:    my %returnhash=();
1.319     matthew  7123:    #
                   7124:    if ($rep eq "unknown_cmd") { 
                   7125:        # an old lond will not know currentdump
                   7126:        # Do a dump and make it look like a currentdump
1.822     albertel 7127:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7128:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7129:        my %hash = @tmp;
                   7130:        @tmp=();
1.424     matthew  7131:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7132:    } else {
                   7133:        my @pairs=split(/\&/,$rep);
1.800     albertel 7134:        foreach my $pair (@pairs) {
                   7135:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7136:            my ($symb,$param) = split(/:/,$key);
                   7137:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7138:                                                         &thaw_unescape($value);
1.319     matthew  7139:        }
1.191     harris41 7140:    }
1.12      www      7141:    return %returnhash;
1.424     matthew  7142: }
                   7143: 
                   7144: sub convert_dump_to_currentdump{
                   7145:     my %hash = %{shift()};
                   7146:     my %returnhash;
                   7147:     # Code ripped from lond, essentially.  The only difference
                   7148:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7149:     # we might run in to problems with parameter names =~ /^v\./
                   7150:     while (my ($key,$value) = each(%hash)) {
                   7151:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7152: 	$symb  = &unescape($symb);
                   7153: 	$param = &unescape($param);
1.424     matthew  7154:         next if ($v eq 'version' || $symb eq 'keys');
                   7155:         next if (exists($returnhash{$symb}) &&
                   7156:                  exists($returnhash{$symb}->{$param}) &&
                   7157:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7158:         $returnhash{$symb}->{$param}=$value;
                   7159:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7160:     }
                   7161:     #
                   7162:     # Remove all of the keys in the hashes which keep track of
                   7163:     # the version of the parameter.
                   7164:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7165:         # use a foreach because we are going to delete from the hash.
                   7166:         foreach my $key (keys(%$param_hash)) {
                   7167:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7168:         }
                   7169:     }
                   7170:     return \%returnhash;
1.12      www      7171: }
                   7172: 
1.627     albertel 7173: # ------------------------------------------------------ critical inc interface
                   7174: 
                   7175: sub cinc {
                   7176:     return &inc(@_,'critical');
                   7177: }
                   7178: 
1.449     matthew  7179: # --------------------------------------------------------------- inc interface
                   7180: 
                   7181: sub inc {
1.627     albertel 7182:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7183:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7184:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7185:     my $uhome=&homeserver($uname,$udomain);
                   7186:     my $items='';
                   7187:     if (! ref($store)) {
                   7188:         # got a single value, so use that instead
                   7189:         $items = &escape($store).'=&';
                   7190:     } elsif (ref($store) eq 'SCALAR') {
                   7191:         $items = &escape($$store).'=&';        
                   7192:     } elsif (ref($store) eq 'ARRAY') {
                   7193:         $items = join('=&',map {&escape($_);} @{$store});
                   7194:     } elsif (ref($store) eq 'HASH') {
                   7195:         while (my($key,$value) = each(%{$store})) {
                   7196:             $items.= &escape($key).'='.&escape($value).'&';
                   7197:         }
                   7198:     }
                   7199:     $items=~s/\&$//;
1.627     albertel 7200:     if ($critical) {
                   7201: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7202:     } else {
                   7203: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7204:     }
1.449     matthew  7205: }
                   7206: 
1.12      www      7207: # --------------------------------------------------------------- put interface
                   7208: 
                   7209: sub put {
1.1172.2.146.  .1(raebu 7210:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7211:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7212:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7213:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7214:    my $items='';
1.800     albertel 7215:    foreach my $item (keys(%$storehash)) {
                   7216:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7217:    }
1.12      www      7218:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7219:22):    if ($encrypt) {
                   7220:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7221:22):    } else {
                   7222:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7223:22):    }
1.47      www      7224: }
                   7225: 
1.631     albertel 7226: # ------------------------------------------------------------ newput interface
                   7227: 
                   7228: sub newput {
                   7229:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7230:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7231:    if (!$uname) { $uname=$env{'user.name'}; }
                   7232:    my $uhome=&homeserver($uname,$udomain);
                   7233:    my $items='';
                   7234:    foreach my $key (keys(%$storehash)) {
                   7235:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7236:    }
                   7237:    $items=~s/\&$//;
                   7238:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7239: }
                   7240: 
                   7241: # ---------------------------------------------------------  putstore interface
                   7242: 
1.524     raeburn  7243: sub putstore {
1.1172.2.59  raeburn  7244:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7245:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7246:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7247:    my $uhome=&homeserver($uname,$udomain);
                   7248:    my $items='';
1.715     albertel 7249:    foreach my $key (keys(%$storehash)) {
                   7250:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7251:    }
1.715     albertel 7252:    $items=~s/\&$//;
1.716     albertel 7253:    my $esc_symb=&escape($symb);
                   7254:    my $esc_v=&escape($version);
1.715     albertel 7255:    my $reply =
1.716     albertel 7256:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7257: 	      $uhome);
1.1172.2.59  raeburn  7258:    if (($tolog) && ($reply eq 'ok')) {
                   7259:        my $namevalue='';
                   7260:        foreach my $key (keys(%{$storehash})) {
                   7261:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7262:        }
1.1172.2.134  raeburn  7263:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7264:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7265:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7266:                      '&version='.$esc_v.
                   7267:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7268:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7269:    }
1.715     albertel 7270:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7271:        # gfall back to way things use to be done
1.715     albertel 7272:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7273: 			    $uname);
1.524     raeburn  7274:    }
1.715     albertel 7275:    return $reply;
                   7276: }
                   7277: 
                   7278: sub old_putstore {
1.716     albertel 7279:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7280:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7281:     if (!$uname) { $uname=$env{'user.name'}; }
                   7282:     my $uhome=&homeserver($uname,$udomain);
                   7283:     my %newstorehash;
1.800     albertel 7284:     foreach my $item (keys(%$storehash)) {
                   7285: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7286: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7287:     }
                   7288:     my $items='';
                   7289:     my %allitems = ();
1.800     albertel 7290:     foreach my $item (keys(%newstorehash)) {
                   7291: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7292: 	    my $key = $1.':keys:'.$2;
                   7293: 	    $allitems{$key} .= $3.':';
                   7294: 	}
1.800     albertel 7295: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7296:     }
1.800     albertel 7297:     foreach my $item (keys(%allitems)) {
                   7298: 	$allitems{$item} =~ s/\:$//;
                   7299: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7300:     }
                   7301:     $items=~s/\&$//;
                   7302:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7303: }
                   7304: 
1.47      www      7305: # ------------------------------------------------------ critical put interface
                   7306: 
                   7307: sub cput {
1.134     albertel 7308:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7309:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7310:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7311:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7312:    my $items='';
1.800     albertel 7313:    foreach my $item (keys(%$storehash)) {
                   7314:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7315:    }
1.47      www      7316:    $items=~s/\&$//;
1.134     albertel 7317:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7318: }
                   7319: 
                   7320: # -------------------------------------------------------------- eget interface
                   7321: 
                   7322: sub eget {
1.133     albertel 7323:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7324:    my $items='';
1.800     albertel 7325:    foreach my $item (@$storearr) {
                   7326:        $items.=&escape($item).'&';
1.191     harris41 7327:    }
1.12      www      7328:    $items=~s/\&$//;
1.620     albertel 7329:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7330:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7331:    my $uhome=&homeserver($uname,$udomain);
                   7332:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7333:    my @pairs=split(/\&/,$rep);
                   7334:    my %returnhash=();
1.42      www      7335:    my $i=0;
1.800     albertel 7336:    foreach my $item (@$storearr) {
                   7337:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7338:       $i++;
1.191     harris41 7339:    }
1.12      www      7340:    return %returnhash;
                   7341: }
                   7342: 
1.667     albertel 7343: # ------------------------------------------------------------ tmpput interface
                   7344: sub tmpput {
1.802     raeburn  7345:     my ($storehash,$server,$context)=@_;
1.667     albertel 7346:     my $items='';
1.800     albertel 7347:     foreach my $item (keys(%$storehash)) {
                   7348: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7349:     }
                   7350:     $items=~s/\&$//;
1.802     raeburn  7351:     if (defined($context)) {
                   7352:         $items .= ':'.&escape($context);
                   7353:     }
1.667     albertel 7354:     return &reply("tmpput:$items",$server);
                   7355: }
                   7356: 
                   7357: # ------------------------------------------------------------ tmpget interface
                   7358: sub tmpget {
1.688     albertel 7359:     my ($token,$server)=@_;
                   7360:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7361:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7362:     my %returnhash;
1.1172.2.85  raeburn  7363:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7364:         return %returnhash;
                   7365:     }
1.667     albertel 7366:     foreach my $item (split(/\&/,$rep)) {
                   7367: 	my ($key,$value)=split(/=/,$item);
                   7368: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7369:     }
                   7370:     return %returnhash;
                   7371: }
                   7372: 
1.1113    raeburn  7373: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7374: sub tmpdel {
                   7375:     my ($token,$server)=@_;
                   7376:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7377:     return &reply("tmpdel:$token",$server);
                   7378: }
                   7379: 
1.1172.2.13  raeburn  7380: # ------------------------------------------------------------ get_timebased_id
                   7381: 
                   7382: sub get_timebased_id {
                   7383:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7384:         $maxtries) = @_;
                   7385:     my ($newid,$error,$dellock);
                   7386:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7387:         return ('','ok','invalid call to get suffix');
                   7388:     }
                   7389: 
                   7390: # set defaults for any optional args for which values were not supplied
                   7391:     if ($who eq '') {
                   7392:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7393:     }
                   7394:     if (!$locktries) {
                   7395:         $locktries = 3;
                   7396:     }
                   7397:     if (!$maxtries) {
                   7398:         $maxtries = 10;
                   7399:     }
                   7400: 
                   7401:     if (($cdom eq '') || ($cnum eq '')) {
                   7402:         if ($env{'request.course.id'}) {
                   7403:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7404:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7405:         }
                   7406:         if (($cdom eq '') || ($cnum eq '')) {
                   7407:             return ('','ok','call to get suffix not in course context');
                   7408:         }
                   7409:     }
                   7410: 
                   7411: # construct locking item
                   7412:     my $lockhash = {
                   7413:                       $prefix."\0".'locked_'.$keyid => $who,
                   7414:                    };
                   7415:     my $tries = 0;
                   7416: 
                   7417: # attempt to get lock on nohist_$namespace file
                   7418:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7419:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7420:         $tries ++;
                   7421:         sleep 1;
                   7422:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7423:     }
                   7424: 
                   7425: # attempt to get unique identifier, based on current timestamp
                   7426:     if ($gotlock eq 'ok') {
                   7427:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7428:         my $id = time;
                   7429:         $newid = $id;
1.1172.2.56  raeburn  7430:         if ($idtype eq 'addcode') {
                   7431:             $newid .= &sixnum_code();
                   7432:         }
1.1172.2.13  raeburn  7433:         my $idtries = 0;
                   7434:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7435:             if ($idtype eq 'concat') {
                   7436:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7437:             } elsif ($idtype eq 'addcode') {
                   7438:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7439:             } else {
                   7440:                 $newid ++;
                   7441:             }
                   7442:             $idtries ++;
                   7443:         }
                   7444:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7445:             my %new_item =  (
                   7446:                               $prefix."\0".$newid => $who,
                   7447:                             );
                   7448:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7449:                                                  $cdom,$cnum);
                   7450:             if ($putresult ne 'ok') {
                   7451:                 undef($newid);
                   7452:                 $error = 'error saving new item: '.$putresult;
                   7453:             }
                   7454:         } else {
1.1172.2.56  raeburn  7455:              undef($newid);
1.1172.2.13  raeburn  7456:              $error = ('error: no unique suffix available for the new item ');
                   7457:         }
                   7458: #  remove lock
                   7459:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7460:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7461:     } else {
                   7462:         $error = "error: could not obtain lockfile\n";
                   7463:         $dellock = 'ok';
1.1172.2.58  raeburn  7464:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7465:             $dellock = 'nolock';
                   7466:         }
1.1172.2.13  raeburn  7467:     }
                   7468:     return ($newid,$dellock,$error);
                   7469: }
                   7470: 
1.1172.2.56  raeburn  7471: sub sixnum_code {
                   7472:     my $code;
                   7473:     for (0..6) {
                   7474:         $code .= int( rand(9) );
                   7475:     }
                   7476:     return $code;
                   7477: }
                   7478: 
1.765     albertel 7479: # -------------------------------------------------- portfolio access checking
                   7480: 
                   7481: sub portfolio_access {
1.1172.2.77  raeburn  7482:     my ($requrl,$clientip) = @_;
1.765     albertel 7483:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7484:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7485:     if ($result) {
                   7486:         my %setters;
                   7487:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7488:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7489:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7490:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7491:                 return 'B';
                   7492:             }
                   7493:         } else {
1.1172.2.142  raeburn  7494:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7495:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7496:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7497:                 return 'B';
                   7498:             }
                   7499:         }
                   7500:     }
1.765     albertel 7501:     if ($result eq 'ok') {
1.766     albertel 7502:        return 'F';
1.765     albertel 7503:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7504:        return 'A';
1.765     albertel 7505:     }
1.766     albertel 7506:     return '';
1.765     albertel 7507: }
                   7508: 
                   7509: sub get_portfolio_access {
1.1172.2.77  raeburn  7510:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7511: 
                   7512:     if (!ref($access_hash)) {
                   7513: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7514: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7515: 						   $file_name);
                   7516: 	$access_hash = $access_controls{$file_name};
                   7517:     }
                   7518: 
1.1172.2.77  raeburn  7519:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7520:     my $now = time;
                   7521:     if (ref($access_hash) eq 'HASH') {
                   7522:         foreach my $key (keys(%{$access_hash})) {
                   7523:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7524:             if ($start > $now) {
                   7525:                 next;
                   7526:             }
                   7527:             if ($end && $end<$now) {
                   7528:                 next;
                   7529:             }
                   7530:             if ($scope eq 'public') {
                   7531:                 $public = $key;
                   7532:                 last;
                   7533:             } elsif ($scope eq 'guest') {
                   7534:                 $guest = $key;
                   7535:             } elsif ($scope eq 'domains') {
                   7536:                 push(@domains,$key);
                   7537:             } elsif ($scope eq 'users') {
                   7538:                 push(@users,$key);
                   7539:             } elsif ($scope eq 'course') {
                   7540:                 push(@courses,$key);
                   7541:             } elsif ($scope eq 'group') {
                   7542:                 push(@groups,$key);
1.1172.2.77  raeburn  7543:             } elsif ($scope eq 'ip') {
                   7544:                 push(@ips,$key);
1.765     albertel 7545:             }
                   7546:         }
                   7547:         if ($public) {
                   7548:             return 'ok';
1.1172.2.77  raeburn  7549:         } elsif (@ips > 0) {
                   7550:             my $allowed;
                   7551:             foreach my $ipkey (@ips) {
                   7552:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7553:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7554:                         $allowed = 1;
                   7555:                         last;
                   7556:                     }
                   7557:                 }
                   7558:             }
                   7559:             if ($allowed) {
                   7560:                 return 'ok';
                   7561:             }
1.765     albertel 7562:         }
                   7563:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7564:             if ($guest) {
                   7565:                 return $guest;
                   7566:             }
                   7567:         } else {
                   7568:             if (@domains > 0) {
                   7569:                 foreach my $domkey (@domains) {
                   7570:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7571:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7572:                             return 'ok';
                   7573:                         }
                   7574:                     }
                   7575:                 }
                   7576:             }
                   7577:             if (@users > 0) {
                   7578:                 foreach my $userkey (@users) {
1.865     raeburn  7579:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7580:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7581:                             if (ref($item) eq 'HASH') {
                   7582:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7583:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7584:                                     return 'ok';
                   7585:                                 }
                   7586:                             }
                   7587:                         }
                   7588:                     } 
1.765     albertel 7589:                 }
                   7590:             }
                   7591:             my %roleshash;
                   7592:             my @courses_and_groups = @courses;
                   7593:             push(@courses_and_groups,@groups); 
                   7594:             if (@courses_and_groups > 0) {
                   7595:                 my (%allgroups,%allroles); 
                   7596:                 my ($start,$end,$role,$sec,$group);
                   7597:                 foreach my $envkey (%env) {
1.1060    raeburn  7598:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7599:                         my $cid = $2.'_'.$3; 
                   7600:                         if ($1 eq 'gr') {
                   7601:                             $group = $4;
                   7602:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7603:                         } else {
                   7604:                             if ($4 eq '') {
                   7605:                                 $sec = 'none';
                   7606:                             } else {
                   7607:                                 $sec = $4;
                   7608:                             }
                   7609:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7610:                         }
1.811     albertel 7611:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7612:                         my $cid = $2.'_'.$3;
                   7613:                         if ($4 eq '') {
                   7614:                             $sec = 'none';
                   7615:                         } else {
                   7616:                             $sec = $4;
                   7617:                         }
                   7618:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7619:                     }
                   7620:                 }
                   7621:                 if (keys(%allroles) == 0) {
                   7622:                     return;
                   7623:                 }
                   7624:                 foreach my $key (@courses_and_groups) {
                   7625:                     my %content = %{$$access_hash{$key}};
                   7626:                     my $cnum = $content{'number'};
                   7627:                     my $cdom = $content{'domain'};
                   7628:                     my $cid = $cdom.'_'.$cnum;
                   7629:                     if (!exists($allroles{$cid})) {
                   7630:                         next;
                   7631:                     }    
                   7632:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7633:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7634:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7635:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7636:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7637:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7638:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7639:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7640:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7641:                                         if (grep/^all$/,@sections) {
                   7642:                                             return 'ok';
                   7643:                                         } else {
                   7644:                                             if (grep/^$sec$/,@sections) {
                   7645:                                                 return 'ok';
                   7646:                                             }
                   7647:                                         }
                   7648:                                     }
                   7649:                                 }
                   7650:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7651:                                     if (grep/^none$/,@groups) {
                   7652:                                         return 'ok';
                   7653:                                     }
                   7654:                                 } else {
                   7655:                                     if (grep/^all$/,@groups) {
                   7656:                                         return 'ok';
                   7657:                                     } 
                   7658:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7659:                                         if (grep/^$group$/,@groups) {
                   7660:                                             return 'ok';
                   7661:                                         }
                   7662:                                     }
                   7663:                                 } 
                   7664:                             }
                   7665:                         }
                   7666:                     }
                   7667:                 }
                   7668:             }
                   7669:             if ($guest) {
                   7670:                 return $guest;
                   7671:             }
                   7672:         }
                   7673:     }
                   7674:     return;
                   7675: }
                   7676: 
                   7677: sub course_group_datechecker {
                   7678:     my ($dates,$now,$status) = @_;
                   7679:     my ($start,$end) = split(/\./,$dates);
                   7680:     if (!$start && !$end) {
                   7681:         return 'ok';
                   7682:     }
                   7683:     if (grep/^active$/,@{$status}) {
                   7684:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7685:             return 'ok';
                   7686:         }
                   7687:     }
                   7688:     if (grep/^previous$/,@{$status}) {
                   7689:         if ($end > $now ) {
                   7690:             return 'ok';
                   7691:         }
                   7692:     }
                   7693:     if (grep/^future$/,@{$status}) {
                   7694:         if ($start > $now) {
                   7695:             return 'ok';
                   7696:         }
                   7697:     }
                   7698:     return; 
                   7699: }
                   7700: 
                   7701: sub parse_portfolio_url {
                   7702:     my ($url) = @_;
                   7703: 
                   7704:     my ($type,$udom,$unum,$group,$file_name);
                   7705:     
1.823     albertel 7706:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7707: 	$type = 1;
                   7708:         $udom = $1;
                   7709:         $unum = $2;
                   7710:         $file_name = $3;
1.823     albertel 7711:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7712: 	$type = 2;
                   7713:         $udom = $1;
                   7714:         $unum = $2;
                   7715:         $group = $3;
                   7716:         $file_name = $3.'/'.$4;
                   7717:     }
                   7718:     if (wantarray) {
                   7719: 	return ($type,$udom,$unum,$file_name,$group);
                   7720:     }
                   7721:     return $type;
                   7722: }
                   7723: 
                   7724: sub is_portfolio_url {
                   7725:     my ($url) = @_;
                   7726:     return scalar(&parse_portfolio_url($url));
                   7727: }
                   7728: 
1.798     raeburn  7729: sub is_portfolio_file {
                   7730:     my ($file) = @_;
1.820     raeburn  7731:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7732:         return 1;
                   7733:     }
                   7734:     return;
                   7735: }
                   7736: 
1.976     raeburn  7737: sub usertools_access {
1.1084    raeburn  7738:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7739:     my ($access,%tools);
                   7740:     if ($context eq '') {
                   7741:         $context = 'tools';
                   7742:     }
                   7743:     if ($context eq 'requestcourses') {
                   7744:         %tools = (
                   7745:                       official   => 1,
                   7746:                       unofficial => 1,
1.1006    raeburn  7747:                       community  => 1,
1.1172.2.37  raeburn  7748:                       textbook   => 1,
1.985     raeburn  7749:                  );
1.1172.2.9  raeburn  7750:     } elsif ($context eq 'requestauthor') {
                   7751:         %tools = (
                   7752:                       requestauthor => 1,
                   7753:                  );
1.985     raeburn  7754:     } else {
                   7755:         %tools = (
                   7756:                       aboutme   => 1,
                   7757:                       blog      => 1,
1.1172.2.6  raeburn  7758:                       webdav    => 1,
1.985     raeburn  7759:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7760:22):                       timezone  => 1,
1.985     raeburn  7761:                  );
                   7762:     }
1.976     raeburn  7763:     return if (!defined($tools{$tool}));
                   7764: 
1.1172.2.35  raeburn  7765:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7766:         $udom = $env{'user.domain'};
                   7767:         $uname = $env{'user.name'};
                   7768:     }
                   7769: 
1.978     raeburn  7770:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7771:         if ($action ne 'reload') {
1.985     raeburn  7772:             if ($context eq 'requestcourses') {
                   7773:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7774:             } elsif ($context eq 'requestauthor') {
                   7775:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7776:             } else {
                   7777:                 return $env{'environment.availabletools.'.$tool};
                   7778:             }
                   7779:         }
1.976     raeburn  7780:     }
                   7781: 
1.1172.2.9  raeburn  7782:     my ($toolstatus,$inststatus,$envkey);
                   7783:     if ($context eq 'requestauthor') {
                   7784:         $envkey = $context;
                   7785:     } else {
                   7786:         $envkey = $context.'.'.$tool;
                   7787:     }
1.976     raeburn  7788: 
1.985     raeburn  7789:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7790:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7791:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7792:         $inststatus = $env{'environment.inststatus'};
                   7793:     } else {
1.1084    raeburn  7794:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7795:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7796:             $inststatus = $userenvref->{'inststatus'};
                   7797:         } else {
1.1172.2.9  raeburn  7798:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7799:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7800:             $inststatus = $userenv{'inststatus'};
                   7801:         }
1.976     raeburn  7802:     }
                   7803: 
                   7804:     if ($toolstatus ne '') {
                   7805:         if ($toolstatus) {
                   7806:             $access = 1;
                   7807:         } else {
                   7808:             $access = 0;
                   7809:         }
                   7810:         return $access;
                   7811:     }
                   7812: 
1.1084    raeburn  7813:     my ($is_adv,%domdef);
                   7814:     if (ref($is_advref) eq 'HASH') {
                   7815:         $is_adv = $is_advref->{'is_adv'};
                   7816:     } else {
                   7817:         $is_adv = &is_advanced_user($udom,$uname);
                   7818:     }
                   7819:     if (ref($domdefref) eq 'HASH') {
                   7820:         %domdef = %{$domdefref};
                   7821:     } else {
                   7822:         %domdef = &get_domain_defaults($udom);
                   7823:     }
1.976     raeburn  7824:     if (ref($domdef{$tool}) eq 'HASH') {
                   7825:         if ($is_adv) {
                   7826:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7827:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7828:                     $access = 1;
                   7829:                 } else {
                   7830:                     $access = 0;
                   7831:                 }
                   7832:                 return $access;
                   7833:             }
                   7834:         }
                   7835:         if ($inststatus ne '') {
                   7836:             my ($hasaccess,$hasnoaccess);
                   7837:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7838:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7839:                     if ($domdef{$tool}{$affiliation}) {
                   7840:                         $hasaccess = 1;
                   7841:                     } else {
                   7842:                         $hasnoaccess = 1;
                   7843:                     }
                   7844:                 }
                   7845:             }
                   7846:             if ($hasaccess || $hasnoaccess) {
                   7847:                 if ($hasaccess) {
                   7848:                     $access = 1;
                   7849:                 } elsif ($hasnoaccess) {
                   7850:                     $access = 0; 
                   7851:                 }
                   7852:                 return $access;
                   7853:             }
                   7854:         } else {
                   7855:             if ($domdef{$tool}{'default'} ne '') {
                   7856:                 if ($domdef{$tool}{'default'}) {
                   7857:                     $access = 1;
                   7858:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7859:                     $access = 0;
                   7860:                 }
                   7861:                 return $access;
                   7862:             }
                   7863:         }
                   7864:     } else {
1.1172.2.6  raeburn  7865:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7866:             $access = 1;
                   7867:         } else {
                   7868:             $access = 0;
                   7869:         }
1.976     raeburn  7870:         return $access;
                   7871:     }
                   7872: }
                   7873: 
1.1050    raeburn  7874: sub is_course_owner {
                   7875:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7876:     if (($udom eq '') || ($uname eq '')) {
                   7877:         $udom = $env{'user.domain'};
                   7878:         $uname = $env{'user.name'};
                   7879:     }
                   7880:     unless (($udom eq '') || ($uname eq '')) {
                   7881:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7882:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7883:                 return 1;
                   7884:             } else {
                   7885:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7886:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7887:                     return 1;
                   7888:                 }
                   7889:             }
                   7890:         }
                   7891:     }
                   7892:     return;
                   7893: }
                   7894: 
1.976     raeburn  7895: sub is_advanced_user {
                   7896:     my ($udom,$uname) = @_;
1.1085    raeburn  7897:     if ($udom ne '' && $uname ne '') {
                   7898:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7899:             if (wantarray) {
                   7900:                 return ($env{'user.adv'},$env{'user.author'});
                   7901:             } else {
                   7902:                 return $env{'user.adv'};
                   7903:             }
1.1085    raeburn  7904:         }
                   7905:     }
1.976     raeburn  7906:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7907:     my %allroles;
1.1128    raeburn  7908:     my ($is_adv,$is_author);
1.976     raeburn  7909:     foreach my $role (keys(%roleshash)) {
                   7910:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7911:         my $area = '/'.$tdomain.'/'.$trest;
                   7912:         if ($sec ne '') {
                   7913:             $area .= '/'.$sec;
                   7914:         }
                   7915:         if (($area ne '') && ($trole ne '')) {
                   7916:             my $spec=$trole.'.'.$area;
                   7917:             if ($trole =~ /^cr\//) {
                   7918:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7919:             } elsif ($trole ne 'gr') {
                   7920:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7921:             }
1.1128    raeburn  7922:             if ($trole eq 'au') {
                   7923:                 $is_author = 1;
                   7924:             }
1.976     raeburn  7925:         }
                   7926:     }
                   7927:     foreach my $role (keys(%allroles)) {
                   7928:         last if ($is_adv);
                   7929:         foreach my $item (split(/:/,$allroles{$role})) {
                   7930:             if ($item ne '') {
                   7931:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7932:                 if ($privilege eq 'adv') {
                   7933:                     $is_adv = 1;
                   7934:                     last;
                   7935:                 }
                   7936:             }
                   7937:         }
                   7938:     }
1.1128    raeburn  7939:     if (wantarray) {
                   7940:         return ($is_adv,$is_author);
                   7941:     }
1.976     raeburn  7942:     return $is_adv;
                   7943: }
1.798     raeburn  7944: 
1.1035    raeburn  7945: sub check_can_request {
1.1036    raeburn  7946:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7947:     my $canreq = 0;
                   7948:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7949:     my @options = ('approval','validate','autolimit');
                   7950:     my $optregex = join('|',@options);
                   7951:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7952:         foreach my $type (@{$types}) {
                   7953:             if (&usertools_access($env{'user.name'},
                   7954:                                   $env{'user.domain'},
                   7955:                                   $type,undef,'requestcourses')) {
                   7956:                 $canreq ++;
1.1036    raeburn  7957:                 if (ref($request_domains) eq 'HASH') {
                   7958:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7959:                 }
1.1035    raeburn  7960:                 if ($dom eq $env{'user.domain'}) {
                   7961:                     $can_request->{$type} = 1;
                   7962:                 }
                   7963:             }
                   7964:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7965:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7966:                 if (@curr > 0) {
1.1036    raeburn  7967:                     foreach my $item (@curr) {
                   7968:                         if (ref($request_domains) eq 'HASH') {
                   7969:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7970:                             if ($otherdom ne '') {
                   7971:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7972:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7973:                                         push(@{$request_domains->{$type}},$otherdom);
                   7974:                                     }
                   7975:                                 } else {
                   7976:                                     push(@{$request_domains->{$type}},$otherdom);
                   7977:                                 }
                   7978:                             }
                   7979:                         }
                   7980:                     }
                   7981:                     unless($dom eq $env{'user.domain'}) {
                   7982:                         $canreq ++;
1.1035    raeburn  7983:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7984:                             $can_request->{$type} = 1;
                   7985:                         }
                   7986:                     }
                   7987:                 }
                   7988:             }
                   7989:         }
                   7990:     }
                   7991:     return $canreq;
                   7992: }
                   7993: 
1.341     www      7994: # ---------------------------------------------- Custom access rule evaluation
                   7995: 
                   7996: sub customaccess {
                   7997:     my ($priv,$uri)=@_;
1.807     albertel 7998:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7999:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8000:     $udom = &LONCAPA::clean_domain($udom);
                   8001:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8002:     my $access=0;
1.800     albertel 8003:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8004: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8005: 	if ($type eq 'user') {
                   8006: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8007: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8008: 		if ($tdom) {
                   8009: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8010: 		}
1.896     albertel 8011: 		if ($tuname) {
                   8012: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8013: 		}
                   8014: 		$access=($effect eq 'allow');
                   8015: 		last;
                   8016: 	    }
                   8017: 	} else {
                   8018: 	    if ($role) {
                   8019: 		if ($role ne $urole) { next; }
                   8020: 	    }
                   8021: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8022: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8023: 		if ($tdom) {
                   8024: 		    if ($tdom ne $udom) { next; }
                   8025: 		}
                   8026: 		if ($tcrs) {
                   8027: 		    if ($tcrs ne $ucrs) { next; }
                   8028: 		}
                   8029: 		if ($tsec) {
                   8030: 		    if ($tsec ne $usec) { next; }
                   8031: 		}
                   8032: 		$access=($effect eq 'allow');
                   8033: 		last;
                   8034: 	    }
                   8035: 	    if ($realm eq '' && $role eq '') {
                   8036: 		$access=($effect eq 'allow');
                   8037: 	    }
1.402     bowersj2 8038: 	}
1.341     www      8039:     }
                   8040:     return $access;
                   8041: }
                   8042: 
1.103     harris41 8043: # ------------------------------------------------- Check for a user privilege
1.12      www      8044: 
                   8045: sub allowed {
1.1172.2.146.  .1(raebu 8046:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8047:     my $ver_orguri=$uri;
1.439     www      8048:     $uri=&deversion($uri);
1.152     www      8049:     my $orguri=$uri;
1.52      www      8050:     $uri=&declutter($uri);
1.809     raeburn  8051: 
1.810     raeburn  8052:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8053:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8054:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8055:             return $1;
                   8056:         } else {
                   8057:             return;
                   8058:         }
                   8059:     }
                   8060: 
1.620     albertel 8061:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8062: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8063:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8064: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8065: 	&& ($priv eq 'bre')) {
1.14      www      8066: 	return 'F';
1.159     www      8067:     }
                   8068: 
1.545     banghart 8069: # Free bre access to user's own portfolio contents
1.714     raeburn  8070:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8071:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8072: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8073:         my %setters;
1.1172.2.142  raeburn  8074:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8075:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8076:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8077:             return 'B';
                   8078:         } else {
                   8079:             return 'F';
                   8080:         }
1.545     banghart 8081:     }
                   8082: 
1.762     raeburn  8083: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8084:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8085:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8086:         if (exists($env{'request.course.id'})) {
                   8087:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8088:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8089:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8090:                 my $courseprivid=$env{'request.course.id'};
                   8091:                 $courseprivid=~s/\_/\//;
                   8092:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8093:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8094:                     return $1; 
1.762     raeburn  8095:                 } else {
                   8096:                     if ($env{'request.course.sec'}) {
                   8097:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8098:                     }
                   8099:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8100:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8101:                         return $2;
                   8102:                     }
1.714     raeburn  8103:                 }
                   8104:             }
                   8105:         }
                   8106:     }
                   8107: 
1.159     www      8108: # Free bre to public access
                   8109: 
                   8110:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8111:22):         my $copyright;
                   8112:22):         unless ($uri =~ /ext\.tool/) {
                   8113:22):             $copyright=&metadata($uri,'copyright');
                   8114:22):         }
1.620     albertel 8115: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8116:            return 'F'; 
                   8117:         }
1.238     www      8118:         if ($copyright eq 'priv') {
                   8119:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8120: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8121: 		return '';
                   8122:             }
                   8123:         }
                   8124:         if ($copyright eq 'domain') {
                   8125:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8126: 	    unless (($env{'user.domain'} eq $1) ||
                   8127:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8128: 		return '';
                   8129:             }
1.262     matthew  8130:         }
1.620     albertel 8131:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8132:             # Library role, so allow browsing of resources in this domain.
                   8133:             return 'F';
1.238     www      8134:         }
1.341     www      8135:         if ($copyright eq 'custom') {
                   8136: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8137:         }
1.14      www      8138:     }
1.264     matthew  8139:     # Domain coordinator is trying to create a course
1.620     albertel 8140:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8141:         # uri is the requested domain in this case.
                   8142:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8143:         # a role of dc for the domain in question.
1.620     albertel 8144:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8145:     }
1.29      www      8146: 
1.52      www      8147:     my $thisallowed='';
                   8148:     my $statecond=0;
                   8149:     my $courseprivid='';
                   8150: 
1.1039    raeburn  8151:     my $ownaccess;
1.1043    raeburn  8152:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8153:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8154:         if ($uri eq '') {
                   8155:             $ownaccess = 1;
                   8156:         } else {
                   8157:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8158:                 my $udom = $env{'user.domain'};
                   8159:                 my $uname = $env{'user.name'};
                   8160:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8161:                     $ownaccess = 1;
1.1040    raeburn  8162:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8163:                     unless ($uri =~ m{\.\./}) {
                   8164:                         $ownaccess = 1;
                   8165:                     }
                   8166:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8167:                     my $now = time;
                   8168:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8169:                         my $adom = $1;
                   8170:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8171:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8172:                                 my ($start,$end) = split(/\./,$env{$key});
                   8173:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8174:                                     $ownaccess = 1;
                   8175:                                     last;
                   8176:                                 }
                   8177:                             }
                   8178:                         }
                   8179:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8180:                         my $adom = $1;
                   8181:                         my $aname = $2;
1.1042    raeburn  8182:                         foreach my $role ('ca','aa') { 
                   8183:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8184:                                 my ($start,$end) =
1.1172.2.142  raeburn  8185:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8186:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8187:                                     $ownaccess = 1;
                   8188:                                     last;
                   8189:                                 }
1.1039    raeburn  8190:                             }
                   8191:                         }
                   8192:                     }
                   8193:                 }
                   8194:             }
                   8195:         }
                   8196:     }
                   8197: 
1.52      www      8198: # Course
                   8199: 
1.620     albertel 8200:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8201:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8202:             $thisallowed.=$1;
                   8203:         }
1.52      www      8204:     }
1.29      www      8205: 
1.52      www      8206: # Domain
                   8207: 
1.620     albertel 8208:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8209:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8210:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8211:             $thisallowed.=$1;
                   8212:         }
1.12      www      8213:     }
1.52      www      8214: 
1.1141    raeburn  8215: # User who is not author or co-author might still be able to edit
                   8216: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8217:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8218:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8219:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8220:             $thisallowed.=$1;
                   8221:         }
                   8222:     }
                   8223: 
1.52      www      8224: # Course: uri itself is a course
1.66      www      8225:     my $courseuri=$uri;
                   8226:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8227:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8228: 
1.620     albertel 8229:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8230:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8231:         if ($priv eq 'mip') {
                   8232:             my $rem = $1;
                   8233:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8234:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8235:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8236:                 if ($cdom ne '') {
                   8237:                     my %passwdconf = &get_passwdconf($cdom);
                   8238:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8239:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8240:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8241:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8242:                                 unless (@inststatuses) {
                   8243:                                     @inststatuses = ('default');
                   8244:                                 }
                   8245:                                 foreach my $status (@inststatuses) {
                   8246:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8247:                                         $thisallowed.=$rem;
                   8248:                                     }
                   8249:                                 }
                   8250:                             }
                   8251:                         }
                   8252:                     }
                   8253:                 }
                   8254:             }
                   8255:         } else {
                   8256:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8257:                 $thisallowed.=$1;
                   8258:             }
1.1039    raeburn  8259:         }
1.12      www      8260:     }
1.29      www      8261: 
1.665     albertel 8262: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8263: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8264:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8265: 	$thisallowed='';
1.671     raeburn  8266:         my ($match)=&is_on_map($uri);
                   8267:         if ($match) {
                   8268:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8269:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8270:                 my $value = $1;
1.1172.2.146.  .1(raebu 8271:22):                 my $deeplinkblock;
                   8272:22):                 unless ($nodeeplinkcheck) {
                   8273:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8274:22):                 }
                   8275:22):                 if ($deeplinkblock) {
                   8276:22):                     $thisallowed='D';
                   8277:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8278:                     $thisallowed.=$value;
1.1162    raeburn  8279:                 } else {
1.1172.2.126  raeburn  8280:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8281:                     if (@blockers > 0) {
                   8282:                         $thisallowed = 'B';
                   8283:                     } else {
                   8284:                         $thisallowed.=$value;
                   8285:                     }
1.1162    raeburn  8286:                 }
1.671     raeburn  8287:             }
                   8288:         } else {
1.705     albertel 8289:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8290:             if ($refuri) {
                   8291:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8292:                     $thisallowed='F';
1.671     raeburn  8293:                 } else {
                   8294:                     $refuri=&declutter($refuri);
                   8295:                     my ($match) = &is_on_map($refuri);
                   8296:                     if ($match) {
1.1172.2.146.  .1(raebu 8297:22):                         my $deeplinkblock;
                   8298:22):                         unless ($nodeeplinkcheck) {
                   8299:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8300:22):                         }
                   8301:22):                         if ($deeplinkblock) {
                   8302:22):                             $thisallowed='D';
                   8303:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8304:                             $thisallowed='F';
1.1172.2.65  raeburn  8305:                         } else {
1.1172.2.127  raeburn  8306:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8307:                             if (@blockers > 0) {
                   8308:                                 $thisallowed = 'B';
                   8309:                             } else {
                   8310:                                 $thisallowed='F';
                   8311:                             }
1.1162    raeburn  8312:                         }
1.671     raeburn  8313:                     }
1.669     raeburn  8314:                 }
1.671     raeburn  8315:             }
                   8316:         }
1.314     www      8317:     }
1.492     albertel 8318: 
1.766     albertel 8319:     if ($priv eq 'bre'
                   8320: 	&& $thisallowed ne 'F' 
                   8321: 	&& $thisallowed ne '2'
                   8322: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8323: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8324:     }
                   8325:     
1.52      www      8326: # Full access at system, domain or course-wide level? Exit.
1.29      www      8327:     if ($thisallowed=~/F/) {
                   8328: 	return 'F';
                   8329:     }
                   8330: 
1.52      www      8331: # If this is generating or modifying users, exit with special codes
1.29      www      8332: 
1.643     www      8333:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8334: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8335: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8336: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8337: 	    unless ($auname) { return $thisallowed; }
                   8338: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8339: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8340: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8341: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8342: 	}
1.52      www      8343: 	return $thisallowed;
                   8344:     }
                   8345: #
1.103     harris41 8346: # Gathered so far: system, domain and course wide privileges
1.52      www      8347: #
                   8348: # Course: See if uri or referer is an individual resource that is part of 
                   8349: # the course
                   8350: 
1.620     albertel 8351:     if ($env{'request.course.id'}) {
1.232     www      8352: 
1.1172.2.115  raeburn  8353: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8354: 
                   8355:         if ($priv eq 'mip') {
                   8356:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8357:                 return $thisallowed;
                   8358:             } else {
                   8359:                 return '';
                   8360:             }
                   8361:         }
                   8362: 
1.620     albertel 8363:        $courseprivid=$env{'request.course.id'};
                   8364:        if ($env{'request.course.sec'}) {
                   8365:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8366:        }
                   8367:        $courseprivid=~s/\_/\//;
                   8368:        my $checkreferer=1;
1.232     www      8369:        my ($match,$cond)=&is_on_map($uri);
                   8370:        if ($match) {
                   8371:            $statecond=$cond;
1.620     albertel 8372:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8373:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8374:                my $value = $1;
                   8375:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8376:22):                    my $deeplinkblock;
                   8377:22):                    unless ($nodeeplinkcheck) {
                   8378:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8379:22):                    }
                   8380:22):                    if ($deeplinkblock) {
                   8381:22):                        $thisallowed = 'D';
                   8382:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8383:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8384:                    } else {
1.1172.2.126  raeburn  8385:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8386:                        if (@blockers > 0) {
                   8387:                            $thisallowed = 'B';
                   8388:                        } else {
                   8389:                            $thisallowed.=$value;
                   8390:                        }
1.1162    raeburn  8391:                    }
                   8392:                } else {
                   8393:                    $thisallowed.=$value;
                   8394:                }
1.52      www      8395:                $checkreferer=0;
                   8396:            }
1.29      www      8397:        }
1.1172.2.126  raeburn  8398: 
1.148     www      8399:        if ($checkreferer) {
1.620     albertel 8400: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8401:             unless ($refuri) {
1.800     albertel 8402:                 foreach my $key (keys(%env)) {
                   8403: 		    if ($key=~/^httpref\..*\*/) {
                   8404: 			my $pattern=$key;
1.156     www      8405:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8406:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8407:                         $pattern=~s/\//\\\//g;
1.152     www      8408:                         if ($orguri=~/$pattern/) {
1.800     albertel 8409: 			    $refuri=$env{$key};
1.148     www      8410:                         }
                   8411:                     }
1.191     harris41 8412:                 }
1.148     www      8413:             }
1.232     www      8414: 
1.148     www      8415:          if ($refuri) { 
1.152     www      8416: 	  $refuri=&declutter($refuri);
1.232     www      8417:           my ($match,$cond)=&is_on_map($refuri);
                   8418:             if ($match) {
                   8419:               my $refstatecond=$cond;
1.620     albertel 8420:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8421:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8422:                   my $value = $1;
                   8423:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8424:22):                       my $deeplinkblock;
                   8425:22):                       unless ($nodeeplinkcheck) {
                   8426:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8427:22):                       }
                   8428:22):                       if ($deeplinkblock) {
                   8429:22):                           $thisallowed = 'D';
                   8430:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8431:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8432:                       } else {
1.1172.2.127  raeburn  8433:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8434:                           if (@blockers > 0) {
                   8435:                               $thisallowed = 'B';
                   8436:                           } else {
                   8437:                               $thisallowed.=$value;
                   8438:                           }
1.1162    raeburn  8439:                       }
                   8440:                   } else {
                   8441:                       $thisallowed.=$value;
                   8442:                   }
1.53      www      8443:                   $uri=$refuri;
                   8444:                   $statecond=$refstatecond;
1.52      www      8445:               }
                   8446:           }
1.148     www      8447:         }
1.29      www      8448:        }
1.52      www      8449:    }
1.29      www      8450: 
1.52      www      8451: #
1.103     harris41 8452: # Gathered now: all privileges that could apply, and condition number
1.52      www      8453: # 
                   8454: #
                   8455: # Full or no access?
                   8456: #
1.29      www      8457: 
1.52      www      8458:     if ($thisallowed=~/F/) {
                   8459: 	return 'F';
                   8460:     }
1.29      www      8461: 
1.52      www      8462:     unless ($thisallowed) {
                   8463:         return '';
                   8464:     }
1.29      www      8465: 
1.52      www      8466: # Restrictions exist, deal with them
                   8467: #
                   8468: #   C:according to course preferences
                   8469: #   R:according to resource settings
                   8470: #   L:unless locked
                   8471: #   X:according to user session state
                   8472: #
                   8473: 
                   8474: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8475: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8476: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8477: # courses, and 2 minutes for current course, in which user has st or ta role
                   8478: # which is neither expired nor a future role (unless current course).
1.52      www      8479: 
1.1172.2.142  raeburn  8480:     my ($needlockcheck,$now,$crsonly);
1.52      www      8481:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8482:         $now = time;
                   8483:         if ($priv eq 'bre') {
                   8484:             if ($uri ne '') {
                   8485:                 if ($orguri =~ m{^/+res/}) {
                   8486:                     if ($uri =~ m{^lib/templates/}) {
                   8487:                         if ($env{'request.course.id'}) {
                   8488:                             $crsonly = 1;
                   8489:                             $needlockcheck = 1;
                   8490:                         }
                   8491:                     } else {
                   8492:                         $needlockcheck = 1;
                   8493:                     }
                   8494:                 } elsif ($env{'request.course.id'}) {
                   8495:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8496:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8497:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8498:                         $crsonly = 1;
                   8499:                     }
                   8500:                     $needlockcheck = 1;
                   8501:                 }
                   8502:             }
                   8503:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8504:             $needlockcheck = 1;
                   8505:         }
                   8506:     }
                   8507:     if ($needlockcheck) {
                   8508:         foreach my $envkey (keys(%env)) {
1.54      www      8509:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8510:                my $courseid=$2;
                   8511:                my $roleid=$1.'.'.$2;
1.92      www      8512:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8513:                unless ($env{'request.role'} eq $roleid) {
                   8514:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8515:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8516:                }
1.54      www      8517:                my $expiretime=600;
1.620     albertel 8518:                if ($env{'request.role'} eq $roleid) {
1.54      www      8519: 		  $expiretime=120;
                   8520:                }
                   8521: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8522:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8523:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8524: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8525:                }
1.620     albertel 8526:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8527:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8528: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8529:                        &log($env{'user.domain'},$env{'user.name'},
                   8530:                             $env{'user.home'},
1.57      www      8531:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8532:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8533:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8534: 		       return '';
                   8535:                    }
                   8536:                }
1.620     albertel 8537:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8538:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8539: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8540:                        &log($env{'user.domain'},$env{'user.name'},
                   8541:                             $env{'user.home'},
1.57      www      8542:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8543:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8544:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8545: 		       return '';
                   8546:                    }
                   8547:                }
                   8548: 	   }
1.29      www      8549:        }
1.52      www      8550:     }
1.1172.2.126  raeburn  8551: 
1.52      www      8552: #
                   8553: # Rest of the restrictions depend on selected course
                   8554: #
                   8555: 
1.620     albertel 8556:     unless ($env{'request.course.id'}) {
1.766     albertel 8557: 	if ($thisallowed eq 'A') {
                   8558: 	    return 'A';
1.814     raeburn  8559:         } elsif ($thisallowed eq 'B') {
                   8560:             return 'B';
1.766     albertel 8561: 	} else {
                   8562: 	    return '1';
                   8563: 	}
1.52      www      8564:     }
1.29      www      8565: 
1.52      www      8566: #
                   8567: # Now user is definitely in a course
                   8568: #
1.53      www      8569: 
                   8570: 
                   8571: # Course preferences
                   8572: 
                   8573:    if ($thisallowed=~/C/) {
1.620     albertel 8574:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8575:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8576:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8577: 	   =~/\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.' in '.
                   8581: 			$env{'request.course.id'});
                   8582: 	   }
1.237     www      8583:            return '';
                   8584:        }
                   8585: 
1.620     albertel 8586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8587: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8588: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8590: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8591: 			$env{'request.course.id'});
                   8592: 	   }
1.54      www      8593:            return '';
                   8594:        }
1.53      www      8595:    }
                   8596: 
                   8597: # Resource preferences
                   8598: 
                   8599:    if ($thisallowed=~/R/) {
1.620     albertel 8600:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8601:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8602: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8605: 	   }
                   8606: 	   return '';
1.54      www      8607:        }
1.53      www      8608:    }
1.30      www      8609: 
1.1172.2.146.  .1(raebu 8610:22): # Restricted for deeplinked session?
                   8611:22): 
                   8612:22):     if ($env{'request.deeplink.login'}) {
                   8613:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8614:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8615:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8616:22):                 return '';
                   8617:22):             }
                   8618:22):         }
                   8619:22):     }
                   8620:22): 
1.246     www      8621: # Restricted by state or randomout?
1.30      www      8622: 
1.52      www      8623:    if ($thisallowed=~/X/) {
1.620     albertel 8624:       if ($env{'acc.randomout'}) {
1.579     albertel 8625: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8626:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8627:             return ''; 
                   8628:          }
1.247     www      8629:       }
                   8630:       if (&condval($statecond)) {
1.52      www      8631: 	 return '2';
                   8632:       } else {
                   8633:          return '';
                   8634:       }
                   8635:    }
1.30      www      8636: 
1.766     albertel 8637:     if ($thisallowed eq 'A') {
                   8638: 	return 'A';
1.814     raeburn  8639:     } elsif ($thisallowed eq 'B') {
                   8640:         return 'B';
1.1172.2.146.  .1(raebu 8641:22):     } elsif ($thisallowed eq 'D') {
                   8642:22):         return 'D';
1.766     albertel 8643:     }
1.52      www      8644:    return 'F';
1.232     www      8645: }
1.1162    raeburn  8646: 
1.1172.2.13  raeburn  8647: # ------------------------------------------- Check construction space access
                   8648: 
                   8649: sub constructaccess {
                   8650:     my ($url,$setpriv)=@_;
                   8651: 
                   8652: # We do not allow editing of previous versions of files
                   8653:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8654: 
                   8655: # Get username and domain from URL
                   8656:     my ($ownername,$ownerdomain,$ownerhome);
                   8657: 
                   8658:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8659:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8660: 
                   8661: # The URL does not really point to any authorspace, forget it
                   8662:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8663: 
                   8664: # Now we need to see if the user has access to the authorspace of
                   8665: # $ownername at $ownerdomain
                   8666: 
                   8667:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8668: # Real author for this?
                   8669:        $ownerhome = $env{'user.home'};
                   8670:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8671:           return ($ownername,$ownerdomain,$ownerhome);
                   8672:        }
                   8673:     } else {
                   8674: # Co-author for this?
                   8675:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8676:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8677:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8678:             return ($ownername,$ownerdomain,$ownerhome);
                   8679:         }
                   8680:     }
                   8681: 
                   8682: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8683: # we might as well leave
                   8684:    unless ($setpriv) { return ''; }
                   8685: 
                   8686: # Backdoor access?
                   8687:     my $allowed=&allowed('eco',$ownerdomain);
                   8688: # Nope
                   8689:     unless ($allowed) { return ''; }
                   8690: # Looks like we may have access, but could be locked by the owner of the construction space
                   8691:     if ($allowed eq 'U') {
                   8692:         my %blocked=&get('environment',['domcoord.author'],
                   8693:                          $ownerdomain,$ownername);
                   8694: # Is blocked by owner
                   8695:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8696:     }
                   8697:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8698: # Grant temporary access
                   8699:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8700:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8701:         if (!$update) { $update = $then; }
                   8702:         my $refresh=$env{'user.refresh.time'};
                   8703:         if (!$refresh) { $refresh = $update; }
                   8704:         my $now = time;
                   8705:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8706:                            $now,'ca','constructaccess');
                   8707:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8708:         return($ownername,$ownerdomain,$ownerhome);
                   8709:     }
                   8710: # No business here
                   8711:     return '';
                   8712: }
                   8713: 
1.1172.2.66  raeburn  8714: # ----------------------------------------------------------- Content Blocking
                   8715: 
                   8716: {
                   8717: # Caches for faster Course Contents display where content blocking
                   8718: # is in operation (i.e., interval param set) for timed quiz.
                   8719: #
                   8720: # User for whom data are being temporarily cached.
                   8721: my $cacheduser='';
1.1172.2.126  raeburn  8722: # Course for which data are being temporarily cached.
                   8723: my $cachedcid='';
1.1172.2.66  raeburn  8724: # Cached blockers for this user (a hash of blocking items).
                   8725: my %cachedblockers=();
                   8726: # When the data were last cached.
                   8727: my $cachedlast='';
                   8728: 
                   8729: sub load_all_blockers {
1.1172.2.128  raeburn  8730:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8731:     if (($uname ne '') && ($udom ne '')) {
                   8732:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8733:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8734:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8735:             return;
                   8736:         }
                   8737:     }
                   8738:     $cachedlast=time;
                   8739:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8740:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8741:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8742:     return;
1.1172.2.66  raeburn  8743: }
                   8744: 
1.1162    raeburn  8745: sub get_comm_blocks {
                   8746:     my ($cdom,$cnum) = @_;
                   8747:     if ($cdom eq '' || $cnum eq '') {
                   8748:         return unless ($env{'request.course.id'});
                   8749:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8750:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8751:     }
                   8752:     my %commblocks;
                   8753:     my $hashid=$cdom.'_'.$cnum;
                   8754:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8755:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8756:         %commblocks = %{$blocksref};
                   8757:     } else {
                   8758:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8759:         my $cachetime = 600;
                   8760:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8761:     }
                   8762:     return %commblocks;
                   8763: }
                   8764: 
1.1172.2.66  raeburn  8765: sub get_commblock_resources {
                   8766:     my ($blocks) = @_;
                   8767:     my %blockers = ();
                   8768:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8769:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8770:     if ($env{'request.course.sec'}) {
                   8771:         $courseurl .= '/'.$env{'request.course.sec'};
                   8772:     }
                   8773:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8774:     my %commblocks;
                   8775:     if (ref($blocks) eq 'HASH') {
                   8776:         %commblocks = %{$blocks};
                   8777:     } else {
                   8778:         %commblocks = &get_comm_blocks();
                   8779:     }
1.1172.2.66  raeburn  8780:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8781:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8782:     return %blockers unless (ref($navmap));
                   8783:     my $now = time;
1.1162    raeburn  8784:     foreach my $block (keys(%commblocks)) {
                   8785:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8786:             my ($start,$end) = ($1,$2);
                   8787:             if ($start <= $now && $end >= $now) {
                   8788:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8789:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8790:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8791:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8792:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8793:                             }
                   8794:                         }
                   8795:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8796:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8797:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8798:                             }
                   8799:                         }
                   8800:                     }
                   8801:                 }
                   8802:             }
                   8803:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8804:             my $item = $1;
                   8805:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8806:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8807:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8808:                     my $type = 'map';
                   8809:                     if ($item eq 'course') {
                   8810:                         $type = 'course';
                   8811:                         @interval=&EXT("resource.0.interval");
                   8812:                     } else {
                   8813:                         if ($item =~ /___\d+___/) {
                   8814:                             $type = 'resource';
                   8815:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8816:                         } else {
1.1172.2.142  raeburn  8817:                             $mapname = &deversion($item);
                   8818:                             if (ref($navmap)) {
                   8819:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8820:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8821:                             }
                   8822:                         }
1.1172.2.66  raeburn  8823:                     }
1.1172.2.146.  .1(raebu 8824:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8825:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8826:                         my $first_access;
                   8827:                         if ($type eq 'resource') {
                   8828:                             $first_access=&get_first_access($interval[1],$item);
                   8829:                         } elsif ($type eq 'map') {
                   8830:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8831:                         } else {
                   8832:                             $first_access=&get_first_access($interval[1]);
                   8833:                         }
                   8834:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8835:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8836:                             if ($timesup > $now) {
                   8837:                                 my $activeblock;
1.1172.2.142  raeburn  8838:                                 if ($type eq 'resource') {
                   8839:                                     if (ref($navmap)) {
                   8840:                                         my $res = $navmap->getBySymb($item);
                   8841:                                         if ($res->answerable()) {
                   8842:                                             $activeblock = 1;
                   8843:                                         }
                   8844:                                     }
                   8845:                                 } elsif ($type eq 'map') {
                   8846:                                     my $mapsymb = &symbread($mapname,1);
                   8847:                                     if (($mapsymb) && (ref($navmap))) {
                   8848:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8849:                                         if (ref($mapres)) {
                   8850:                                             my $first = $mapres->map_start();
                   8851:                                             my $finish = $mapres->map_finish();
                   8852:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8853:                                             if (ref($it)) {
                   8854:                                                 my $res;
                   8855:                                                 while ($res = $it->next(undef,1)) {
                   8856:                                                     next unless (ref($res));
                   8857:                                                     my $symb = $res->symb();
                   8858:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8859:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8860:                                                     if ($interval[1] eq 'map') {
                   8861:                                                         if ($res->answerable()) {
                   8862:                                                             $activeblock = 1;
                   8863:                                                             last;
                   8864:                                                         }
                   8865:                                                     }
                   8866:                                                 }
                   8867:                                             }
                   8868:                                         }
1.1172.2.66  raeburn  8869:                                     }
                   8870:                                 }
                   8871:                                 if ($activeblock) {
                   8872:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8873:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8874:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8875:                                          }
                   8876:                                     }
                   8877:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8878:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8879:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8880:                                         }
1.1162    raeburn  8881:                                     }
                   8882:                                 }
                   8883:                             }
                   8884:                         }
                   8885:                     }
                   8886:                 }
                   8887:             }
                   8888:         }
                   8889:     }
1.1172.2.66  raeburn  8890:     return %blockers;
1.1162    raeburn  8891: }
                   8892: 
1.1172.2.66  raeburn  8893: sub has_comm_blocking {
1.1172.2.128  raeburn  8894:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8895:     my @blockers;
                   8896:     return unless ($env{'request.course.id'});
                   8897:     return unless ($priv eq 'bre');
                   8898:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8899:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8900:     if ($env{'request.course.sec'}) {
                   8901:         $courseurl .= '/'.$env{'request.course.sec'};
                   8902:     }
                   8903:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8904:     my %blockinfo;
                   8905:     if (ref($blocks) eq 'HASH') {
                   8906:         %blockinfo = &get_commblock_resources($blocks);
                   8907:     } else {
                   8908:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8909:         %blockinfo = %cachedblockers;
                   8910:     }
                   8911:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8912:     my (%possibles,@symbs);
                   8913:     if (!$symb) {
1.1172.2.128  raeburn  8914:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8915:     }
1.1172.2.66  raeburn  8916:     if ($symb) {
                   8917:         @symbs = ($symb);
                   8918:     } elsif (keys(%possibles)) {
                   8919:         @symbs = keys(%possibles);
                   8920:     }
                   8921:     my $noblock;
                   8922:     foreach my $symb (@symbs) {
                   8923:         last if ($noblock);
                   8924:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8925:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8926:             if ($block =~ /^firstaccess____(.+)$/) {
                   8927:                 my $item = $1;
1.1172.2.126  raeburn  8928:                 unless ($blocked) {
                   8929:                     if (($item eq $map) || ($item eq $symb)) {
                   8930:                         $noblock = 1;
                   8931:                         last;
                   8932:                     }
1.1172.2.66  raeburn  8933:                 }
1.1162    raeburn  8934:             }
1.1172.2.128  raeburn  8935:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8936:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8937:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8938:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8939:                             push(@blockers,$block);
                   8940:                         }
                   8941:                     }
                   8942:                 }
1.1172.2.128  raeburn  8943:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8944:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8945:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8946:                             push(@blockers,$block);
                   8947:                         }
1.1172.2.66  raeburn  8948:                     }
                   8949:                 }
1.1162    raeburn  8950:             }
                   8951:         }
                   8952:     }
1.1172.2.126  raeburn  8953:     unless ($noblock) {
                   8954:         return @blockers;
                   8955:     }
                   8956:     return;
1.1172.2.66  raeburn  8957: }
1.1162    raeburn  8958: }
                   8959: 
1.1172.2.146.  .1(raebu 8960:22): sub deeplink_check {
                   8961:22):     my ($priv,$symb,$uri) = @_;
                   8962:22):     return unless ($env{'request.course.id'});
                   8963:22):     return unless ($priv eq 'bre');
                   8964:22):     return if ($env{'request.state'} eq 'construct');
                   8965:22):     return if ($env{'request.role.adv'});
                   8966:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8967:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8968:22):     my (%possibles,@symbs);
                   8969:22):     if (!$symb) {
                   8970:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8971:22):     }
                   8972:22):     if ($symb) {
                   8973:22):         @symbs = ($symb);
                   8974:22):     } elsif (keys(%possibles)) {
                   8975:22):         @symbs = keys(%possibles);
                   8976:22):     }
                   8977:22): 
                   8978:22):     my ($deeplink_symb,$allow);
                   8979:22):     if ($env{'request.deeplink.login'}) {
                   8980:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8981:22):     }
                   8982:22):     foreach my $symb (@symbs) {
                   8983:22):         last if ($allow);
                   8984:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8985:22):         if ($deeplink eq '') {
                   8986:22):             $allow = 1;
                   8987:22):         } else {
                   8988:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8989:22):             if ($state ne 'only') {
                   8990:22):                 $allow = 1;
                   8991:22):             } else {
                   8992:22):                 my $check_deeplink_entry;
                   8993:22):                 if ($protect ne 'none') {
                   8994:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8995:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8996:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8997:22):                             $check_deeplink_entry = 1
                   8998:22):                         }
                   8999:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9000:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9001:22):                             $check_deeplink_entry = 1;
                   9002:22):                         }
                   9003:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9004:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9005:22):                             $check_deeplink_entry = 1;
                   9006:22):                         }
                   9007:22):                     }
                   9008:22):                 }
                   9009:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9010:22):                     if ($scope eq 'res') {
                   9011:22):                         if ($symb eq $deeplink_symb) {
                   9012:22):                             $allow = 1;
                   9013:22):                         }
                   9014:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9015:22):                         my ($map_from_symb,$map_from_login);
                   9016:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9017:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9018:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9019:22):                         } else {
                   9020:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9021:22):                         }
                   9022:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9023:22):                             if ($map_from_symb eq $map_from_login) {
                   9024:22):                                 $allow = 1;
                   9025:22):                             } elsif ($scope eq 'rec') {
                   9026:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9027:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9028:22):                                     $allow = 1;
                   9029:22):                                 }
                   9030:22):                             }
                   9031:22):                         }
                   9032:22):                     }
                   9033:22):                 }
                   9034:22):             }
                   9035:22):         }
                   9036:22):     }
                   9037:22):     return if ($allow);
                   9038:22):     return 1;
                   9039:22): }
                   9040:22): 
1.1172.2.66  raeburn  9041: # -------------------------------- Deversion and split uri into path an filename
                   9042: 
1.1133    foxr     9043: #
1.1172.2.66  raeburn  9044: #   Removes the version from a URI and
1.1133    foxr     9045: #   splits it in to its filename and path to the filename.
                   9046: #   Seems like File::Basename could have done this more clearly.
                   9047: #   Parameters:
                   9048: #      $uri   - input URI
                   9049: #   Returns:
                   9050: #     Two element list consisting of 
                   9051: #     $pathname  - the URI up to and excluding the trailing /
                   9052: #     $filename  - The part of the URI following the last /
                   9053: #  NOTE:
                   9054: #    Another realization of this is simply:
                   9055: #    use File::Basename;
                   9056: #    ...
                   9057: #    $uri = shift;
                   9058: #    $filename = basename($uri);
                   9059: #    $path     = dirname($uri);
                   9060: #    return ($filename, $path);
                   9061: #
                   9062: #     The implementation below is probably faster however.
                   9063: #
1.710     albertel 9064: sub split_uri_for_cond {
                   9065:     my $uri=&deversion(&declutter(shift));
                   9066:     my @uriparts=split(/\//,$uri);
                   9067:     my $filename=pop(@uriparts);
                   9068:     my $pathname=join('/',@uriparts);
                   9069:     return ($pathname,$filename);
                   9070: }
1.232     www      9071: # --------------------------------------------------- Is a resource on the map?
                   9072: 
                   9073: sub is_on_map {
1.710     albertel 9074:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9075:     #Trying to find the conditional for the file
1.620     albertel 9076:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9077: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9078:     if ($match) {
1.289     bowersj2 9079: 	return (1,$1);
                   9080:     } else {
1.434     www      9081: 	return (0,0);
1.289     bowersj2 9082:     }
1.12      www      9083: }
                   9084: 
1.427     www      9085: # --------------------------------------------------------- Get symb from alias
                   9086: 
                   9087: sub get_symb_from_alias {
                   9088:     my $symb=shift;
                   9089:     my ($map,$resid,$url)=&decode_symb($symb);
                   9090: # Already is a symb
                   9091:     if ($url) { return $symb; }
                   9092: # Must be an alias
                   9093:     my $aliassymb='';
                   9094:     my %bighash;
1.620     albertel 9095:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9096:                             &GDBM_READER(),0640)) {
                   9097:         my $rid=$bighash{'mapalias_'.$symb};
                   9098: 	if ($rid) {
                   9099: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9100: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9101: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9102: 	}
                   9103:         untie %bighash;
                   9104:     }
                   9105:     return $aliassymb;
                   9106: }
                   9107: 
1.12      www      9108: # ----------------------------------------------------------------- Define Role
                   9109: 
                   9110: sub definerole {
                   9111:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9112:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9113:     foreach my $role (split(':',$sysrole)) {
                   9114: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9115:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9116:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9117: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9118:                return "refused:s:$crole&$cqual"; 
                   9119:             }
                   9120:         }
1.191     harris41 9121:     }
1.800     albertel 9122:     foreach my $role (split(':',$domrole)) {
                   9123: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9124:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9125:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9126: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9127:                return "refused:d:$crole&$cqual"; 
                   9128:             }
                   9129:         }
1.191     harris41 9130:     }
1.800     albertel 9131:     foreach my $role (split(':',$courole)) {
                   9132: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9133:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9134:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9135: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9136:                return "refused:c:$crole&$cqual"; 
                   9137:             }
                   9138:         }
1.191     harris41 9139:     }
1.1172.2.84  raeburn  9140:     my $uhome;
                   9141:     if (($uname ne '') && ($udom ne '')) {
                   9142:         $uhome = &homeserver($uname,$udom);
                   9143:         return $uhome if ($uhome eq 'no_host');
                   9144:     } else {
                   9145:         $uname = $env{'user.name'};
                   9146:         $udom = $env{'user.domain'};
                   9147:         $uhome = $env{'user.home'};
                   9148:     }
1.620     albertel 9149:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9150:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9151:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9152:     return reply($command,$uhome);
1.12      www      9153:   } else {
                   9154:     return 'refused';
                   9155:   }
1.105     harris41 9156: }
                   9157: 
                   9158: # ---------------- Make a metadata query against the network of library servers
                   9159: 
                   9160: sub metadata_query {
1.1172.2.33  raeburn  9161:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9162:     my %rhash;
1.845     albertel 9163:     my %libserv = &all_library();
1.244     matthew  9164:     my @server_list = (defined($server_array) ? @$server_array
                   9165:                                               : keys(%libserv) );
                   9166:     for my $server (@server_list) {
1.1172.2.33  raeburn  9167:         my $domains = '';
                   9168:         if (ref($domains_hash) eq 'HASH') {
                   9169:             $domains = $domains_hash->{$server};    
                   9170:         }
1.118     harris41 9171: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9172: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9173: 	    $rhash{$server}=$reply;
                   9174: 	}
                   9175: 	else {
                   9176: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9177: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9178: 			     $server);
                   9179: 	    $rhash{$server}=$reply;
                   9180: 	}
1.112     harris41 9181:     }
1.118     harris41 9182:     return \%rhash;
1.240     www      9183: }
                   9184: 
                   9185: # ----------------------------------------- Send log queries and wait for reply
                   9186: 
                   9187: sub log_query {
                   9188:     my ($uname,$udom,$query,%filters)=@_;
                   9189:     my $uhome=&homeserver($uname,$udom);
                   9190:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9191:     my $uhost=&hostname($uhome);
1.800     albertel 9192:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9193:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9194:                        $uhome);
1.479     albertel 9195:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9196:     return get_query_reply($queryid);
                   9197: }
                   9198: 
1.818     raeburn  9199: # -------------------------- Update MySQL table for portfolio file
                   9200: 
                   9201: sub update_portfolio_table {
1.821     raeburn  9202:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9203:     if ($group ne '') {
                   9204:         $file_name =~s /^\Q$group\E//;
                   9205:     }
1.818     raeburn  9206:     my $homeserver = &homeserver($uname,$udom);
                   9207:     my $queryid=
1.821     raeburn  9208:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9209:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9210:     my $reply = &get_query_reply($queryid);
                   9211:     return $reply;
                   9212: }
                   9213: 
1.899     raeburn  9214: # -------------------------- Update MySQL allusers table
                   9215: 
                   9216: sub update_allusers_table {
                   9217:     my ($uname,$udom,$names) = @_;
                   9218:     my $homeserver = &homeserver($uname,$udom);
                   9219:     my $queryid=
                   9220:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9221:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9222:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9223:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9224:                'generation='.&escape($names->{'generation'}).'%%'.
                   9225:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9226:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9227:     return;
1.899     raeburn  9228: }
                   9229: 
1.508     raeburn  9230: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9231: 
                   9232: sub fetch_enrollment_query {
1.511     raeburn  9233:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9234:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9235:     my $maxtries = 1;
1.508     raeburn  9236:     if ($context eq 'automated') {
                   9237:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9238:         $sleep = 2;
                   9239:         $loopmax = 100;
1.547     raeburn  9240:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9241:     } else {
                   9242:         $homeserver = &homeserver($cnum,$dom);
                   9243:     }
1.838     albertel 9244:     my $host=&hostname($homeserver);
1.506     raeburn  9245:     my $cmd = '';
1.1000    raeburn  9246:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9247:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9248:     }
                   9249:     $cmd =~ s/%%$//;
                   9250:     $cmd = &escape($cmd);
                   9251:     my $query = 'fetchenrollment';
1.620     albertel 9252:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9253:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9254:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9255:         return 'error: '.$queryid;
                   9256:     }
1.1172.2.93  raeburn  9257:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9258:     my $tries = 1;
                   9259:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9260:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9261:         $tries ++;
                   9262:     }
1.526     raeburn  9263:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9264:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9265:     } else {
1.901     albertel 9266:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9267:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9268:             foreach my $line (@responses) {
                   9269:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9270:                 $$replyref{$key} = $value;
                   9271:             }
                   9272:         } else {
1.1117    foxr     9273:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9274:             foreach my $line (@responses) {
                   9275:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9276:                 $$replyref{$key} = $value;
                   9277:                 if ($value > 0) {
1.800     albertel 9278:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9279:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9280:                         my $destname = $pathname.'/'.$filename;
                   9281:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9282:                         if ($xml_classlist =~ /^error/) {
                   9283:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9284:                         } else {
1.1172.2.96  raeburn  9285:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9286:                                 print FILE &unescape($xml_classlist);
                   9287:                                 close(FILE);
1.526     raeburn  9288:                             } else {
                   9289:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9290:                             }
                   9291:                         }
                   9292:                     }
                   9293:                 }
                   9294:             }
                   9295:         }
                   9296:         return 'ok';
                   9297:     }
                   9298:     return 'error';
                   9299: }
                   9300: 
1.242     www      9301: sub get_query_reply {
1.1172.2.79  raeburn  9302:     my ($queryid,$sleep,$loopmax) = @_;
                   9303:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9304:         $sleep = 0.2;
                   9305:     }
                   9306:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9307:         $loopmax = 100;
                   9308:     }
1.1117    foxr     9309:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9310:     my $reply='';
1.1172.2.79  raeburn  9311:     for (1..$loopmax) {
                   9312: 	sleep($sleep);
1.240     www      9313:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9314: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9315: 		$reply = join('',<$fh>);
                   9316: 		close($fh);
1.240     www      9317: 	   } else { return 'error: reply_file_error'; }
1.242     www      9318:            return &unescape($reply);
                   9319: 	}
1.240     www      9320:     }
1.242     www      9321:     return 'timeout:'.$queryid;
1.240     www      9322: }
                   9323: 
                   9324: sub courselog_query {
1.241     www      9325: #
                   9326: # possible filters:
                   9327: # url: url or symb
                   9328: # username
                   9329: # domain
                   9330: # action: view, submit, grade
                   9331: # start: timestamp
                   9332: # end: timestamp
                   9333: #
1.240     www      9334:     my (%filters)=@_;
1.620     albertel 9335:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9336:     if ($filters{'url'}) {
                   9337: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9338:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9339:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9340:     }
1.620     albertel 9341:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9342:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9343:     return &log_query($cname,$cdom,'courselog',%filters);
                   9344: }
                   9345: 
                   9346: sub userlog_query {
1.858     raeburn  9347: #
                   9348: # possible filters:
                   9349: # action: log check role
                   9350: # start: timestamp
                   9351: # end: timestamp
                   9352: #
1.240     www      9353:     my ($uname,$udom,%filters)=@_;
                   9354:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9355: }
                   9356: 
1.506     raeburn  9357: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9358: 
                   9359: sub auto_run {
1.508     raeburn  9360:     my ($cnum,$cdom) = @_;
1.876     raeburn  9361:     my $response = 0;
                   9362:     my $settings;
                   9363:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9364:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9365:         $settings = $domconfig{'autoenroll'};
                   9366:         if ($settings->{'run'} eq '1') {
                   9367:             $response = 1;
                   9368:         }
                   9369:     } else {
1.934     raeburn  9370:         my $homeserver;
                   9371:         if (&is_course($cdom,$cnum)) {
                   9372:             $homeserver = &homeserver($cnum,$cdom);
                   9373:         } else {
                   9374:             $homeserver = &domain($cdom,'primary');
                   9375:         }
                   9376:         if ($homeserver ne 'no_host') {
                   9377:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9378:         }
1.876     raeburn  9379:     }
1.506     raeburn  9380:     return $response;
                   9381: }
1.776     albertel 9382: 
1.506     raeburn  9383: sub auto_get_sections {
1.508     raeburn  9384:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9385:     my $homeserver;
                   9386:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9387:         $homeserver = &homeserver($cnum,$cdom);
                   9388:     }
                   9389:     if (!defined($homeserver)) { 
                   9390:         if ($cdom =~ /^$match_domain$/) {
                   9391:             $homeserver = &domain($cdom,'primary');
                   9392:         }
                   9393:     }
                   9394:     my @secs;
                   9395:     if (defined($homeserver)) {
                   9396:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9397:         unless ($response eq 'refused') {
                   9398:             @secs = split(/:/,$response);
                   9399:         }
1.506     raeburn  9400:     }
                   9401:     return @secs;
                   9402: }
1.776     albertel 9403: 
1.506     raeburn  9404: sub auto_new_course {
1.1099    raeburn  9405:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9406:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9407:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9408:     return $response;
                   9409: }
1.776     albertel 9410: 
1.506     raeburn  9411: sub auto_validate_courseID {
1.508     raeburn  9412:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9413:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9414:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9415:     return $response;
                   9416: }
1.776     albertel 9417: 
1.1007    raeburn  9418: sub auto_validate_instcode {
1.1020    raeburn  9419:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9420:     my ($homeserver,$response);
                   9421:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9422:         $homeserver = &homeserver($cnum,$cdom);
                   9423:     }
                   9424:     if (!defined($homeserver)) {
                   9425:         if ($cdom =~ /^$match_domain$/) {
                   9426:             $homeserver = &domain($cdom,'primary');
                   9427:         }
                   9428:     }
1.1065    raeburn  9429:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9430:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9431:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9432:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9433: }
                   9434: 
1.1172.2.141  raeburn  9435: sub auto_validate_inst_crosslist {
                   9436:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9437:     my ($homeserver,$response);
                   9438:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9439:         $homeserver = &homeserver($cnum,$cdom);
                   9440:     }
                   9441:     if (!defined($homeserver)) {
                   9442:         if ($cdom =~ /^$match_domain$/) {
                   9443:             $homeserver = &domain($cdom,'primary');
                   9444:         }
                   9445:     }
                   9446:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9447:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9448:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9449:                          &escape($coowner),$homeserver);
                   9450:     }
                   9451:     return $response;
                   9452: }
                   9453: 
1.506     raeburn  9454: sub auto_create_password {
1.873     raeburn  9455:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9456:     my ($homeserver,$response);
1.506     raeburn  9457:     my $create_passwd = 0;
                   9458:     my $authchk = '';
1.873     raeburn  9459:     if ($udom =~ /^$match_domain$/) {
                   9460:         $homeserver = &domain($udom,'primary');
                   9461:     }
                   9462:     if ($homeserver eq '') {
                   9463:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9464:             $homeserver = &homeserver($cnum,$cdom);
                   9465:         }
                   9466:     }
                   9467:     if ($homeserver eq '') {
                   9468:         $authchk = 'nodomain';
1.506     raeburn  9469:     } else {
1.873     raeburn  9470:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9471:         if ($response eq 'refused') {
                   9472:             $authchk = 'refused';
                   9473:         } else {
1.901     albertel 9474:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9475:         }
1.506     raeburn  9476:     }
                   9477:     return ($authparam,$create_passwd,$authchk);
                   9478: }
                   9479: 
1.706     raeburn  9480: sub auto_photo_permission {
                   9481:     my ($cnum,$cdom,$students) = @_;
                   9482:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9483:     my ($outcome,$perm_reqd,$conditions) = 
                   9484: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9485:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9486: 	return (undef,undef);
                   9487:     }
1.706     raeburn  9488:     return ($outcome,$perm_reqd,$conditions);
                   9489: }
                   9490: 
                   9491: sub auto_checkphotos {
                   9492:     my ($uname,$udom,$pid) = @_;
                   9493:     my $homeserver = &homeserver($uname,$udom);
                   9494:     my ($result,$resulttype);
                   9495:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9496: 				   &escape($uname).':'.&escape($pid),
                   9497: 				   $homeserver));
1.709     albertel 9498:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9499: 	return (undef,undef);
                   9500:     }
1.706     raeburn  9501:     if ($outcome) {
                   9502:         ($result,$resulttype) = split(/:/,$outcome);
                   9503:     } 
                   9504:     return ($result,$resulttype);
                   9505: }
                   9506: 
                   9507: sub auto_photochoice {
                   9508:     my ($cnum,$cdom) = @_;
                   9509:     my $homeserver = &homeserver($cnum,$cdom);
                   9510:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9511: 						       &escape($cdom),
                   9512: 						       $homeserver)));
1.709     albertel 9513:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9514: 	return (undef,undef);
                   9515:     }
1.706     raeburn  9516:     return ($update,$comment);
                   9517: }
                   9518: 
                   9519: sub auto_photoupdate {
                   9520:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9521:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9522:     my $host=&hostname($homeserver);
1.706     raeburn  9523:     my $cmd = '';
                   9524:     my $maxtries = 1;
1.800     albertel 9525:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9526:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9527:     }
                   9528:     $cmd =~ s/%%$//;
                   9529:     $cmd = &escape($cmd);
                   9530:     my $query = 'institutionalphotos';
                   9531:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9532:     unless ($queryid=~/^\Q$host\E\_/) {
                   9533:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9534:         return 'error: '.$queryid;
                   9535:     }
                   9536:     my $reply = &get_query_reply($queryid);
                   9537:     my $tries = 1;
                   9538:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9539:         $reply = &get_query_reply($queryid);
                   9540:         $tries ++;
                   9541:     }
                   9542:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9543:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9544:     } else {
                   9545:         my @responses = split(/:/,$reply);
                   9546:         my $outcome = shift(@responses); 
                   9547:         foreach my $item (@responses) {
                   9548:             my ($key,$value) = split(/=/,$item);
                   9549:             $$photo{$key} = $value;
                   9550:         }
                   9551:         return $outcome;
                   9552:     }
                   9553:     return 'error';
                   9554: }
                   9555: 
1.521     raeburn  9556: sub auto_instcode_format {
1.793     albertel 9557:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9558: 	$cat_order) = @_;
1.521     raeburn  9559:     my $courses = '';
1.772     raeburn  9560:     my @homeservers;
1.521     raeburn  9561:     if ($caller eq 'global') {
1.841     albertel 9562: 	my %servers = &get_servers($codedom,'library');
                   9563: 	foreach my $tryserver (keys(%servers)) {
                   9564: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9565: 		push(@homeservers,$tryserver);
                   9566: 	    }
1.584     raeburn  9567:         }
1.1022    raeburn  9568:     } elsif ($caller eq 'requests') {
                   9569:         if ($codedom =~ /^$match_domain$/) {
                   9570:             my $chome = &domain($codedom,'primary');
                   9571:             unless ($chome eq 'no_host') {
                   9572:                 push(@homeservers,$chome);
                   9573:             }
                   9574:         }
1.521     raeburn  9575:     } else {
1.772     raeburn  9576:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9577:     }
1.793     albertel 9578:     foreach my $code (keys(%{$instcodes})) {
                   9579:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9580:     }
                   9581:     chop($courses);
1.772     raeburn  9582:     my $ok_response = 0;
                   9583:     my $response;
                   9584:     while (@homeservers > 0 && $ok_response == 0) {
                   9585:         my $server = shift(@homeservers); 
                   9586:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9587:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9588:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9589: 		split(/:/,$response);
1.772     raeburn  9590:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9591:             push(@{$codetitles},&str2array($codetitles_str));
                   9592:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9593:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9594:             $ok_response = 1;
                   9595:         }
                   9596:     }
                   9597:     if ($ok_response) {
1.521     raeburn  9598:         return 'ok';
1.772     raeburn  9599:     } else {
                   9600:         return $response;
1.521     raeburn  9601:     }
                   9602: }
                   9603: 
1.792     raeburn  9604: sub auto_instcode_defaults {
                   9605:     my ($domain,$returnhash,$code_order) = @_;
                   9606:     my @homeservers;
1.841     albertel 9607: 
                   9608:     my %servers = &get_servers($domain,'library');
                   9609:     foreach my $tryserver (keys(%servers)) {
                   9610: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9611: 	    push(@homeservers,$tryserver);
                   9612: 	}
1.792     raeburn  9613:     }
1.841     albertel 9614: 
1.792     raeburn  9615:     my $response;
1.841     albertel 9616:     foreach my $server (@homeservers) {
1.792     raeburn  9617:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9618:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9619: 	
                   9620: 	foreach my $pair (split(/\&/,$response)) {
                   9621: 	    my ($name,$value)=split(/\=/,$pair);
                   9622: 	    if ($name eq 'code_order') {
                   9623: 		@{$code_order} = split(/\&/,&unescape($value));
                   9624: 	    } else {
                   9625: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9626: 	    }
                   9627: 	}
                   9628: 	return 'ok';
1.792     raeburn  9629:     }
1.841     albertel 9630: 
                   9631:     return $response;
1.1003    raeburn  9632: }
                   9633: 
                   9634: sub auto_possible_instcodes {
1.1007    raeburn  9635:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9636:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9637:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9638:         return;
                   9639:     }
1.1003    raeburn  9640:     my (@homeservers,$uhome);
                   9641:     if (defined(&domain($domain,'primary'))) {
                   9642:         $uhome=&domain($domain,'primary');
                   9643:         push(@homeservers,&domain($domain,'primary'));
                   9644:     } else {
                   9645:         my %servers = &get_servers($domain,'library');
                   9646:         foreach my $tryserver (keys(%servers)) {
                   9647:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9648:                 push(@homeservers,$tryserver);
                   9649:             }
                   9650:         }
                   9651:     }
                   9652:     my $response;
                   9653:     foreach my $server (@homeservers) {
                   9654:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9655:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9656:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9657:             split(':',$response);
                   9658:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9659:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9660:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9661:             my ($name,$value)=split('=',$item);
                   9662:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9663:         }
                   9664:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9665:             my ($name,$value)=split('=',$item);
                   9666:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9667:         }
                   9668:         return 'ok';
                   9669:     }
                   9670:     return $response;
                   9671: }
1.792     raeburn  9672: 
1.1010    raeburn  9673: sub auto_courserequest_checks {
                   9674:     my ($dom) = @_;
1.1020    raeburn  9675:     my ($homeserver,%validations);
                   9676:     if ($dom =~ /^$match_domain$/) {
                   9677:         $homeserver = &domain($dom,'primary');
                   9678:     }
                   9679:     unless ($homeserver eq 'no_host') {
                   9680:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9681:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9682:             my @items = split(/&/,$response);
                   9683:             foreach my $item (@items) {
                   9684:                 my ($key,$value) = split('=',$item);
                   9685:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9686:             }
                   9687:         }
                   9688:     }
1.1010    raeburn  9689:     return %validations; 
                   9690: }
                   9691: 
1.1020    raeburn  9692: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9693:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9694:     my ($homeserver,$response);
                   9695:     if ($dom =~ /^$match_domain$/) {
                   9696:         $homeserver = &domain($dom,'primary');
                   9697:     }
1.1172.2.43  raeburn  9698:     unless ($homeserver eq 'no_host') {
                   9699:         my $customdata;
                   9700:         if (ref($custominfo) eq 'HASH') {
                   9701:             $customdata = &freeze_escape($custominfo);
                   9702:         }
1.1020    raeburn  9703:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9704:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9705:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9706:                                     $customdata,$homeserver));
1.1020    raeburn  9707:     }
                   9708:     return $response;
                   9709: }
                   9710: 
1.777     albertel 9711: sub auto_validate_class_sec {
1.918     raeburn  9712:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9713:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9714:     my $ownerlist;
                   9715:     if (ref($owners) eq 'ARRAY') {
                   9716:         $ownerlist = join(',',@{$owners});
                   9717:     } else {
                   9718:         $ownerlist = $owners;
                   9719:     }
1.773     raeburn  9720:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9721:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9722:     return $response;
                   9723: }
                   9724: 
1.1172.2.141  raeburn  9725: sub auto_instsec_reformat {
                   9726:     my ($cdom,$action,$instsecref) = @_;
                   9727:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9728:     my @homeservers;
                   9729:     if (defined(&domain($cdom,'primary'))) {
                   9730:         push(@homeservers,&domain($cdom,'primary'));
                   9731:     } else {
                   9732:         my %servers = &get_servers($cdom,'library');
                   9733:         foreach my $tryserver (keys(%servers)) {
                   9734:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9735:                 push(@homeservers,$tryserver);
                   9736:             }
                   9737:         }
                   9738:     }
                   9739:     my $response;
                   9740:     my %reformatted = %{$instsecref};
                   9741:     foreach my $server (@homeservers) {
                   9742:         if (ref($instsecref) eq 'HASH') {
                   9743:             my $info = &freeze_escape($instsecref);
                   9744:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9745:                                 $action.':'.$info,$server);
                   9746:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9747:             my @items = split(/&/,$response);
                   9748:             foreach my $item (@items) {
                   9749:                 my ($key,$value) = split(/=/,$item);
                   9750:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9751:             }
                   9752:         }
                   9753:     }
                   9754:     return %reformatted;
                   9755: }
                   9756: 
1.1172.2.94  raeburn  9757: sub auto_validate_instclasses {
                   9758:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9759:     my ($homeserver,%validations);
                   9760:     $homeserver = &homeserver($cnum,$cdom);
                   9761:     unless ($homeserver eq 'no_host') {
                   9762:         my $ownerlist;
                   9763:         if (ref($owners) eq 'ARRAY') {
                   9764:             $ownerlist = join(',',@{$owners});
                   9765:         } else {
                   9766:             $ownerlist = $owners;
                   9767:         }
                   9768:         if (ref($classesref) eq 'HASH') {
                   9769:             my $classes = &freeze_escape($classesref);
                   9770:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9771:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9772:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9773:                 my @items = split(/&/,$response);
                   9774:                 foreach my $item (@items) {
                   9775:                     my ($key,$value) = split('=',$item);
                   9776:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9777:                 }
                   9778:             }
                   9779:         }
                   9780:     }
                   9781:     return %validations;
                   9782: }
                   9783: 
1.1172.2.38  raeburn  9784: sub auto_crsreq_update {
                   9785:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9786:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9787:     my ($homeserver,%crsreqresponse);
                   9788:     if ($cdom =~ /^$match_domain$/) {
                   9789:         $homeserver = &domain($cdom,'primary');
                   9790:     }
                   9791:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9792:         my $info;
                   9793:         if (ref($inbound) eq 'HASH') {
                   9794:             $info = &freeze_escape($inbound);
                   9795:         }
                   9796:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9797:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9798:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9799:                             &escape($title).':'.&escape($code).':'.
                   9800:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9801:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9802:             my @items = split(/&/,$response);
                   9803:             foreach my $item (@items) {
                   9804:                 my ($key,$value) = split('=',$item);
                   9805:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9806:             }
                   9807:         }
                   9808:     }
                   9809:     return \%crsreqresponse;
                   9810: }
                   9811: 
1.1172.2.78  raeburn  9812: sub auto_export_grades {
                   9813:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9814:     my ($homeserver,%exportresponse);
                   9815:     if ($cdom =~ /^$match_domain$/) {
                   9816:         $homeserver = &domain($cdom,'primary');
                   9817:     }
                   9818:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9819:         my $info;
                   9820:         if (ref($inforef) eq 'HASH') {
                   9821:             $info = &freeze_escape($inforef);
                   9822:         }
                   9823:         if (ref($gradesref) eq 'HASH') {
                   9824:             my $grades = &freeze_escape($gradesref);
                   9825:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9826:                                 $info.':'.$grades,$homeserver);
                   9827:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9828:                 my @items = split(/&/,$response);
                   9829:                 foreach my $item (@items) {
                   9830:                     my ($key,$value) = split('=',$item);
                   9831:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9832:                 }
                   9833:             }
                   9834:         }
                   9835:     }
                   9836:     return \%exportresponse;
                   9837: }
                   9838: 
1.1172.2.68  raeburn  9839: sub check_instcode_cloning {
                   9840:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9841:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9842:         return;
                   9843:     }
                   9844:     my $canclone;
                   9845:     if (@{$code_order} > 0) {
                   9846:         my $instcoderegexp ='^';
                   9847:         my @clonecodes = split(/\&/,$cloner);
                   9848:         foreach my $item (@{$code_order}) {
                   9849:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9850:                 foreach my $pair (@clonecodes) {
                   9851:                     my ($key,$val) = split(/\=/,$pair,2);
                   9852:                     $val = &unescape($val);
                   9853:                     if ($key eq $item) {
                   9854:                         $instcoderegexp .= '('.$val.')';
                   9855:                         last;
                   9856:                     }
                   9857:                 }
                   9858:             } else {
                   9859:                 $instcoderegexp .= $codedefaults->{$item};
                   9860:             }
                   9861:         }
                   9862:         $instcoderegexp .= '$';
                   9863:         my (@from,@to);
                   9864:         eval {
                   9865:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9866:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9867:         };
                   9868:         if ((@from > 0) && (@to > 0)) {
                   9869:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9870:             if (!@diffs) {
                   9871:                 $canclone = 1;
                   9872:             }
                   9873:         }
                   9874:     }
                   9875:     return $canclone;
                   9876: }
                   9877: 
                   9878: sub default_instcode_cloning {
                   9879:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9880:     my (%codedefaults,@code_order,$canclone);
                   9881:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9882:         %codedefaults = %{$codedefaultsref};
                   9883:         @code_order = @{$codeorderref};
                   9884:     } elsif ($clonedom) {
                   9885:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9886:     }
                   9887:     if (($domdefclone) && (@code_order)) {
                   9888:         my @clonecodes = split(/\+/,$domdefclone);
                   9889:         my $instcoderegexp ='^';
                   9890:         foreach my $item (@code_order) {
                   9891:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9892:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9893:             } else {
                   9894:                 $instcoderegexp .= $codedefaults{$item};
                   9895:             }
                   9896:         }
                   9897:         $instcoderegexp .= '$';
                   9898:         my (@from,@to);
                   9899:         eval {
                   9900:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9901:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9902:         };
                   9903:         if ((@from > 0) && (@to > 0)) {
                   9904:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9905:             if (!@diffs) {
                   9906:                 $canclone = 1;
                   9907:             }
                   9908:         }
                   9909:     }
                   9910:     return $canclone;
                   9911: }
                   9912: 
1.679     raeburn  9913: # ------------------------------------------------------- Course Group routines
                   9914: 
                   9915: sub get_coursegroups {
1.809     raeburn  9916:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9917:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9918: }
                   9919: 
1.679     raeburn  9920: sub modify_coursegroup {
                   9921:     my ($cdom,$cnum,$groupsettings) = @_;
                   9922:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9923: }
                   9924: 
1.809     raeburn  9925: sub toggle_coursegroup_status {
                   9926:     my ($cdom,$cnum,$group,$action) = @_;
                   9927:     my ($from_namespace,$to_namespace);
                   9928:     if ($action eq 'delete') {
                   9929:         $from_namespace = 'coursegroups';
                   9930:         $to_namespace = 'deleted_groups';
                   9931:     } else {
                   9932:         $from_namespace = 'deleted_groups';
                   9933:         $to_namespace = 'coursegroups';
                   9934:     }
                   9935:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9936:     if (my $tmp = &error(%curr_group)) {
                   9937:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9938:         return ('read error',$tmp);
                   9939:     } else {
                   9940:         my %savedsettings = %curr_group; 
1.809     raeburn  9941:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9942:         my $deloutcome;
                   9943:         if ($result eq 'ok') {
1.809     raeburn  9944:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9945:         } else {
                   9946:             return ('write error',$result);
                   9947:         }
                   9948:         if ($deloutcome eq 'ok') {
                   9949:             return 'ok';
                   9950:         } else {
                   9951:             return ('delete error',$deloutcome);
                   9952:         }
                   9953:     }
                   9954: }
                   9955: 
1.679     raeburn  9956: sub modify_group_roles {
1.957     raeburn  9957:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9958:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9959:     my $role = 'gr/'.&escape($userprivs);
                   9960:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9961:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9962:     if ($result eq 'ok') {
                   9963:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9964:     }
1.679     raeburn  9965:     return $result;
                   9966: }
                   9967: 
                   9968: sub modify_coursegroup_membership {
                   9969:     my ($cdom,$cnum,$membership) = @_;
                   9970:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9971:     return $result;
                   9972: }
                   9973: 
1.682     raeburn  9974: sub get_active_groups {
                   9975:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9976:     my $now = time;
                   9977:     my %groups = ();
                   9978:     foreach my $key (keys(%env)) {
1.811     albertel 9979:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9980:             my ($start,$end) = split(/\./,$env{$key});
                   9981:             if (($end!=0) && ($end<$now)) { next; }
                   9982:             if (($start!=0) && ($start>$now)) { next; }
                   9983:             if ($1 eq $cdom && $2 eq $cnum) {
                   9984:                 $groups{$3} = $env{$key} ;
                   9985:             }
                   9986:         }
                   9987:     }
                   9988:     return %groups;
                   9989: }
                   9990: 
1.683     raeburn  9991: sub get_group_membership {
                   9992:     my ($cdom,$cnum,$group) = @_;
                   9993:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9994: }
                   9995: 
                   9996: sub get_users_groups {
                   9997:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9998:     my @usersgroups;
1.683     raeburn  9999:     my $cachetime=1800;
                   10000: 
                   10001:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10002:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10003:     if (defined($cached)) {
1.734     albertel 10004:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10005:     } else {  
                   10006:         $grouplist = '';
1.816     raeburn  10007:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10008:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10009:         my $access_end = $env{'course.'.$courseid.
                   10010:                               '.default_enrollment_end_date'};
                   10011:         my $now = time;
                   10012:         foreach my $key (keys(%roleshash)) {
                   10013:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10014:                 my $group = $1;
                   10015:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10016:                     my $start = $2;
                   10017:                     my $end = $1;
                   10018:                     if ($start == -1) { next; } # deleted from group
                   10019:                     if (($start!=0) && ($start>$now)) { next; }
                   10020:                     if (($end!=0) && ($end<$now)) {
                   10021:                         if ($access_end && $access_end < $now) {
                   10022:                             if ($access_end - $end < 86400) {
                   10023:                                 push(@usersgroups,$group);
1.733     raeburn  10024:                             }
                   10025:                         }
1.817     raeburn  10026:                         next;
1.733     raeburn  10027:                     }
1.817     raeburn  10028:                     push(@usersgroups,$group);
1.683     raeburn  10029:                 }
                   10030:             }
                   10031:         }
1.817     raeburn  10032:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10033:         $grouplist = join(':',@usersgroups);
                   10034:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10035:     }
1.733     raeburn  10036:     return @usersgroups;
1.683     raeburn  10037: }
                   10038: 
                   10039: sub devalidate_getgroups_cache {
                   10040:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10041:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10042: 
1.683     raeburn  10043:     my $hashid="$udom:$uname:$courseid";
                   10044:     &devalidate_cache_new('getgroups',$hashid);
                   10045: }
                   10046: 
1.12      www      10047: # ------------------------------------------------------------------ Plain Text
                   10048: 
                   10049: sub plaintext {
1.988     raeburn  10050:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10051:     if ($short =~ m{^cr/}) {
1.758     albertel 10052: 	return (split('/',$short))[-1];
                   10053:     }
1.742     raeburn  10054:     if (!defined($cid)) {
                   10055:         $cid = $env{'request.course.id'};
                   10056:     }
                   10057:     my %rolenames = (
1.1008    raeburn  10058:                       Course    => 'std',
                   10059:                       Community => 'alt1',
1.742     raeburn  10060:                     );
1.1037    raeburn  10061:     if ($cid ne '') {
                   10062:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10063:             unless ($forcedefault) {
                   10064:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10065:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10066:                 return &Apache::lonlocal::mt($roletext);
                   10067:             }
                   10068:         }
                   10069:     }
                   10070:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10071:         (defined($rolenames{$type})) && 
                   10072:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10073:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10074:     } elsif ($cid ne '') {
                   10075:         my $crstype = $env{'course.'.$cid.'.type'};
                   10076:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10077:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10078:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10079:         }
1.742     raeburn  10080:     }
1.1037    raeburn  10081:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10082: }
                   10083: 
                   10084: # ----------------------------------------------------------------- Assign Role
                   10085: 
                   10086: sub assignrole {
1.957     raeburn  10087:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10088:         $context)=@_;
1.21      www      10089:     my $mrole;
                   10090:     if ($role =~ /^cr\//) {
1.393     www      10091:         my $cwosec=$url;
1.811     albertel 10092:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10093: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10094:            my $refused = 1;
                   10095:            if ($context eq 'requestcourses') {
                   10096:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10097:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10098:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10099:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10100:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10101:                            if ($crsenv{'internal.courseowner'} eq
                   10102:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10103:                                $refused = '';
                   10104:                            }
                   10105:                        }
                   10106:                    }
                   10107:                }
                   10108:            }
                   10109:            if ($refused) {
                   10110:                &logthis('Refused custom assignrole: '.
                   10111:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10112:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10113:                return 'refused';
                   10114:            }
1.104     www      10115:         }
1.21      www      10116:         $mrole='cr';
1.678     raeburn  10117:     } elsif ($role =~ /^gr\//) {
                   10118:         my $cwogrp=$url;
1.811     albertel 10119:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10120:         unless (&allowed('mdg',$cwogrp)) {
                   10121:             &logthis('Refused group assignrole: '.
                   10122:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10123:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10124:             return 'refused';
                   10125:         }
                   10126:         $mrole='gr';
1.21      www      10127:     } else {
1.82      www      10128:         my $cwosec=$url;
1.811     albertel 10129:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10130:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10131:             my $refused;
                   10132:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10133:                 if (!(&allowed('c'.$role,$url))) {
                   10134:                     $refused = 1;
                   10135:                 }
                   10136:             } else {
                   10137:                 $refused = 1;
                   10138:             }
1.947     raeburn  10139:             if ($refused) {
1.1045    raeburn  10140:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10141:                 if (!$selfenroll && $context eq 'course') {
                   10142:                     my %crsenv;
                   10143:                     if ($role eq 'cc' || $role eq 'co') {
                   10144:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10145:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10146:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10147:                                 if ($crsenv{'internal.courseowner'} eq 
                   10148:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10149:                                     $refused = '';
                   10150:                                 }
                   10151:                             }
                   10152:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10153:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10154:                                 if ($crsenv{'internal.courseowner'} eq 
                   10155:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10156:                                     $refused = '';
                   10157:                                 }
                   10158:                             }
                   10159:                         }
                   10160:                     }
                   10161:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10162:                     $refused = '';
1.1017    raeburn  10163:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10164:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10165:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10166:                         my $wrongcc;
                   10167:                         if ($cnum =~ /^$match_community$/) {
                   10168:                             $wrongcc = 1 if ($role eq 'cc');
                   10169:                         } else {
                   10170:                             $wrongcc = 1 if ($role eq 'co');
                   10171:                         }
                   10172:                         unless ($wrongcc) {
                   10173:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10174:                             if ($crsenv{'internal.courseowner'} eq 
                   10175:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10176:                                 $refused = '';
                   10177:                             }
1.1017    raeburn  10178:                         }
                   10179:                     }
1.1172.2.9  raeburn  10180:                 } elsif ($context eq 'requestauthor') {
                   10181:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10182:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10183:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10184:                             $refused = '';
                   10185:                         } else {
                   10186:                             my %domdefaults = &get_domain_defaults($udom);
                   10187:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10188:                                 my $checkbystatus;
                   10189:                                 if ($env{'user.adv'}) {
                   10190:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10191:                                     if ($disposition eq 'automatic') {
                   10192:                                         $refused = '';
                   10193:                                     } elsif ($disposition eq '') {
                   10194:                                         $checkbystatus = 1;
                   10195:                                     }
                   10196:                                 } else {
                   10197:                                     $checkbystatus = 1;
                   10198:                                 }
                   10199:                                 if ($checkbystatus) {
                   10200:                                     if ($env{'environment.inststatus'}) {
                   10201:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10202:                                         foreach my $type (@inststatuses) {
                   10203:                                             if (($type ne '') &&
                   10204:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10205:                                                 $refused = '';
                   10206:                                             }
                   10207:                                         }
                   10208:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10209:                                         $refused = '';
                   10210:                                     }
                   10211:                                 }
                   10212:                             }
                   10213:                         }
                   10214:                     }
1.1017    raeburn  10215:                 }
                   10216:                 if ($refused) {
1.947     raeburn  10217:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10218:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10219: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10220:                     return 'refused';
                   10221:                 }
1.932     raeburn  10222:             }
1.1131    raeburn  10223:         } elsif ($role eq 'au') {
                   10224:             if ($url ne '/'.$udom.'/') {
                   10225:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10226:                          ' to assign author role for '.$uname.':'.$udom.
                   10227:                          ' in domain: '.$url.' refused (wrong domain).');
                   10228:                 return 'refused';
                   10229:             }
1.104     www      10230:         }
1.21      www      10231:         $mrole=$role;
                   10232:     }
1.620     albertel 10233:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10234:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10235:     if ($end) { $command.='_'.$end; }
1.21      www      10236:     if ($start) {
                   10237: 	if ($end) { 
1.81      www      10238:            $command.='_'.$start; 
1.21      www      10239:         } else {
1.81      www      10240:            $command.='_0_'.$start;
1.21      www      10241:         }
                   10242:     }
1.739     raeburn  10243:     my $origstart = $start;
                   10244:     my $origend = $end;
1.957     raeburn  10245:     my $delflag;
1.357     www      10246: # actually delete
                   10247:     if ($deleteflag) {
1.373     www      10248: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10249: # modify command to delete the role
1.620     albertel 10250:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10251:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10252: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10253: # set start and finish to negative values for userrolelog
                   10254:            $start=-1;
                   10255:            $end=-1;
1.957     raeburn  10256:            $delflag = 1;
1.357     www      10257:         }
                   10258:     }
                   10259: # send command
1.349     www      10260:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10261: # log new user role if status is ok
1.349     www      10262:     if ($answer eq 'ok') {
1.663     raeburn  10263: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10264:         if (($role eq 'cc') || ($role eq 'in') ||
                   10265:             ($role eq 'ep') || ($role eq 'ad') ||
                   10266:             ($role eq 'ta') || ($role eq 'st') ||
                   10267:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10268:             ($role eq 'co')) {
1.1172.2.13  raeburn  10269: # for course roles, perform group memberships changes triggered by role change.
                   10270:             unless ($role =~ /^gr/) {
                   10271:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10272:                                                  $origstart,$selfenroll,$context);
                   10273:             }
1.1172.2.9  raeburn  10274:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10275:                            $selfenroll,$context);
                   10276:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10277:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10278:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10279:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10280:                            $context);
                   10281:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10282:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10283:                              $context);
                   10284:         }
1.1053    raeburn  10285:         if ($role eq 'cc') {
                   10286:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10287:         }
1.349     www      10288:     }
                   10289:     return $answer;
1.169     harris41 10290: }
                   10291: 
1.1053    raeburn  10292: sub autoupdate_coowners {
                   10293:     my ($url,$end,$start,$uname,$udom) = @_;
                   10294:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10295:     if (($cdom ne '') && ($cnum ne '')) {
                   10296:         my $now = time;
                   10297:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10298:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10299:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10300:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10301:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10302:             if ($instcode ne '') {
1.1056    raeburn  10303:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10304:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10305:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10306:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10307:                         unless ($result eq 'valid') {
                   10308:                             if ($xlists ne '') {
                   10309:                                 foreach my $xlist (split(',',$xlists)) {
                   10310:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10311:                                     $result =
                   10312:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10313:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10314:                                     last if ($result eq 'valid');
                   10315:                                 }
                   10316:                             }
                   10317:                         }
1.1056    raeburn  10318:                         if ($result eq 'valid') {
                   10319:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10320:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10321:                                     push(@newcoowners,$coowner);
                   10322:                                 }
                   10323:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10324:                                     push(@newcoowners,$uname.':'.$udom);
                   10325:                                 }
                   10326:                                 @newcoowners = sort(@newcoowners);
                   10327:                             } else {
                   10328:                                 push(@newcoowners,$uname.':'.$udom);
                   10329:                             }
1.1172.2.141  raeburn  10330:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10331:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10332:                                 unless ($coowner eq $uname.':'.$udom) {
                   10333:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10334:                                 }
                   10335:                             }
1.1172.2.141  raeburn  10336:                             unless (@newcoowners > 0) {
                   10337:                                 $delcoowners = 1;
                   10338:                                 $coowners = '';
                   10339:                             }
1.1053    raeburn  10340:                         }
                   10341:                         if (@newcoowners || $delcoowners) {
                   10342:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10343:                                             $delcoowners,@newcoowners);
                   10344:                         }
                   10345:                     }
                   10346:                 }
                   10347:             }
                   10348:         }
                   10349:     }
                   10350: }
                   10351: 
                   10352: sub store_coowners {
                   10353:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10354:     my $cid = $cdom.'_'.$cnum;
                   10355:     my ($coowners,$delresult,$putresult);
                   10356:     if (@newcoowners) {
                   10357:         $coowners = join(',',@newcoowners);
                   10358:         my %coownershash = (
                   10359:                             'internal.co-owners' => $coowners,
                   10360:                            );
                   10361:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10362:         if ($putresult eq 'ok') {
                   10363:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10364:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10365:             }
                   10366:         }
                   10367:     }
                   10368:     if ($delcoowners) {
                   10369:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10370:         if ($delresult eq 'ok') {
                   10371:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10372:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10373:             }
                   10374:         }
                   10375:     }
                   10376:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10377:         my %crsinfo =
                   10378:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10379:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10380:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10381:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10382:         }
                   10383:     }
                   10384: }
                   10385: 
1.169     harris41 10386: # -------------------------------------------------- Modify user authentication
1.197     www      10387: # Overrides without validation
                   10388: 
1.169     harris41 10389: sub modifyuserauth {
                   10390:     my ($udom,$uname,$umode,$upass)=@_;
                   10391:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10392:     my $allowed;
                   10393:     if (&allowed('mau',$udom)) {
                   10394:         $allowed = 1;
                   10395:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10396:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10397:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10398:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10399:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10400:         if (($cdom ne '') && ($cnum ne '')) {
                   10401:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10402:             if ($is_owner) {
                   10403:                 $allowed = 1;
                   10404:             }
                   10405:         }
                   10406:     }
                   10407:     unless ($allowed) { return 'refused'; }
1.197     www      10408:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10409:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10410:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10411:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10412: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10413:     my $ip = &get_requestor_ip();
1.620     albertel 10414:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10415:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10416:          '(Remote '.$ip.'): '.$reply);
1.197     www      10417:     &log($udom,,$uname,$uhome,
1.620     albertel 10418:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10419:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10420:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10421:     unless ($reply eq 'ok') {
1.197     www      10422:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10423: 	return 'error: '.$reply;
                   10424:     }   
1.170     harris41 10425:     return 'ok';
1.80      www      10426: }
                   10427: 
1.81      www      10428: # --------------------------------------------------------------- Modify a user
1.80      www      10429: 
1.81      www      10430: sub modifyuser {
1.206     matthew  10431:     my ($udom,    $uname, $uid,
                   10432:         $umode,   $upass, $first,
                   10433:         $middle,  $last,  $gene,
1.1058    raeburn  10434:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10435:     $udom= &LONCAPA::clean_domain($udom);
                   10436:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10437:     my $showcandelete = 'none';
                   10438:     if (ref($candelete) eq 'ARRAY') {
                   10439:         if (@{$candelete} > 0) {
                   10440:             $showcandelete = join(', ',@{$candelete});
                   10441:         }
                   10442:     }
1.81      www      10443:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10444:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10445: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10446:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10447:                                      ' desiredhome not specified'). 
1.620     albertel 10448:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10449:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10450:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10451:     my $newuser;
                   10452:     if ($uhome eq 'no_host') {
                   10453:         $newuser = 1;
                   10454:     }
1.80      www      10455: # ----------------------------------------------------------------- Create User
1.406     albertel 10456:     if (($uhome eq 'no_host') && 
                   10457: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10458:         my $unhome='';
1.844     albertel 10459:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10460:             $unhome = $desiredhome;
1.620     albertel 10461: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10462: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10463:         } else { # load balancing routine for determining $unhome
1.81      www      10464:             my $loadm=10000000;
1.841     albertel 10465: 	    my %servers = &get_servers($udom,'library');
                   10466: 	    foreach my $tryserver (keys(%servers)) {
                   10467: 		my $answer=reply('load',$tryserver);
                   10468: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10469: 		    $loadm=$answer;
                   10470: 		    $unhome=$tryserver;
                   10471: 		}
1.80      www      10472: 	    }
                   10473:         }
                   10474:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10475: 	    return 'error: unable to find a home server for '.$uname.
                   10476:                    ' in domain '.$udom;
1.80      www      10477:         }
                   10478:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10479:                          &escape($upass),$unhome);
                   10480: 	unless ($reply eq 'ok') {
                   10481:             return 'error: '.$reply;
                   10482:         }   
1.230     stredwic 10483:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10484:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10485: 	    return 'error: unable verify users home machine.';
1.80      www      10486:         }
1.209     matthew  10487:     }   # End of creation of new user
1.80      www      10488: # ---------------------------------------------------------------------- Add ID
                   10489:     if ($uid) {
                   10490:        $uid=~tr/A-Z/a-z/;
                   10491:        my %uidhash=&idrget($udom,$uname);
1.196     www      10492:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10493:          && (!$forceid)) {
1.80      www      10494: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10495: 	      return 'error: user id "'.$uid.'" does not match '.
                   10496:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10497:           }
                   10498:        } else {
                   10499: 	  &idput($udom,($uname => $uid));
                   10500:        }
                   10501:     }
                   10502: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10503:     my @tmp=&get('environment',
1.899     raeburn  10504: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10505:                     'permanentemail','inststatus'],
1.134     albertel 10506: 		   $udom,$uname);
1.1075    raeburn  10507:     my (%names,%oldnames);
1.313     matthew  10508:     if ($tmp[0] =~ m/^error:.*/) { 
                   10509:         %names=(); 
                   10510:     } else {
                   10511:         %names = @tmp;
1.1075    raeburn  10512:         %oldnames = %names;
1.313     matthew  10513:     }
1.388     www      10514: #
1.1058    raeburn  10515: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10516: # of users did not contain them), do not overwrite existing values
                   10517: # unless field is in $candelete array ref.  
                   10518: #
                   10519: 
                   10520:     my @fields = ('firstname','middlename','lastname','generation',
                   10521:                   'permanentemail','id');
                   10522:     my %newvalues;
                   10523:     if (ref($candelete) eq 'ARRAY') {
                   10524:         foreach my $field (@fields) {
                   10525:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10526:                 if ($field eq 'firstname') {
                   10527:                     $names{$field} = $first;
                   10528:                 } elsif ($field eq 'middlename') {
                   10529:                     $names{$field} = $middle;
                   10530:                 } elsif ($field eq 'lastname') {
                   10531:                     $names{$field} = $last;
                   10532:                 } elsif ($field eq 'generation') { 
                   10533:                     $names{$field} = $gene;
                   10534:                 } elsif ($field eq 'permanentemail') {
                   10535:                     $names{$field} = $email;
                   10536:                 } elsif ($field eq 'id') {
                   10537:                     $names{$field}  = $uid;
                   10538:                 }
                   10539:             }
                   10540:         }
                   10541:     }
1.388     www      10542:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10543:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10544:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10545:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10546:     if ($email) {
                   10547:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10548:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10549:     }
1.899     raeburn  10550:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10551:     if (defined($inststatus)) {
                   10552:         $names{'inststatus'} = '';
                   10553:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10554:         if (ref($usertypes) eq 'HASH') {
                   10555:             my @okstatuses; 
                   10556:             foreach my $item (split(/:/,$inststatus)) {
                   10557:                 if (defined($usertypes->{$item})) {
                   10558:                     push(@okstatuses,$item);  
                   10559:                 }
                   10560:             }
                   10561:             if (@okstatuses) {
                   10562:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10563:             }
                   10564:         }
                   10565:     }
1.1075    raeburn  10566:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10567:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10568:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10569:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10570:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10571:     } else {
                   10572:         $logmsg .= ' during self creation';
                   10573:     }
1.1075    raeburn  10574:     my $changed;
                   10575:     if ($newuser) {
                   10576:         $changed = 1;
                   10577:     } else {
                   10578:         foreach my $field (@fields) {
                   10579:             if ($names{$field} ne $oldnames{$field}) {
                   10580:                 $changed = 1;
                   10581:                 last;
                   10582:             }
                   10583:         }
                   10584:     }
                   10585:     unless ($changed) {
                   10586:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10587:         &logthis($logmsg);
                   10588:         return 'ok';
                   10589:     }
                   10590:     my $reply = &put('environment', \%names, $udom,$uname);
                   10591:     if ($reply ne 'ok') { 
                   10592:         return 'error: '.$reply;
                   10593:     }
1.1087    raeburn  10594:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10595:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10596:     }
1.1075    raeburn  10597:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10598:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10599:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10600:     &logthis($logmsg);
1.134     albertel 10601:     return 'ok';
1.80      www      10602: }
                   10603: 
1.81      www      10604: # -------------------------------------------------------------- Modify student
1.80      www      10605: 
1.81      www      10606: sub modifystudent {
                   10607:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10608:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10609:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10610:     if (!$cid) {
1.620     albertel 10611: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10612: 	    return 'not_in_class';
                   10613: 	}
1.80      www      10614:     }
                   10615: # --------------------------------------------------------------- Make the user
1.81      www      10616:     my $reply=&modifyuser
1.209     matthew  10617: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10618:          $desiredhome,$email,$inststatus);
1.80      www      10619:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10620:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10621:     # student's environment
1.297     matthew  10622:     $uid = undef if (!$forceid);
1.455     albertel 10623:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10624: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10625:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10626:     return $reply;
                   10627: }
                   10628: 
                   10629: sub modify_student_enrollment {
1.1172.2.23  raeburn  10630:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10631:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10632:     my ($cdom,$cnum,$chome);
                   10633:     if (!$cid) {
1.620     albertel 10634: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10635: 	    return 'not_in_class';
                   10636: 	}
1.620     albertel 10637: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10638: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10639:     } else {
                   10640: 	($cdom,$cnum)=split(/_/,$cid);
                   10641:     }
1.620     albertel 10642:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10643:     if (!$chome) {
1.457     raeburn  10644: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10645:     }
1.455     albertel 10646:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10647:     # Make sure the user exists
1.81      www      10648:     my $uhome=&homeserver($uname,$udom);
                   10649:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10650: 	return 'error: no such user';
                   10651:     }
1.297     matthew  10652:     # Get student data if we were not given enough information
                   10653:     if (!defined($first)  || $first  eq '' || 
                   10654:         !defined($last)   || $last   eq '' || 
                   10655:         !defined($uid)    || $uid    eq '' || 
                   10656:         !defined($middle) || $middle eq '' || 
                   10657:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10658:         # They did not supply us with enough data to enroll the student, so
                   10659:         # we need to pick up more information.
1.297     matthew  10660:         my %tmp = &get('environment',
1.294     matthew  10661:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10662:                        ,$udom,$uname);
                   10663: 
1.800     albertel 10664:         #foreach my $key (keys(%tmp)) {
                   10665:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10666:         #}
1.294     matthew  10667:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10668:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10669:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10670:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10671:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10672:     }
1.556     albertel 10673:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10674:     my $user = "$uname:$udom";
                   10675:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10676:     my $reply=cput('classlist',
1.1148    raeburn  10677: 		   {$user => 
1.1172.2.76  raeburn  10678: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10679: 		   $cdom,$cnum);
1.1148    raeburn  10680:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10681:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10682:     } else { 
1.81      www      10683: 	return 'error: '.$reply;
                   10684:     }
1.297     matthew  10685:     # Add student role to user
1.83      www      10686:     my $uurl='/'.$cid;
1.81      www      10687:     $uurl=~s/\_/\//g;
                   10688:     if ($usec) {
                   10689: 	$uurl.='/'.$usec;
                   10690:     }
1.1148    raeburn  10691:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10692:                              $selfenroll,$context);
                   10693:     if ($result ne 'ok') {
                   10694:         if ($old_entry{$user} ne '') {
                   10695:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10696:         } else {
                   10697:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10698:         }
                   10699:     }
                   10700:     return $result; 
1.21      www      10701: }
                   10702: 
1.556     albertel 10703: sub format_name {
                   10704:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10705:     my $name;
                   10706:     if ($first ne 'lastname') {
                   10707: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10708:     } else {
                   10709: 	if ($lastname=~/\S/) {
                   10710: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10711: 	    $name=~s/\s+,/,/;
                   10712: 	} else {
                   10713: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10714: 	}
                   10715:     }
                   10716:     $name=~s/^\s+//;
                   10717:     $name=~s/\s+$//;
                   10718:     $name=~s/\s+/ /g;
                   10719:     return $name;
                   10720: }
                   10721: 
1.84      www      10722: # ------------------------------------------------- Write to course preferences
                   10723: 
                   10724: sub writecoursepref {
                   10725:     my ($courseid,%prefs)=@_;
                   10726:     $courseid=~s/^\///;
                   10727:     $courseid=~s/\_/\//g;
                   10728:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10729:     my $chome=homeserver($cnum,$cdomain);
                   10730:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10731: 	return 'error: no such course';
                   10732:     }
                   10733:     my $cstring='';
1.800     albertel 10734:     foreach my $pref (keys(%prefs)) {
                   10735: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10736:     }
1.84      www      10737:     $cstring=~s/\&$//;
                   10738:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10739: }
                   10740: 
                   10741: # ---------------------------------------------------------- Make/modify course
                   10742: 
                   10743: sub createcourse {
1.741     raeburn  10744:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10745:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10746:     $url=&declutter($url);
                   10747:     my $cid='';
1.1028    raeburn  10748:     if ($context eq 'requestcourses') {
                   10749:         my $can_create = 0;
                   10750:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10751:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10752:22):             my $reload;
                   10753:22):             if (($callercontext eq 'auto') &&
                   10754:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10755:22):                 $reload = 'reload';
                   10756:22):             }
                   10757:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10758:                                   $context)) {
                   10759:                 $can_create = 1;
                   10760:             }
                   10761:         } else {
                   10762:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10763:                                            $category);
                   10764:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10765:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10766:                 if (@curr > 0) {
                   10767:                     my @options = qw(approval validate autolimit);
                   10768:                     my $optregex = join('|',@options);
                   10769:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10770:                         $can_create = 1;
                   10771:                     }
                   10772:                 }
                   10773:             }
                   10774:         }
                   10775:         if ($can_create) {
                   10776:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10777:                 unless (&allowed('ccc',$udom)) {
                   10778:                     return 'refused'; 
                   10779:                 }
1.1017    raeburn  10780:             }
                   10781:         } else {
                   10782:             return 'refused';
                   10783:         }
1.1028    raeburn  10784:     } elsif (!&allowed('ccc',$udom)) {
                   10785:         return 'refused';
1.84      www      10786:     }
1.1011    raeburn  10787: # --------------------------------------------------------------- Get Unique ID
                   10788:     my $uname;
                   10789:     if ($cnum =~ /^$match_courseid$/) {
                   10790:         my $chome=&homeserver($cnum,$udom,'true');
                   10791:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10792:             $uname = $cnum;
                   10793:         } else {
1.1038    raeburn  10794:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10795:         }
                   10796:     } else {
1.1038    raeburn  10797:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10798:     }
                   10799:     return $uname if ($uname =~ /^error/);
                   10800: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10801:     if (!defined($course_server)) {
                   10802:         if (defined(&domain($udom,'primary'))) {
                   10803:             $course_server = &domain($udom,'primary');
                   10804:         } else {
                   10805:             $course_server = $env{'user.home'}; 
                   10806:         }
                   10807:     }
                   10808:     my %host_servers =
                   10809:         &Apache::lonnet::get_servers($udom,'library');
                   10810:     unless ($host_servers{$course_server}) {
                   10811:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10812:     }
1.84      www      10813: # ------------------------------------------------------------- Make the course
                   10814:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10815:                       $course_server);
1.84      www      10816:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10817:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10818:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10819: 	return 'error: no such course';
                   10820:     }
1.271     www      10821: # ----------------------------------------------------------------- Course made
1.516     raeburn  10822: # log existence
1.1029    raeburn  10823:     my $now = time;
1.918     raeburn  10824:     my $newcourse = {
                   10825:                     $udom.'_'.$uname => {
1.921     raeburn  10826:                                      description => $description,
                   10827:                                      inst_code   => $inst_code,
                   10828:                                      owner       => $course_owner,
                   10829:                                      type        => $crstype,
1.1029    raeburn  10830:                                      creator     => $env{'user.name'}.':'.
                   10831:                                                     $env{'user.domain'},
                   10832:                                      created     => $now,
                   10833:                                      context     => $context,
1.918     raeburn  10834:                                                 },
                   10835:                     };
1.921     raeburn  10836:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10837: # set toplevel url
1.271     www      10838:     my $topurl=$url;
                   10839:     unless ($nonstandard) {
                   10840: # ------------------------------------------ For standard courses, make top url
                   10841:         my $mapurl=&clutter($url);
1.278     www      10842:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10843:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10844: <map>
                   10845: <resource id="1" type="start"></resource>
                   10846: <resource id="2" src="$mapurl"></resource>
                   10847: <resource id="3" type="finish"></resource>
                   10848: <link index="1" from="1" to="2"></link>
                   10849: <link index="2" from="2" to="3"></link>
                   10850: </map>
                   10851: ENDINITMAP
                   10852:         $topurl=&declutter(
1.638     albertel 10853:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10854:                           );
                   10855:     }
                   10856: # ----------------------------------------------------------- Write preferences
1.84      www      10857:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10858:                      ('description'              => $description,
                   10859:                       'url'                      => $topurl,
                   10860:                       'internal.creator'         => $env{'user.name'}.':'.
                   10861:                                                     $env{'user.domain'},
                   10862:                       'internal.created'         => $now,
                   10863:                       'internal.creationcontext' => $context)
                   10864:                     );
1.84      www      10865:     return '/'.$udom.'/'.$uname;
                   10866: }
                   10867: 
1.1011    raeburn  10868: # ------------------------------------------------------------------- Create ID
                   10869: sub generate_coursenum {
1.1038    raeburn  10870:     my ($udom,$crstype) = @_;
1.1011    raeburn  10871:     my $domdesc = &domain($udom);
                   10872:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10873:     my $first;
                   10874:     if ($crstype eq 'Community') {
                   10875:         $first = '0';
                   10876:     } else {
                   10877:         $first = int(1+rand(9)); 
                   10878:     } 
                   10879:     my $uname=$first.
1.1011    raeburn  10880:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10881:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10882:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10883: # ----------------------------------------------- Make sure that does not exist
                   10884:     my $uhome=&homeserver($uname,$udom,'true');
                   10885:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10886:         if ($crstype eq 'Community') {
                   10887:             $first = '0';
                   10888:         } else {
                   10889:             $first = int(1+rand(9));
                   10890:         }
                   10891:         $uname=$first.
1.1011    raeburn  10892:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10893:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10894:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10895:         $uhome=&homeserver($uname,$udom,'true');
                   10896:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10897:             return 'error: unable to generate unique course-ID';
                   10898:         }
                   10899:     }
                   10900:     return $uname;
                   10901: }
                   10902: 
1.813     albertel 10903: sub is_course {
1.1167    droeschl 10904:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10905:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10906:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10907:     my $uhome=&homeserver($cnum,$cdom);
                   10908:     my $iscourse;
                   10909:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10910:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10911:     } else {
                   10912:         my $hashid = $cdom.':'.$cnum;
                   10913:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10914:         unless (defined($cached)) {
                   10915:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10916:                                         $cnum,undef,undef,'.');
                   10917:             $iscourse = 0;
                   10918:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10919:                 $iscourse = 1;
                   10920:             }
                   10921:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10922:         }
                   10923:     }
                   10924:     return unless($iscourse);
1.1167    droeschl 10925:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10926: }
                   10927: 
1.1015    raeburn  10928: sub store_userdata {
                   10929:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10930:     my $result;
1.1016    raeburn  10931:     if ($datakey ne '') {
1.1013    raeburn  10932:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10933:             if ($udom eq '' || $uname eq '') {
                   10934:                 $udom = $env{'user.domain'};
                   10935:                 $uname = $env{'user.name'};
                   10936:             }
                   10937:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10938:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10939:                 $result = 'error: no_host';
                   10940:             } else {
1.1172.2.138  raeburn  10941:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10942:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10943: 
                   10944:                 my $namevalue='';
                   10945:                 foreach my $key (keys(%{$storehash})) {
                   10946:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10947:                 }
                   10948:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10949:                 unless ($namespace eq 'courserequests') {
                   10950:                     $datakey = &escape($datakey);
                   10951:                 }
1.1105    raeburn  10952:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10953:                                   $namevalue,$uhome);
1.1013    raeburn  10954:             }
                   10955:         } else {
                   10956:             $result = 'error: data to store was not a hash reference'; 
                   10957:         }
                   10958:     } else {
                   10959:         $result= 'error: invalid requestkey'; 
                   10960:     }
                   10961:     return $result;
                   10962: }
                   10963: 
1.21      www      10964: # ---------------------------------------------------------- Assign Custom Role
                   10965: 
                   10966: sub assigncustomrole {
1.957     raeburn  10967:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10968:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10969:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10970: }
                   10971: 
                   10972: # ----------------------------------------------------------------- Revoke Role
                   10973: 
                   10974: sub revokerole {
1.957     raeburn  10975:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10976:     my $now=time;
1.965     raeburn  10977:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10978: }
                   10979: 
                   10980: # ---------------------------------------------------------- Revoke Custom Role
                   10981: 
                   10982: sub revokecustomrole {
1.957     raeburn  10983:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10984:     my $now=time;
1.357     www      10985:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10986:            $deleteflag,$selfenroll,$context);
1.17      www      10987: }
                   10988: 
1.533     banghart 10989: # ------------------------------------------------------------ Disk usage
1.535     albertel 10990: sub diskusage {
1.955     raeburn  10991:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10992:     $directorypath =~ s/\/$//;
                   10993:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10994:                        .&escape($getpropath).':'.&escape($uname).':'
                   10995:                        .&escape($udom),homeserver($uname,$udom));
                   10996:     if ($listing eq 'unknown_cmd') {
                   10997:         if ($getpropath) {
                   10998:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10999:         }
                   11000:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11001:     }
1.514     albertel 11002:     return $listing;
1.512     banghart 11003: }
                   11004: 
1.566     banghart 11005: sub is_locked {
1.1096    raeburn  11006:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11007:     my @check;
                   11008:     my $is_locked;
1.1093    raeburn  11009:     push (@check,$file_name);
1.613     albertel 11010:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11011: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11012:     my ($tmp)=keys(%locked);
                   11013:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11014:     
1.566     banghart 11015:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11016:         $is_locked = 'false';
                   11017:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11018:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11019:                $is_locked = 'true';
1.1096    raeburn  11020:                if (ref($which) eq 'ARRAY') {
                   11021:                    push(@{$which},$entry);
                   11022:                } else {
                   11023:                    last;
                   11024:                }
1.745     raeburn  11025:            }
                   11026:        }
1.566     banghart 11027:     } else {
                   11028:         $is_locked = 'false';
                   11029:     }
1.1093    raeburn  11030:     return $is_locked;
1.566     banghart 11031: }
                   11032: 
1.759     albertel 11033: sub declutter_portfile {
                   11034:     my ($file) = @_;
1.833     albertel 11035:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11036:     return $file;
                   11037: }
                   11038: 
1.559     banghart 11039: # ------------------------------------------------------------- Mark as Read Only
                   11040: 
                   11041: sub mark_as_readonly {
                   11042:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11043:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11044:     my ($tmp)=keys(%current_permissions);
                   11045:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11046:     foreach my $file (@{$files}) {
1.759     albertel 11047: 	$file = &declutter_portfile($file);
1.561     banghart 11048:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11049:     }
1.613     albertel 11050:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11051:     return;
                   11052: }
                   11053: 
1.572     banghart 11054: # ------------------------------------------------------------Save Selected Files
                   11055: 
                   11056: sub save_selected_files {
                   11057:     my ($user, $path, @files) = @_;
                   11058:     my $filename = $user."savedfiles";
1.573     banghart 11059:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11060:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11061:     foreach my $file (@files) {
1.620     albertel 11062:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11063:     }
                   11064:     foreach my $file (@other_files) {
1.574     banghart 11065:         print (OUT $file."\n");
1.572     banghart 11066:     }
1.574     banghart 11067:     close (OUT);
1.572     banghart 11068:     return 'ok';
                   11069: }
                   11070: 
1.574     banghart 11071: sub clear_selected_files {
                   11072:     my ($user) = @_;
                   11073:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11074:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11075:     print (OUT undef);
                   11076:     close (OUT);
                   11077:     return ("ok");    
                   11078: }
                   11079: 
1.572     banghart 11080: sub files_in_path {
                   11081:     my ($user, $path) = @_;
                   11082:     my $filename = $user."savedfiles";
                   11083:     my %return_files;
1.1172.2.96  raeburn  11084:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11085:     while (my $line_in = <IN>) {
1.574     banghart 11086:         chomp ($line_in);
                   11087:         my @paths_and_file = split (m!/!, $line_in);
                   11088:         my $file_part = pop (@paths_and_file);
                   11089:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11090:         $path_part.='/';
                   11091:         my $path_and_file = $path_part.$file_part;
                   11092:         if ($path_part eq $path) {
                   11093:             $return_files{$file_part}= 'selected';
                   11094:         }
                   11095:     }
1.574     banghart 11096:     close (IN);
                   11097:     return (\%return_files);
1.572     banghart 11098: }
                   11099: 
                   11100: # called in portfolio select mode, to show files selected NOT in current directory
                   11101: sub files_not_in_path {
                   11102:     my ($user, $path) = @_;
                   11103:     my $filename = $user."savedfiles";
                   11104:     my @return_files;
                   11105:     my $path_part;
1.1172.2.96  raeburn  11106:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11107:     while (my $line = <IN>) {
1.572     banghart 11108:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11109:         my @paths_and_file = split(m|/|, $line);
                   11110:         my $file_part = pop(@paths_and_file);
                   11111:         chomp($file_part);
                   11112:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11113:         $path_part .= '/';
                   11114:         my $path_and_file = $path_part.$file_part;
                   11115:         if ($path_part ne $path) {
1.800     albertel 11116:             push(@return_files, ($path_and_file));
1.572     banghart 11117:         }
                   11118:     }
1.800     albertel 11119:     close(OUT);
1.574     banghart 11120:     return (@return_files);
1.572     banghart 11121: }
                   11122: 
1.745     raeburn  11123: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11124: 
1.745     raeburn  11125: sub get_portfile_permissions {
                   11126:     my ($domain,$user) = @_;
1.613     albertel 11127:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11128:     my ($tmp)=keys(%current_permissions);
                   11129:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11130:     return \%current_permissions;
                   11131: }
                   11132: 
                   11133: #---------------------------------------------Get portfolio file access controls
                   11134: 
1.749     raeburn  11135: sub get_access_controls {
1.745     raeburn  11136:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11137:     my %access;
                   11138:     my $real_file = $file;
                   11139:     $file =~ s/\.meta$//;
1.745     raeburn  11140:     if (defined($file)) {
1.749     raeburn  11141:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11142:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11143:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11144:             }
                   11145:         }
1.745     raeburn  11146:     } else {
1.749     raeburn  11147:         foreach my $key (keys(%{$current_permissions})) {
                   11148:             if ($key =~ /\0accesscontrol$/) {
                   11149:                 if (defined($group)) {
                   11150:                     if ($key !~ m-^\Q$group\E/-) {
                   11151:                         next;
                   11152:                     }
                   11153:                 }
                   11154:                 my ($fullpath) = split(/\0/,$key);
                   11155:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11156:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11157:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11158:                     }
                   11159:                 }
                   11160:             }
                   11161:         }
                   11162:     }
                   11163:     return %access;
                   11164: }
                   11165: 
                   11166: sub modify_access_controls {
                   11167:     my ($file_name,$changes,$domain,$user)=@_;
                   11168:     my ($outcome,$deloutcome);
                   11169:     my %store_permissions;
                   11170:     my %new_values;
                   11171:     my %new_control;
                   11172:     my %translation;
                   11173:     my @deletions = ();
                   11174:     my $now = time;
                   11175:     if (exists($$changes{'activate'})) {
                   11176:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11177:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11178:             my $numnew = scalar(@newitems);
                   11179:             for (my $i=0; $i<$numnew; $i++) {
                   11180:                 my $newkey = $newitems[$i];
                   11181:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11182:                 if ($newkey =~ /^\d+:/) { 
                   11183:                     $newkey =~ s/^(\d+)/$newid/;
                   11184:                     $translation{$1} = $newid;
                   11185:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11186:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11187:                     $translation{$1} = $newid;
                   11188:                 }
1.749     raeburn  11189:                 $new_values{$file_name."\0".$newkey} = 
                   11190:                                           $$changes{'activate'}{$newitems[$i]};
                   11191:                 $new_control{$newkey} = $now;
                   11192:             }
                   11193:         }
                   11194:     }
                   11195:     my %todelete;
                   11196:     my %changed_items;
                   11197:     foreach my $action ('delete','update') {
                   11198:         if (exists($$changes{$action})) {
                   11199:             if (ref($$changes{$action}) eq 'HASH') {
                   11200:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11201:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11202:                     if ($action eq 'delete') { 
                   11203:                         $todelete{$itemnum} = 1;
                   11204:                     } else {
                   11205:                         $changed_items{$itemnum} = $key;
                   11206:                     }
                   11207:                 }
1.745     raeburn  11208:             }
                   11209:         }
1.749     raeburn  11210:     }
                   11211:     # get lock on access controls for file.
                   11212:     my $lockhash = {
                   11213:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11214:                                                        ':'.$env{'user.domain'},
                   11215:                    }; 
                   11216:     my $tries = 0;
                   11217:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11218:    
1.1172.2.79  raeburn  11219:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11220:         $tries ++;
1.1172.2.79  raeburn  11221:         sleep(0.1);
1.749     raeburn  11222:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11223:     }
                   11224:     if ($gotlock eq 'ok') {
                   11225:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11226:         my ($tmp)=keys(%curr_permissions);
                   11227:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11228:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11229:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11230:             if (ref($curr_controls) eq 'HASH') {
                   11231:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11232:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11233:                     if (defined($todelete{$itemnum})) {
                   11234:                         push(@deletions,$file_name."\0".$control_item);
                   11235:                     } else {
                   11236:                         if (defined($changed_items{$itemnum})) {
                   11237:                             $new_control{$changed_items{$itemnum}} = $now;
                   11238:                             push(@deletions,$file_name."\0".$control_item);
                   11239:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11240:                         } else {
                   11241:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11242:                         }
                   11243:                     }
1.745     raeburn  11244:                 }
                   11245:             }
                   11246:         }
1.970     raeburn  11247:         my ($group);
                   11248:         if (&is_course($domain,$user)) {
                   11249:             ($group,my $file) = split(/\//,$file_name,2);
                   11250:         }
1.749     raeburn  11251:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11252:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11253:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11254:         #  remove lock
                   11255:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11256:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11257:         my $sqlresult =
1.970     raeburn  11258:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11259:                                     $group);
1.749     raeburn  11260:     } else {
                   11261:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11262:     }
1.749     raeburn  11263:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11264: }
                   11265: 
1.827     raeburn  11266: sub make_public_indefinitely {
                   11267:     my ($requrl) = @_;
                   11268:     my $now = time;
                   11269:     my $action = 'activate';
                   11270:     my $aclnum = 0;
                   11271:     if (&is_portfolio_url($requrl)) {
                   11272:         my (undef,$udom,$unum,$file_name,$group) =
                   11273:             &parse_portfolio_url($requrl);
                   11274:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11275:         my %access_controls = &get_access_controls($current_perms,
                   11276:                                                    $group,$file_name);
                   11277:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11278:             my ($num,$scope,$end,$start) = 
                   11279:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11280:             if ($scope eq 'public') {
                   11281:                 if ($start <= $now && $end == 0) {
                   11282:                     $action = 'none';
                   11283:                 } else {
                   11284:                     $action = 'update';
                   11285:                     $aclnum = $num;
                   11286:                 }
                   11287:                 last;
                   11288:             }
                   11289:         }
                   11290:         if ($action eq 'none') {
                   11291:              return 'ok';
                   11292:         } else {
                   11293:             my %changes;
                   11294:             my $newend = 0;
                   11295:             my $newstart = $now;
                   11296:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11297:             $changes{$action}{$newkey} = {
                   11298:                 type => 'public',
                   11299:                 time => {
                   11300:                     start => $newstart,
                   11301:                     end   => $newend,
                   11302:                 },
                   11303:             };
                   11304:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11305:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11306:             return $outcome;
                   11307:         }
                   11308:     } else {
                   11309:         return 'invalid';
                   11310:     }
                   11311: }
                   11312: 
1.745     raeburn  11313: #------------------------------------------------------Get Marked as Read Only
                   11314: 
                   11315: sub get_marked_as_readonly {
                   11316:     my ($domain,$user,$what,$group) = @_;
                   11317:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11318:     my @readonly_files;
1.629     banghart 11319:     my $cmp1=$what;
                   11320:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11321:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11322:         if (defined($group)) {
                   11323:             if ($file_name !~ m-^\Q$group\E/-) {
                   11324:                 next;
                   11325:             }
                   11326:         }
1.561     banghart 11327:         if (ref($value) eq "ARRAY"){
                   11328:             foreach my $stored_what (@{$value}) {
1.629     banghart 11329:                 my $cmp2=$stored_what;
1.759     albertel 11330:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11331:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11332:                 }
1.629     banghart 11333:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11334:                     push(@readonly_files, $file_name);
1.745     raeburn  11335:                     last;
1.563     banghart 11336:                 } elsif (!defined($what)) {
                   11337:                     push(@readonly_files, $file_name);
1.745     raeburn  11338:                     last;
1.561     banghart 11339:                 }
                   11340:             }
1.745     raeburn  11341:         }
1.561     banghart 11342:     }
                   11343:     return @readonly_files;
                   11344: }
1.577     banghart 11345: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11346: 
1.577     banghart 11347: sub get_marked_as_readonly_hash {
1.745     raeburn  11348:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11349:     my %readonly_files;
1.745     raeburn  11350:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11351:         if (defined($group)) {
                   11352:             if ($file_name !~ m-^\Q$group\E/-) {
                   11353:                 next;
                   11354:             }
                   11355:         }
1.577     banghart 11356:         if (ref($value) eq "ARRAY"){
                   11357:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11358:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11359:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11360:                         if ($lock_descriptor eq 'graded') {
                   11361:                             $readonly_files{$file_name} = 'graded';
                   11362:                         } elsif ($lock_descriptor eq 'handback') {
                   11363:                             $readonly_files{$file_name} = 'handback';
                   11364:                         } else {
                   11365:                             if (!exists($readonly_files{$file_name})) {
                   11366:                                 $readonly_files{$file_name} = 'locked';
                   11367:                             }
                   11368:                         }
1.745     raeburn  11369:                     }
1.750     banghart 11370:                 } 
1.577     banghart 11371:             }
                   11372:         } 
                   11373:     }
                   11374:     return %readonly_files;
                   11375: }
1.559     banghart 11376: # ------------------------------------------------------------ Unmark as Read Only
                   11377: 
                   11378: sub unmark_as_readonly {
1.629     banghart 11379:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11380:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11381:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11382:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11383:     my $symb_crs = $what;
                   11384:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11385:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11386:     my ($tmp)=keys(%current_permissions);
                   11387:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11388:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11389:     foreach my $file (@readonly_files) {
1.759     albertel 11390: 	my $clean_file = &declutter_portfile($file);
                   11391: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11392: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11393:         my @new_locks;
                   11394:         my @del_keys;
                   11395:         if (ref($current_locks) eq "ARRAY"){
                   11396:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11397:                 my $compare=$locker;
1.749     raeburn  11398:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11399:                     $compare=join('',@{$locker});
1.746     raeburn  11400:                     if ($compare ne $symb_crs) {
                   11401:                         push(@new_locks, $locker);
                   11402:                     }
1.563     banghart 11403:                 }
                   11404:             }
1.650     albertel 11405:             if (scalar(@new_locks) > 0) {
1.563     banghart 11406:                 $current_permissions{$file} = \@new_locks;
                   11407:             } else {
                   11408:                 push(@del_keys, $file);
1.613     albertel 11409:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11410:                 delete($current_permissions{$file});
1.563     banghart 11411:             }
                   11412:         }
1.561     banghart 11413:     }
1.613     albertel 11414:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11415:     return;
                   11416: }
1.512     banghart 11417: 
1.17      www      11418: # ------------------------------------------------------------ Directory lister
                   11419: 
                   11420: sub dirlist {
1.955     raeburn  11421:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11422:     $uri=~s/^\///;
                   11423:     $uri=~s/\/$//;
1.253     stredwic 11424:     my ($udom, $uname);
1.955     raeburn  11425:     if ($getuserdir) {
1.253     stredwic 11426:         $udom = $userdomain;
                   11427:         $uname = $username;
1.955     raeburn  11428:     } else {
                   11429:         (undef,$udom,$uname)=split(/\//,$uri);
                   11430:         if(defined($userdomain)) {
                   11431:             $udom = $userdomain;
                   11432:         }
                   11433:         if(defined($username)) {
                   11434:             $uname = $username;
                   11435:         }
1.253     stredwic 11436:     }
1.955     raeburn  11437:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11438: 
1.955     raeburn  11439:     $dirRoot = $perlvar{'lonDocRoot'};
                   11440:     if (defined($getpropath)) {
                   11441:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11442:         $dirRoot =~ s/\/$//;
1.955     raeburn  11443:     } elsif (defined($getuserdir)) {
                   11444:         my $subdir=$uname.'__';
                   11445:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11446:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11447:                    ."/$udom/$subdir/$uname";
                   11448:     } elsif (defined($alternateRoot)) {
                   11449:         $dirRoot = $alternateRoot;
1.751     banghart 11450:     }
1.253     stredwic 11451: 
                   11452:     if($udom) {
                   11453:         if($uname) {
1.1135    raeburn  11454:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11455:             if ($uhome eq 'no_host') {
                   11456:                 return ([],'no_host');
                   11457:             }
1.955     raeburn  11458:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11459:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11460:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11461:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11462:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11463:             } else {
                   11464:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11465:             }
1.605     matthew  11466:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11467:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11468:                 @listing_results = split(/:/,$listing);
                   11469:             } else {
                   11470:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11471:             }
1.1135    raeburn  11472:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11473:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11474:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11475:                 return ([],$listing);
                   11476:             } else {
                   11477:                 return (\@listing_results);
1.1135    raeburn  11478:             }
1.955     raeburn  11479:         } elsif(!$alternateRoot) {
1.1136    raeburn  11480:             my (%allusers,%listerror);
1.841     albertel 11481: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11482:  	    foreach my $tryserver (keys(%servers)) {
                   11483:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11484:                                   &escape($udom),$tryserver);
                   11485:                 if ($listing eq 'unknown_cmd') {
                   11486: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11487: 				      $udom, $tryserver);
                   11488:                 } else {
                   11489:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11490:                 }
1.841     albertel 11491: 		if ($listing eq 'unknown_cmd') {
                   11492: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11493: 				      $udom, $tryserver);
                   11494: 		    @listing_results = split(/:/,$listing);
                   11495: 		} else {
                   11496: 		    @listing_results =
                   11497: 			map { &unescape($_); } split(/:/,$listing);
                   11498: 		}
1.1136    raeburn  11499:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11500:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11501:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11502:                     $listerror{$tryserver} = $listing;
                   11503:                 } else {
1.841     albertel 11504: 		    foreach my $line (@listing_results) {
                   11505: 			my ($entry) = split(/&/,$line,2);
                   11506: 			$allusers{$entry} = 1;
                   11507: 		    }
                   11508: 		}
1.253     stredwic 11509:             }
1.1136    raeburn  11510:             my @alluserslist=();
1.800     albertel 11511:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11512:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11513:             }
1.1172.2.80  raeburn  11514:             if (!%listerror) {
                   11515:                 # no errors
                   11516:                 return (\@alluserslist);
                   11517:             } elsif (scalar(keys(%servers)) == 1) {
                   11518:                 # one library server, one error
                   11519:                 my ($key) = keys(%listerror);
                   11520:                 return (\@alluserslist, $listerror{$key});
                   11521:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11522:                 # con_lost indicates that we might miss data from at least one
                   11523:                 # library server
                   11524:                 return (\@alluserslist, 'con_lost');
                   11525:             } else {
                   11526:                 # multiple library servers and no con_lost -> data should be
                   11527:                 # complete.
                   11528:                 return (\@alluserslist);
                   11529:             }
                   11530: 
1.253     stredwic 11531:         } else {
1.1136    raeburn  11532:             return ([],'missing username');
1.253     stredwic 11533:         }
1.955     raeburn  11534:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11535:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11536:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11537:         return (\@all_domains);
1.955     raeburn  11538:     } else {
1.1136    raeburn  11539:         return ([],'missing domain');
1.275     stredwic 11540:     }
                   11541: }
                   11542: 
                   11543: # --------------------------------------------- GetFileTimestamp
                   11544: # This function utilizes dirlist and returns the date stamp for
                   11545: # when it was last modified.  It will also return an error of -1
                   11546: # if an error occurs
                   11547: 
                   11548: sub GetFileTimestamp {
1.955     raeburn  11549:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11550:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11551:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11552:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11553:                                     undef,$getuserdir);
                   11554:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11555:         return -1;
                   11556:     }
                   11557:     if (ref($fileref) eq 'ARRAY') {
                   11558:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11559:         # @stats contains first the filename, then the stat output
                   11560:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11561:     } else {
                   11562:         return -1;
1.253     stredwic 11563:     }
1.26      www      11564: }
                   11565: 
1.712     albertel 11566: sub stat_file {
                   11567:     my ($uri) = @_;
1.787     albertel 11568:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11569: 
1.955     raeburn  11570:     my ($udom,$uname,$file);
1.712     albertel 11571:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11572: 	($udom,$uname,$file) =
1.811     albertel 11573: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11574: 	$file = 'userfiles/'.$file;
                   11575:     }
                   11576:     if ($uri =~ m-^/res/-) {
                   11577: 	($udom,$uname) = 
1.807     albertel 11578: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11579: 	$file = $uri;
                   11580:     }
                   11581: 
                   11582:     if (!$udom || !$uname || !$file) {
                   11583: 	# unable to handle the uri
                   11584: 	return ();
                   11585:     }
1.956     raeburn  11586:     my $getpropath;
                   11587:     if ($file =~ /^userfiles\//) {
                   11588:         $getpropath = 1;
                   11589:     }
1.1136    raeburn  11590:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11591:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11592:         return ();
                   11593:     } else {
                   11594:         if (ref($listref) eq 'ARRAY') {
                   11595:             my @stats = split('&',$listref->[0]);
                   11596: 	    shift(@stats); #filename is first
                   11597: 	    return @stats;
                   11598:         }
1.712     albertel 11599:     }
                   11600:     return ();
                   11601: }
                   11602: 
1.26      www      11603: # -------------------------------------------------------- Value of a Condition
                   11604: 
1.713     albertel 11605: # gets the value of a specific preevaluated condition
                   11606: #    stored in the string  $env{user.state.<cid>}
                   11607: # or looks up a condition reference in the bighash and if if hasn't
                   11608: # already been evaluated recurses into docondval to get the value of
                   11609: # the condition, then memoizing it to 
                   11610: #   $env{user.state.<cid>.<condition>}
1.40      www      11611: sub directcondval {
                   11612:     my $number=shift;
1.620     albertel 11613:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11614: 	&Apache::lonuserstate::evalstate();
                   11615:     }
1.713     albertel 11616:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11617: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11618:     } elsif ($number =~ /^_/) {
                   11619: 	my $sub_condition;
                   11620: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11621: 		&GDBM_READER(),0640)) {
                   11622: 	    $sub_condition=$bighash{'conditions'.$number};
                   11623: 	    untie(%bighash);
                   11624: 	}
                   11625: 	my $value = &docondval($sub_condition);
1.949     raeburn  11626: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11627: 	return $value;
                   11628:     }
1.620     albertel 11629:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11630:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11631:     } else {
                   11632:        return 2;
                   11633:     }
                   11634: }
                   11635: 
1.713     albertel 11636: # get the collection of conditions for this resource
1.26      www      11637: sub condval {
                   11638:     my $condidx=shift;
1.54      www      11639:     my $allpathcond='';
1.713     albertel 11640:     foreach my $cond (split(/\|/,$condidx)) {
                   11641: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11642: 	    $allpathcond.=
                   11643: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11644: 	}
1.191     harris41 11645:     }
1.54      www      11646:     $allpathcond=~s/\|$//;
1.713     albertel 11647:     return &docondval($allpathcond);
                   11648: }
                   11649: 
                   11650: #evaluates an expression of conditions
                   11651: sub docondval {
                   11652:     my ($allpathcond) = @_;
                   11653:     my $result=0;
                   11654:     if ($env{'request.course.id'}
                   11655: 	&& defined($allpathcond)) {
                   11656: 	my $operand='|';
                   11657: 	my @stack;
                   11658: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11659: 	    if ($chunk eq '(') {
                   11660: 		push @stack,($operand,$result);
                   11661: 	    } elsif ($chunk eq ')') {
                   11662: 		my $before=pop @stack;
                   11663: 		if (pop @stack eq '&') {
                   11664: 		    $result=$result>$before?$before:$result;
                   11665: 		} else {
                   11666: 		    $result=$result>$before?$result:$before;
                   11667: 		}
                   11668: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11669: 		$operand=$chunk;
                   11670: 	    } else {
                   11671: 		my $new=directcondval($chunk);
                   11672: 		if ($operand eq '&') {
                   11673: 		    $result=$result>$new?$new:$result;
                   11674: 		} else {
                   11675: 		    $result=$result>$new?$result:$new;
                   11676: 		}
                   11677: 	    }
                   11678: 	}
1.26      www      11679:     }
                   11680:     return $result;
1.421     albertel 11681: }
                   11682: 
                   11683: # ---------------------------------------------------- Devalidate courseresdata
                   11684: 
                   11685: sub devalidatecourseresdata {
                   11686:     my ($coursenum,$coursedomain)=@_;
                   11687:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11688:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11689: }
                   11690: 
1.763     www      11691: 
1.200     www      11692: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11693: #
                   11694: #  Parameters:
                   11695: #      $coursenum    - Number of the course.
                   11696: #      $coursedomain - Domain at which the course was created.
                   11697: #  Returns:
                   11698: #     A hash of the course parameters along (I think) with timestamps
                   11699: #     and version info.
1.877     foxr     11700: 
1.624     albertel 11701: sub get_courseresdata {
                   11702:     my ($coursenum,$coursedomain)=@_;
1.200     www      11703:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11704:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11705:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11706:     my %dumpreply;
1.417     albertel 11707:     unless (defined($cached)) {
1.624     albertel 11708: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11709: 	$result=\%dumpreply;
1.251     albertel 11710: 	my ($tmp) = keys(%dumpreply);
                   11711: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11712: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11713: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11714: 	    return $tmp;
1.416     albertel 11715: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11716: 	    $result=undef;
1.599     albertel 11717: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11718: 	}
                   11719:     }
1.624     albertel 11720:     return $result;
                   11721: }
                   11722: 
1.633     albertel 11723: sub devalidateuserresdata {
                   11724:     my ($uname,$udom)=@_;
                   11725:     my $hashid="$udom:$uname";
                   11726:     &devalidate_cache_new('userres',$hashid);
                   11727: }
                   11728: 
1.624     albertel 11729: sub get_userresdata {
                   11730:     my ($uname,$udom)=@_;
                   11731:     #most student don\'t have any data set, check if there is some data
                   11732:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11733: 
                   11734:     my $hashid="$udom:$uname";
                   11735:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11736:     if (!defined($cached)) {
                   11737: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11738: 	$result=\%resourcedata;
                   11739: 	&do_cache_new('userres',$hashid,$result,600);
                   11740:     }
                   11741:     my ($tmp)=keys(%$result);
                   11742:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11743: 	return $result;
                   11744:     }
                   11745:     #error 2 occurs when the .db doesn't exist
                   11746:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11747:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11748: 	    &logthis("<font color=\"blue\">WARNING:".
                   11749: 		     " Trying to get resource data for ".
                   11750: 		     $uname." at ".$udom.": ".
                   11751: 		     $tmp."</font>");
                   11752:         }
1.624     albertel 11753:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11754: 	#&EXT_cache_set($udom,$uname);
                   11755: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11756: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11757:     }
                   11758:     return $tmp;
                   11759: }
1.879     foxr     11760: #----------------------------------------------- resdata - return resource data
                   11761: #  Purpose:
                   11762: #    Return resource data for either users or for a course.
                   11763: #  Parameters:
                   11764: #     $name      - Course/user name.
                   11765: #     $domain    - Name of the domain the user/course is registered on.
                   11766: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11767: #     @which     - Array of names of resources desired.
                   11768: #  Returns:
                   11769: #     The value of the first reasource in @which that is found in the
                   11770: #     resource hash.
                   11771: #  Exceptional Conditions:
                   11772: #     If the $type passed in is not valid (not the string 'course' or 
                   11773: #     'user', an undefined  reference is returned.
                   11774: #     If none of the resources are found, an undef is returned
1.624     albertel 11775: sub resdata {
                   11776:     my ($name,$domain,$type,@which)=@_;
                   11777:     my $result;
                   11778:     if ($type eq 'course') {
                   11779: 	$result=&get_courseresdata($name,$domain);
                   11780:     } elsif ($type eq 'user') {
                   11781: 	$result=&get_userresdata($name,$domain);
                   11782:     }
                   11783:     if (!ref($result)) { return $result; }    
1.251     albertel 11784:     foreach my $item (@which) {
1.927     albertel 11785: 	if (defined($result->{$item->[0]})) {
                   11786: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11787: 	}
1.250     albertel 11788:     }
1.291     albertel 11789:     return undef;
1.200     www      11790: }
                   11791: 
1.1172.2.146.  .1(raebu 11792:22): sub get_domain_lti {
                   11793:22):     my ($cdom,$context) = @_;
          .4(raebu 11794:22):     my ($name,$cachename,%lti);
          .1(raebu 11795:22):     if ($context eq 'consumer') {
                   11796:22):         $name = 'ltitools';
                   11797:22):     } elsif ($context eq 'provider') {
                   11798:22):         $name = 'lti';
          .4(raebu 11799:22):     } elsif ($context eq 'linkprot') {
                   11800:22):         $name = 'ltisec';
          .1(raebu 11801:22):     } else {
                   11802:22):         return %lti;
                   11803:22):     }
          .4(raebu 11804:22): 
                   11805:22):     if ($context eq 'linkprot') {
                   11806:22):         $cachename = $context;
                   11807:22):     } else {
                   11808:22):         $cachename = $name;
                   11809:22):     }
                   11810:22): 
                   11811:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11812:22):     if (defined($cached)) {
                   11813:22):         if (ref($result) eq 'HASH') {
                   11814:22):             %lti = %{$result};
                   11815:22):         }
                   11816:22):     } else {
                   11817:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11818:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11819:22):             if ($context eq 'linkprot') {
                   11820:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11821:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11822:22):                 }
                   11823:22):             } else {
                   11824:22):                 %lti = %{$domconfig{$name}};
                   11825:22):             }
                   11826:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11827:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11828:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11829:22):                     foreach my $id (keys(%lti)) {
                   11830:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11831:22):                             foreach my $item ('key','secret') {
                   11832:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11833:22):                             }
          .1(raebu 11834:22):                         }
                   11835:22):                     }
                   11836:22):                 }
                   11837:22):             }
                   11838:22):         }
                   11839:22):         my $cachetime = 24*60*60;
          .4(raebu 11840:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11841:22):     }
                   11842:22):     return %lti;
                   11843:22): }
                   11844:22): 
                   11845:22): sub get_course_lti {
                   11846:22):     my ($cnum,$cdom) = @_;
                   11847:22):     my $hashid=$cdom.'_'.$cnum;
                   11848:22):     my %courselti;
                   11849:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11850:22):     if (defined($cached)) {
                   11851:22):         if (ref($result) eq 'HASH') {
                   11852:22):             %courselti = %{$result};
                   11853:22):         }
                   11854:22):     } else {
                   11855:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11856:22):         my $cachetime = 24*60*60;
                   11857:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11858:22):     }
                   11859:22):     return %courselti;
                   11860:22): }
                   11861:22): 
          .3(raebu 11862:22): sub courselti_itemid {
                   11863:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11864:22):     my ($chome,$itemid);
                   11865:22):     $chome = &homeserver($cnum,$cdom);
                   11866:22):     return if ($chome eq 'no_host');
                   11867:22):     if (ref($params) eq 'HASH') {
                   11868:22):         my $items = &freeze_escape($params);
                   11869:22):         my $rep;
                   11870:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11871:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11872:22):         } else {
                   11873:22):             my $escurl = &escape($url);
                   11874:22):             my $escmethod = &escape($method);
                   11875:22):             my $items = &freeze_escape($params);
                   11876:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11877:22):         }
                   11878:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11879:22):                 ($rep eq 'unknown_cmd')) {
                   11880:22):             $itemid = $rep;
                   11881:22):         }
                   11882:22):     }
                   11883:22):     return $itemid;
                   11884:22): }
                   11885:22): 
                   11886:22): sub domainlti_itemid {
                   11887:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11888:22):     my ($primary_id,$itemid);
                   11889:22):     $primary_id = &domain($cdom,'primary');
                   11890:22):     return if ($primary_id eq '');
                   11891:22):     if (ref($params) eq 'HASH') {
                   11892:22):         my $items = &freeze_escape($params);
                   11893:22):         my $rep;
                   11894:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11895:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11896:22):         } else {
                   11897:22):             my $cnum = '';
                   11898:22):             my $escurl = &escape($url);
                   11899:22):             my $escmethod = &escape($method);
                   11900:22):             my $items = &freeze_escape($params);
                   11901:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11902:22):         }
                   11903:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11904:22):                 ($rep eq 'unknown_cmd')) {
                   11905:22):             $itemid = $rep;
                   11906:22):         }
                   11907:22):     }
                   11908:22):     return $itemid;
                   11909:22): }
                   11910:22): 
1.1172.2.31  raeburn  11911: sub get_numsuppfiles {
                   11912:     my ($cnum,$cdom,$ignorecache)=@_;
                   11913:     my $hashid=$cnum.':'.$cdom;
                   11914:     my ($suppcount,$cached);
                   11915:     unless ($ignorecache) {
                   11916:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11917:     }
                   11918:     unless (defined($cached)) {
                   11919:         my $chome=&homeserver($cnum,$cdom);
                   11920:         unless ($chome eq 'no_host') {
                   11921:             ($suppcount,my $errors) = (0,0);
                   11922:             my $suppmap = 'supplemental.sequence';
                   11923:             ($suppcount,$errors) =
                   11924:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11925:         }
                   11926:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11927:     }
                   11928:     return $suppcount;
                   11929: }
                   11930: 
1.379     matthew  11931: #
                   11932: # EXT resource caching routines
                   11933: #
                   11934: 
1.1172.2.146.  .1(raebu 11935:22): {
                   11936:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11937:22): #
                   11938:22): # The course for which we cache
                   11939:22): my $cachedmapkey='';
                   11940:22): # The cached recursive maps for this course
                   11941:22): my %cachedmaps=();
                   11942:22): # When this was last done
                   11943:22): my $cachedmaptime='';
                   11944:22): 
1.379     matthew  11945: sub clear_EXT_cache_status {
1.383     albertel 11946:     &delenv('cache.EXT.');
1.379     matthew  11947: }
                   11948: 
                   11949: sub EXT_cache_status {
                   11950:     my ($target_domain,$target_user) = @_;
1.383     albertel 11951:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11952:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11953:         # We know already the user has no data
                   11954:         return 1;
                   11955:     } else {
                   11956:         return 0;
                   11957:     }
                   11958: }
                   11959: 
                   11960: sub EXT_cache_set {
                   11961:     my ($target_domain,$target_user) = @_;
1.383     albertel 11962:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11963:     #&appenv({$cachename => time});
1.379     matthew  11964: }
                   11965: 
1.28      www      11966: # --------------------------------------------------------- Value of a Variable
1.58      www      11967: sub EXT {
1.715     albertel 11968: 
1.1172.2.28  raeburn  11969:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11970:     unless ($varname) { return ''; }
1.218     albertel 11971:     #get real user name/domain, courseid and symb
                   11972:     my $courseid;
1.359     albertel 11973:     my $publicuser;
1.427     www      11974:     if ($symbparm) {
                   11975: 	$symbparm=&get_symb_from_alias($symbparm);
                   11976:     }
1.218     albertel 11977:     if (!($uname && $udom)) {
1.790     albertel 11978:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11979:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11980:     } else {
1.620     albertel 11981: 	$courseid=$env{'request.course.id'};
1.218     albertel 11982:     }
1.48      www      11983:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11984:     my $rest;
1.320     albertel 11985:     if (defined($therest[0])) {
1.48      www      11986:        $rest=join('.',@therest);
                   11987:     } else {
                   11988:        $rest='';
                   11989:     }
1.320     albertel 11990: 
1.57      www      11991:     my $qualifierrest=$qualifier;
                   11992:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11993:     my $spacequalifierrest=$space;
                   11994:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11995:     if ($realm eq 'user') {
1.48      www      11996: # --------------------------------------------------------------- user.resource
                   11997: 	if ($space eq 'resource') {
1.651     albertel 11998: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11999: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12000: 		 &&
1.1172.2.142  raeburn  12001: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12002: 		# if we are in the middle of processing the resource the
                   12003: 		# get the value we are planning on committing
                   12004:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12005:                     return $Apache::lonhomework::results{$qualifierrest};
                   12006:                 } else {
                   12007:                     return $Apache::lonhomework::history{$qualifierrest};
                   12008:                 }
1.335     albertel 12009: 	    } else {
1.359     albertel 12010: 		my %restored;
1.620     albertel 12011: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12012: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12013: 		} else {
                   12014: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12015: 		}
1.335     albertel 12016: 		return $restored{$qualifierrest};
                   12017: 	    }
1.48      www      12018: # ----------------------------------------------------------------- user.access
                   12019:         } elsif ($space eq 'access') {
1.218     albertel 12020: 	    # FIXME - not supporting calls for a specific user
1.48      www      12021:             return &allowed($qualifier,$rest);
                   12022: # ------------------------------------------ user.preferences, user.environment
                   12023:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12024: 	    if (($uname eq $env{'user.name'}) &&
                   12025: 		($udom eq $env{'user.domain'})) {
                   12026: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12027: 	    } else {
1.359     albertel 12028: 		my %returnhash;
                   12029: 		if (!$publicuser) {
                   12030: 		    %returnhash=&userenvironment($udom,$uname,
                   12031: 						 $qualifierrest);
                   12032: 		}
1.218     albertel 12033: 		return $returnhash{$qualifierrest};
                   12034: 	    }
1.48      www      12035: # ----------------------------------------------------------------- user.course
                   12036:         } elsif ($space eq 'course') {
1.218     albertel 12037: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12038:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12039: # ------------------------------------------------------------------- user.role
                   12040:         } elsif ($space eq 'role') {
1.218     albertel 12041: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12042:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12043:             if ($qualifier eq 'value') {
                   12044: 		return $role;
                   12045:             } elsif ($qualifier eq 'extent') {
                   12046:                 return $where;
                   12047:             }
                   12048: # ----------------------------------------------------------------- user.domain
                   12049:         } elsif ($space eq 'domain') {
1.218     albertel 12050:             return $udom;
1.48      www      12051: # ------------------------------------------------------------------- user.name
                   12052:         } elsif ($space eq 'name') {
1.218     albertel 12053:             return $uname;
1.48      www      12054: # ---------------------------------------------------- Any other user namespace
1.29      www      12055:         } else {
1.359     albertel 12056: 	    my %reply;
                   12057: 	    if (!$publicuser) {
                   12058: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12059: 	    }
                   12060: 	    return $reply{$qualifierrest};
1.48      www      12061:         }
1.236     www      12062:     } elsif ($realm eq 'query') {
                   12063: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12064:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12065: 						[$spacequalifierrest]);
1.620     albertel 12066: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12067:    } elsif ($realm eq 'request') {
1.48      www      12068: # ------------------------------------------------------------- request.browser
                   12069:         if ($space eq 'browser') {
1.1145    bisitz   12070:             return $env{'browser.'.$qualifier};
1.57      www      12071: # ------------------------------------------------------------ request.filename
                   12072:         } else {
1.620     albertel 12073:             return $env{'request.'.$spacequalifierrest};
1.29      www      12074:         }
1.28      www      12075:     } elsif ($realm eq 'course') {
1.48      www      12076: # ---------------------------------------------------------- course.description
1.620     albertel 12077:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12078:     } elsif ($realm eq 'resource') {
1.165     www      12079: 
1.620     albertel 12080: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12081: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12082: 	}
1.693     albertel 12083: 
1.1172.2.30  raeburn  12084:         if ($qualifier eq '') {
                   12085: 	    if ($space eq 'title') {
                   12086: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12087: 	        return &gettitle($symbparm);
                   12088: 	    }
1.693     albertel 12089: 	
1.1172.2.30  raeburn  12090: 	    if ($space eq 'map') {
                   12091: 	        my ($map) = &decode_symb($symbparm);
                   12092: 	        return &symbread($map);
                   12093: 	    }
                   12094:             if ($space eq 'maptitle') {
                   12095:                 my ($map) = &decode_symb($symbparm);
                   12096:                 return &gettitle($map);
                   12097:             }
                   12098: 	    if ($space eq 'filename') {
                   12099: 	        if ($symbparm) {
                   12100: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12101: 	        }
                   12102: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12103: 	    }
1.1172.2.30  raeburn  12104: 
                   12105:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12106:                 if ($space eq 'visibleparts') {
                   12107:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12108:                     my $item;
                   12109:                     if (ref($navmap)) {
                   12110:                         my $res = $navmap->getBySymb($symbparm);
                   12111:                         my $parts = $res->parts();
                   12112:                         if (ref($parts) eq 'ARRAY') {
                   12113:                             $item = join(',',@{$parts});
                   12114:                         }
                   12115:                         undef($navmap);
                   12116:                     }
                   12117:                     return $item;
                   12118:                 }
                   12119:             }
                   12120:         }
1.693     albertel 12121: 
                   12122: 	my ($section, $group, @groups);
1.593     albertel 12123: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12124:         if (($courseid eq '') && ($cid)) {
                   12125:             $courseid = $cid;
                   12126:         }
                   12127: 	if (($symbparm && $courseid) && 
                   12128: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12129: 
1.218     albertel 12130: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12131: 
1.60      www      12132: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12133: 	    my $symbp=$symbparm;
1.735     albertel 12134: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12135: 
                   12136: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12137: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12138: 
1.620     albertel 12139: 	    if (($env{'user.name'} eq $uname) &&
                   12140: 		($env{'user.domain'} eq $udom)) {
                   12141: 		$section=$env{'request.course.sec'};
1.733     raeburn  12142:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12143:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12144: 	    } else {
1.539     albertel 12145: 		if (! defined($usection)) {
1.551     albertel 12146: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12147: 		} else {
                   12148: 		    $section = $usection;
                   12149: 		}
1.733     raeburn  12150:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12151: 	    }
                   12152: 
                   12153: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12154: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12155: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12156: 
1.593     albertel 12157: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12158: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12159: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12160: 
1.60      www      12161: # ----------------------------------------------------------- first, check user
1.624     albertel 12162: 
                   12163: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12164: 				       ([$courselevelr,'resource'],
                   12165: 					[$courselevelm,'map'     ],
                   12166: 					[$courselevel, 'course'  ]));
1.931     albertel 12167: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12168: 
1.594     albertel 12169: # ------------------------------------------------ second, check some of course
1.684     raeburn  12170:             my $coursereply;
1.691     raeburn  12171:             if (@groups > 0) {
                   12172:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12173:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12174:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12175:             }
1.96      www      12176: 
1.684     raeburn  12177: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12178: 				  $env{'course.'.$courseid.'.domain'},
                   12179: 				  'course',
                   12180: 				  ([$seclevelr,   'resource'],
                   12181: 				   [$seclevelm,   'map'     ],
                   12182: 				   [$seclevel,    'course'  ],
                   12183: 				   [$courselevelr,'resource']));
                   12184: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12185: 
1.60      www      12186: # ------------------------------------------------------ third, check map parms
1.218     albertel 12187: 	    my %parmhash=();
                   12188: 	    my $thisparm='';
                   12189: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12190: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12191: 		    &GDBM_READER(),0640)) {
1.218     albertel 12192: 		$thisparm=$parmhash{$symbparm};
                   12193: 		untie(%parmhash);
                   12194: 	    }
1.927     albertel 12195: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12196: 	}
1.594     albertel 12197: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12198: 
1.218     albertel 12199: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12200: 	my $filename;
                   12201: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12202: 	if ($symbparm) {
1.409     www      12203: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12204: 	} else {
1.620     albertel 12205: 	    $filename=$env{'request.filename'};
1.282     albertel 12206: 	}
                   12207: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12208: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12209: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12210: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12211: 
1.927     albertel 12212: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12213: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12214: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12215: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12216: 				     $env{'course.'.$courseid.'.domain'},
                   12217: 				     'course',
1.927     albertel 12218: 				     ([$courselevelm,'map'   ],
                   12219: 				      [$courselevel, 'course']));
                   12220: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12221: 	}
1.145     www      12222: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12223: 	unless ($space eq '0') {
1.336     albertel 12224: 	    my @parts=split(/_/,$space);
                   12225: 	    my $id=pop(@parts);
                   12226: 	    my $part=join('_',@parts);
                   12227: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12228: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12229: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12230: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12231: 	}
1.395     albertel 12232: 	if ($recurse) { return undef; }
                   12233: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12234: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12235: # ---------------------------------------------------- Any other user namespace
                   12236:     } elsif ($realm eq 'environment') {
                   12237: # ----------------------------------------------------------------- environment
1.620     albertel 12238: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12239: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12240: 	} else {
1.770     albertel 12241: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12242: 		return '';
                   12243: 	    }
1.219     albertel 12244: 	    my %returnhash=&userenvironment($udom,$uname,
                   12245: 					    $spacequalifierrest);
                   12246: 	    return $returnhash{$spacequalifierrest};
                   12247: 	}
1.28      www      12248:     } elsif ($realm eq 'system') {
1.48      www      12249: # ----------------------------------------------------------------- system.time
                   12250: 	if ($space eq 'time') {
                   12251: 	    return time;
                   12252:         }
1.696     albertel 12253:     } elsif ($realm eq 'server') {
                   12254: # ----------------------------------------------------------------- system.time
                   12255: 	if ($space eq 'name') {
                   12256: 	    return $ENV{'SERVER_NAME'};
                   12257:         }
1.1172.2.146.  .1(raebu 12258:22):     } elsif ($realm eq 'client') {
                   12259:22):         if ($space eq 'remote_addr') {
                   12260:22):             return &get_requestor_ip();
                   12261:22):         }
1.28      www      12262:     }
1.48      www      12263:     return '';
1.61      www      12264: }
                   12265: 
1.927     albertel 12266: sub get_reply {
                   12267:     my ($reply_value) = @_;
1.940     raeburn  12268:     if (ref($reply_value) eq 'ARRAY') {
                   12269:         if (wantarray) {
                   12270: 	    return @$reply_value;
                   12271:         }
                   12272:         return $reply_value->[0];
                   12273:     } else {
                   12274:         return $reply_value;
1.927     albertel 12275:     }
                   12276: }
                   12277: 
1.691     raeburn  12278: sub check_group_parms {
                   12279:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12280:     my @groupitems = ();
                   12281:     my $resultitem;
1.927     albertel 12282:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12283:     foreach my $group (@{$groups}) {
                   12284:         foreach my $level (@levels) {
1.927     albertel 12285:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12286:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12287:         }
                   12288:     }
                   12289:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12290:                             $env{'course.'.$courseid.'.domain'},
                   12291:                                      'course',@groupitems);
                   12292:     return $coursereply;
                   12293: }
                   12294: 
1.1172.2.146.  .1(raebu 12295:22): sub get_map_hierarchy {
                   12296:22):     my ($mapname,$courseid) = @_;
                   12297:22):     my @recurseup = ();
                   12298:22):     if ($mapname) {
                   12299:22):         if (($cachedmapkey eq $courseid) &&
                   12300:22):             (abs($cachedmaptime-time)<5)) {
                   12301:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12302:22):                 return @{$cachedmaps{$mapname}};
                   12303:22):             }
                   12304:22):         }
                   12305:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12306:22):         if (ref($navmap)) {
                   12307:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12308:22):             undef($navmap);
                   12309:22):             $cachedmaps{$mapname} = \@recurseup;
                   12310:22):             $cachedmaptime=time;
                   12311:22):             $cachedmapkey=$courseid;
                   12312:22):         }
                   12313:22):     }
                   12314:22):     return @recurseup;
                   12315:22): }
                   12316:22): 
          .2(raebu 12317:22): }
          .1(raebu 12318:22): 
1.691     raeburn  12319: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12320:     my ($courseid,@groups) = @_;
                   12321:     @groups = sort(@groups);
1.691     raeburn  12322:     return @groups;
                   12323: }
                   12324: 
1.395     albertel 12325: sub packages_tab_default {
                   12326:     my ($uri,$varname)=@_;
                   12327:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12328: 
                   12329:     my (@extension,@specifics,$do_default);
                   12330:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12331: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12332: 	if ($pack_type eq 'default') {
                   12333: 	    $do_default=1;
                   12334: 	} elsif ($pack_type eq 'extension') {
                   12335: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12336: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12337: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12338: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12339: 	}
                   12340:     }
                   12341:     # first look for a package that matches the requested part id
                   12342:     foreach my $package (@specifics) {
                   12343: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12344: 	next if ($pack_part ne $part);
                   12345: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12346: 	    return $packagetab{"$pack_type&$name&default"};
                   12347: 	}
                   12348:     }
                   12349:     # look for any possible matching non extension_ package
                   12350:     foreach my $package (@specifics) {
                   12351: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12352: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12353: 	    return $packagetab{"$pack_type&$name&default"};
                   12354: 	}
1.585     albertel 12355: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12356: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12357: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12358: 	}
                   12359:     }
1.738     albertel 12360:     # look for any posible extension_ match
                   12361:     foreach my $package (@extension) {
                   12362: 	my ($package,$pack_type)=@{$package};
                   12363: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12364: 	    return $packagetab{"$pack_type&$name&default"};
                   12365: 	}
                   12366: 	if (defined($packagetab{$package."&$name&default"})) {
                   12367: 	    return $packagetab{$package."&$name&default"};
                   12368: 	}
                   12369:     }
                   12370:     # look for a global default setting
                   12371:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12372: 	return $packagetab{"default&$name&default"};
                   12373:     }
1.395     albertel 12374:     return undef;
                   12375: }
                   12376: 
1.334     albertel 12377: sub add_prefix_and_part {
                   12378:     my ($prefix,$part)=@_;
                   12379:     my $keyroot;
                   12380:     if (defined($prefix) && $prefix !~ /^__/) {
                   12381: 	# prefix that has a part already
                   12382: 	$keyroot=$prefix;
                   12383:     } elsif (defined($prefix)) {
                   12384: 	# prefix that is missing a part
                   12385: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12386:     } else {
                   12387: 	# no prefix at all
                   12388: 	if (defined($part)) { $keyroot='_'.$part; }
                   12389:     }
                   12390:     return $keyroot;
                   12391: }
                   12392: 
1.71      www      12393: # ---------------------------------------------------------------- Get metadata
                   12394: 
1.599     albertel 12395: my %metaentry;
1.1070    www      12396: my %importedpartids;
1.1172.2.99  raeburn  12397: my %importedrespids;
1.71      www      12398: sub metadata {
1.176     www      12399:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12400:     $uri=&declutter($uri);
1.288     albertel 12401:     # if it is a non metadata possible uri return quickly
1.529     albertel 12402:     if (($uri eq '') || 
                   12403: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12404:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12405:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12406: 	return undef;
                   12407:     }
1.1172.2.49  raeburn  12408:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12409: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12410: 	return undef;
1.288     albertel 12411:     }
1.73      www      12412:     my $filename=$uri;
                   12413:     $uri=~s/\.meta$//;
1.172     www      12414: #
                   12415: # Is the metadata already cached?
1.177     www      12416: # Look at timestamp of caching
1.172     www      12417: # Everything is cached by the main uri, libraries are never directly cached
                   12418: #
1.428     albertel 12419:     if (!defined($liburi)) {
1.599     albertel 12420: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12421: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12422:     }
                   12423:     {
1.1069    www      12424: # Imported parts would go here
1.1172.2.99  raeburn  12425:         my @origfiletagids=();
1.1069    www      12426:         my $importedparts=0;
1.1172.2.99  raeburn  12427: 
                   12428: # Imported responseids would go here
                   12429:         my $importedresponses=0;
1.172     www      12430: #
                   12431: # Is this a recursive call for a library?
                   12432: #
1.599     albertel 12433: #	if (! exists($metacache{$uri})) {
                   12434: #	    $metacache{$uri}={};
                   12435: #	}
1.924     albertel 12436: 	my $cachetime = 60*60;
1.171     www      12437:         if ($liburi) {
                   12438: 	    $liburi=&declutter($liburi);
                   12439:             $filename=$liburi;
1.401     bowersj2 12440:         } else {
1.599     albertel 12441: 	    &devalidate_cache_new('meta',$uri);
                   12442: 	    undef(%metaentry);
1.401     bowersj2 12443: 	}
1.140     www      12444:         my %metathesekeys=();
1.73      www      12445:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12446: 	my $metastring;
1.1140    www      12447: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12448: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12449: 	    $metastring = 
1.929     albertel 12450: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12451: 					  ('grade_target' => 'meta'));
                   12452: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12453: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12454:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12455: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12456: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12457: 	    $metastring=&getfile($file);
1.489     albertel 12458: 	}
1.208     albertel 12459:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12460:         my $token;
1.140     www      12461:         undef %metathesekeys;
1.71      www      12462:         while ($token=$parser->get_token) {
1.339     albertel 12463: 	    if ($token->[0] eq 'S') {
                   12464: 		if (defined($token->[2]->{'package'})) {
1.172     www      12465: #
                   12466: # This is a package - get package info
                   12467: #
1.339     albertel 12468: 		    my $package=$token->[2]->{'package'};
                   12469: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12470: 		    if (defined($token->[2]->{'id'})) { 
                   12471: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12472: 		    }
1.599     albertel 12473: 		    if ($metaentry{':packages'}) {
                   12474: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12475: 		    } else {
1.599     albertel 12476: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12477: 		    }
1.736     albertel 12478: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12479: 			my $part=$keyroot;
                   12480: 			$part=~s/^\_//;
1.736     albertel 12481: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12482: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12483: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12484: 			    # ignore package.tab specified default values
                   12485:                             # here &package_tab_default() will fetch those
                   12486: 			    if ($subp eq 'default') { next; }
1.736     albertel 12487: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12488: 			    my $unikey;
                   12489: 			    if ($pack =~ /_0$/) {
                   12490: 				$unikey='parameter_0_'.$name;
                   12491: 				$part=0;
                   12492: 			    } else {
                   12493: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12494: 			    }
1.339     albertel 12495: 			    if ($subp eq 'display') {
                   12496: 				$value.=' [Part: '.$part.']';
                   12497: 			    }
1.599     albertel 12498: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12499: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12500: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12501: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12502: 			    }
1.599     albertel 12503: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12504: 				$metaentry{':'.$unikey}=
                   12505: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12506: 			    }
1.339     albertel 12507: 			}
                   12508: 		    }
                   12509: 		} else {
1.172     www      12510: #
                   12511: # This is not a package - some other kind of start tag
1.339     albertel 12512: #
                   12513: 		    my $entry=$token->[1];
1.1068    www      12514: 		    my $unikey='';
1.175     www      12515: 
1.339     albertel 12516: 		    if ($entry eq 'import') {
1.175     www      12517: #
                   12518: # Importing a library here
1.339     albertel 12519: #
1.1067    www      12520:                         my $location=$parser->get_text('/import');
                   12521:                         my $dir=$filename;
                   12522:                         $dir=~s|[^/]*$||;
                   12523:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12524: 
                   12525:                         my $importid=$token->[2]->{'id'};
1.1068    www      12526:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12527: #
                   12528: # Check metadata for imported file to
                   12529: # see if it contained response items
                   12530: #
                   12531:                         my %currmetaentry = %metaentry;
                   12532:                         my $libresponseorder = &metadata($location,'responseorder');
                   12533:                         my $origfile;
                   12534:                         if ($libresponseorder ne '') {
                   12535:                             if ($#origfiletagids<0) {
                   12536:                                 undef(%importedrespids);
                   12537:                                 undef(%importedpartids);
                   12538:                             }
                   12539:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12540:                             if (@{$importedrespids{$importid}} > 0) {
                   12541:                                 $importedresponses = 1;
                   12542: # We need to get the original file and the imported file to get the response order correct
                   12543: # Load and inspect original file
                   12544:                                 if ($#origfiletagids<0) {
                   12545:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12546:                                     $origfile=&getfile($origfilelocation);
                   12547:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12548:                                 }
                   12549:                             }
                   12550:                         }
                   12551: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12552: # hash populated for imported library file
                   12553:                         %metaentry = %currmetaentry;
                   12554:                         undef(%currmetaentry);
1.1068    www      12555:                         if ($importmode eq 'problem') {
1.1069    www      12556: # Import as problem/response
1.1068    www      12557:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12558:                         } elsif ($importmode eq 'part') {
                   12559: # Import as part(s)
1.1069    www      12560:                            $importedparts=1;
                   12561: # We need to get the original file and the imported file to get the part order correct
                   12562: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12563: # Load and inspect original file if we didn't do that already
                   12564:                            if ($#origfiletagids<0) {
                   12565:                                undef(%importedrespids);
                   12566:                                undef(%importedpartids);
                   12567:                                if ($origfile eq '') {
                   12568:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12569:                                    $origfile=&getfile($origfilelocation);
                   12570:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12571:                                }
1.1070    www      12572:                            }
                   12573: 
1.1069    www      12574: # Load and inspect imported file
                   12575:                            my $impfile=&getfile($location);
                   12576:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12577:                            if ($#impfilepartids>=0) {
                   12578: # This problem had parts
1.1070    www      12579:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12580:                            } else {
                   12581: # Importing by turning a single problem into a problem part
                   12582: # It gets the import-tags ID as part-ID
                   12583:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12584:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12585:                            }
1.1068    www      12586:                         } else {
                   12587: # Normal import
                   12588:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12589:                            if (defined($token->[2]->{'id'})) {
                   12590:                               $unikey.='_'.$token->[2]->{'id'};
                   12591:                            }
1.1067    www      12592:                         }
                   12593: 
1.339     albertel 12594: 			if ($depthcount<20) {
1.736     albertel 12595: 			    my $metadata = 
                   12596: 				&metadata($uri,'keys', $location,$unikey,
                   12597: 					  $depthcount+1);
                   12598: 			    foreach my $meta (split(',',$metadata)) {
                   12599: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12600: 				$metathesekeys{$meta}=1;
1.339     albertel 12601: 			    }
1.1068    www      12602: 			
                   12603:                         }
1.1067    www      12604: 		    } else {
                   12605: #
                   12606: # Not importing, some other kind of non-package, non-library start tag
                   12607: # 
                   12608:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12609:                         if (defined($token->[2]->{'id'})) {
                   12610:                             $unikey.='_'.$token->[2]->{'id'};
                   12611:                         }
1.339     albertel 12612: 			if (defined($token->[2]->{'name'})) { 
                   12613: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12614: 			}
                   12615: 			$metathesekeys{$unikey}=1;
1.736     albertel 12616: 			foreach my $param (@{$token->[3]}) {
                   12617: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12618: 				$token->[2]->{$param};
1.339     albertel 12619: 			}
                   12620: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12621: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12622: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12623: 		 # only ws inside the tag, and not in default, so use default
                   12624: 		 # as value
1.599     albertel 12625: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12626: 			} elsif ( $internaltext =~ /\S/ ) {
                   12627: 		  # something interesting inside the tag
                   12628: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12629: 			} else {
1.908     albertel 12630: 		  # no interesting values, don't set a default
1.339     albertel 12631: 			}
1.172     www      12632: # end of not-a-package not-a-library import
1.339     albertel 12633: 		    }
1.172     www      12634: # end of not-a-package start tag
1.339     albertel 12635: 		}
1.172     www      12636: # the next is the end of "start tag"
1.339     albertel 12637: 	    }
                   12638: 	}
1.483     albertel 12639: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12640: 	$extension = lc($extension);
                   12641: 	if ($extension eq 'htm') { $extension='html'; }
                   12642: 
1.737     albertel 12643: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12644: 	    #no specific packages #how's our extension
                   12645: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12646: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12647: 					 \%metathesekeys);
                   12648: 	}
1.883     albertel 12649: 
                   12650: 	if (!exists($metaentry{':packages'})
                   12651: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12652: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12653: 		#no specific packages well let's get default then
                   12654: 		if ($key!~/^default&/) { next; }
1.488     albertel 12655: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12656: 					     \%metathesekeys);
                   12657: 	    }
                   12658: 	}
1.338     www      12659: # are there custom rights to evaluate
1.599     albertel 12660: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12661: 
1.338     www      12662:     #
                   12663:     # Importing a rights file here
1.339     albertel 12664:     #
                   12665: 	    unless ($depthcount) {
1.599     albertel 12666: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12667: 		my $dir=$filename;
                   12668: 		$dir=~s|[^/]*$||;
                   12669: 		$location=&filelocation($dir,$location);
1.736     albertel 12670: 		my $rights_metadata =
                   12671: 		    &metadata($uri,'keys',$location,'_rights',
                   12672: 			      $depthcount+1);
                   12673: 		foreach my $rights (split(',',$rights_metadata)) {
                   12674: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12675: 		    $metathesekeys{$rights}=1;
1.339     albertel 12676: 		}
                   12677: 	    }
                   12678: 	}
1.737     albertel 12679: 	# uniqifiy package listing
                   12680: 	my %seen;
                   12681: 	my @uniq_packages =
                   12682: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12683: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12684: 
1.1172.2.99  raeburn  12685:         if (($importedresponses) || ($importedparts)) {
                   12686:             if ($importedparts) {
1.1070    www      12687: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12688:                 $metaentry{':partorder'}='';
                   12689:                 $metathesekeys{'partorder'}=1;
                   12690:             }
                   12691:             if ($importedresponses) {
                   12692: # We had imported responses and need to rebuild responseorder
                   12693:                 $metaentry{':responseorder'}='';
                   12694:                 $metathesekeys{'responseorder'}=1;
                   12695:             }
                   12696:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12697:                 my $origid = $origfiletagids[$index+1];
                   12698:                 if ($origfiletagids[$index] eq 'part') {
                   12699: # Original part, part of the problem
                   12700:                     if ($importedparts) {
                   12701:                         $metaentry{':partorder'}.=','.$origid;
                   12702:                     }
                   12703:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12704:                     if ($importedparts) {
                   12705: # We have imported parts at this position
                   12706:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12707:                     }
                   12708:                     if ($importedresponses) {
                   12709: # We have imported responses at this position
                   12710:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12711:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12712:                         }
                   12713:                     }
                   12714:                 } else {
                   12715: # Original response item, part of the problem
                   12716:                     if ($importedresponses) {
                   12717:                         $metaentry{':responseorder'}.=','.$origid;
                   12718:                     }
                   12719:                 }
                   12720:             }
                   12721:             if ($importedparts) {
                   12722:                 $metaentry{':partorder'}=~s/^\,//;
                   12723:             }
                   12724:             if ($importedresponses) {
                   12725:                 $metaentry{':responseorder'}=~s/^\,//;
                   12726:             }
1.1070    www      12727:         }
                   12728: 
1.737     albertel 12729: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12730: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12731: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12732: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12733: # this is the end of "was not already recently cached
1.71      www      12734:     }
1.599     albertel 12735:     return $metaentry{':'.$what};
1.261     albertel 12736: }
                   12737: 
1.488     albertel 12738: sub metadata_create_package_def {
1.483     albertel 12739:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12740:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12741:     if ($subp eq 'default') { next; }
                   12742:     
1.599     albertel 12743:     if (defined($metaentry{':packages'})) {
                   12744: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12745:     } else {
1.599     albertel 12746: 	$metaentry{':packages'}=$package;
1.483     albertel 12747:     }
                   12748:     my $value=$packagetab{$key};
                   12749:     my $unikey;
                   12750:     $unikey='parameter_0_'.$name;
1.599     albertel 12751:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12752:     $$metathesekeys{$unikey}=1;
1.599     albertel 12753:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12754: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12755:     }
1.599     albertel 12756:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12757: 	$metaentry{':'.$unikey}=
                   12758: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12759:     }
                   12760: }
                   12761: 
1.261     albertel 12762: sub metadata_generate_part0 {
                   12763:     my ($metadata,$metacache,$uri) = @_;
                   12764:     my %allnames;
1.737     albertel 12765:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12766: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12767: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12768: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12769: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12770: 	    $allnames{$name}=$part;
                   12771: 	  }
                   12772: 	}
                   12773:     }
                   12774:     foreach my $name (keys(%allnames)) {
                   12775:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12776:       my $key=":parameter_0_$name";
1.261     albertel 12777:       $$metacache{"$key.part"}='0';
                   12778:       $$metacache{"$key.name"}=$name;
1.428     albertel 12779:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12780: 					   $allnames{$name}.'_'.$name.
                   12781: 					   '.type'};
1.428     albertel 12782:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12783: 			     '.display'};
1.644     www      12784:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12785:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12786:       $$metacache{"$key.display"}=$olddis;
                   12787:     }
1.71      www      12788: }
                   12789: 
1.764     albertel 12790: # ------------------------------------------------------ Devalidate title cache
                   12791: 
                   12792: sub devalidate_title_cache {
                   12793:     my ($url)=@_;
                   12794:     if (!$env{'request.course.id'}) { return; }
                   12795:     my $symb=&symbread($url);
                   12796:     if (!$symb) { return; }
                   12797:     my $key=$env{'request.course.id'}."\0".$symb;
                   12798:     &devalidate_cache_new('title',$key);
                   12799: }
                   12800: 
1.1014    droeschl 12801: # ------------------------------------------------- Get the title of a course
                   12802: 
                   12803: sub current_course_title {
                   12804:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12805: }
1.301     www      12806: # ------------------------------------------------- Get the title of a resource
                   12807: 
                   12808: sub gettitle {
                   12809:     my $urlsymb=shift;
                   12810:     my $symb=&symbread($urlsymb);
1.534     albertel 12811:     if ($symb) {
1.620     albertel 12812: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12813: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12814: 	if (defined($cached)) { 
                   12815: 	    return $result;
                   12816: 	}
1.534     albertel 12817: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12818: 	my $title='';
1.907     albertel 12819: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12820: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12821: 	} else {
                   12822: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12823: 		    &GDBM_READER(),0640)) {
                   12824: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12825: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12826: 		untie(%bighash);
                   12827: 	    }
1.534     albertel 12828: 	}
                   12829: 	$title=~s/\&colon\;/\:/gs;
                   12830: 	if ($title) {
1.1159    www      12831: # Remember both $symb and $title for dynamic metadata
                   12832:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12833:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12834: # Cache this title and then return it
1.599     albertel 12835: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12836: 	}
                   12837: 	$urlsymb=$url;
                   12838:     }
                   12839:     my $title=&metadata($urlsymb,'title');
                   12840:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12841:     return $title;
1.301     www      12842: }
1.613     albertel 12843: 
1.614     albertel 12844: sub get_slot {
                   12845:     my ($which,$cnum,$cdom)=@_;
                   12846:     if (!$cnum || !$cdom) {
1.790     albertel 12847: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12848: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12849: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12850:     }
1.703     albertel 12851:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12852:     my %slotinfo;
                   12853:     if (exists($remembered{$key})) {
                   12854: 	$slotinfo{$which} = $remembered{$key};
                   12855:     } else {
                   12856: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12857: 	&Apache::lonhomework::showhash(%slotinfo);
                   12858: 	my ($tmp)=keys(%slotinfo);
                   12859: 	if ($tmp=~/^error:/) { return (); }
                   12860: 	$remembered{$key} = $slotinfo{$which};
                   12861:     }
1.616     albertel 12862:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12863: 	return %{$slotinfo{$which}};
                   12864:     }
                   12865:     return $slotinfo{$which};
1.614     albertel 12866: }
1.1150    raeburn  12867: 
                   12868: sub get_reservable_slots {
                   12869:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12870:     my $now = time;
                   12871:     my $reservable_info;
                   12872:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12873:     if (exists($remembered{$key})) {
                   12874:         $reservable_info = $remembered{$key};
                   12875:     } else {
                   12876:         my %resv;
                   12877:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12878:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12879:         $reservable_info = \%resv;
                   12880:         $remembered{$key} = $reservable_info;
                   12881:     }
                   12882:     return $reservable_info;
                   12883: }
                   12884: 
                   12885: sub get_course_slots {
                   12886:     my ($cnum,$cdom) = @_;
                   12887:     my $hashid=$cnum.':'.$cdom;
                   12888:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12889:     if (defined($cached)) {
                   12890:         if (ref($result) eq 'HASH') {
                   12891:             return %{$result};
                   12892:         }
                   12893:     } else {
                   12894:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12895:         my ($tmp) = keys(%slots);
                   12896:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12897:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12898:             return %slots;
                   12899:         }
                   12900:     }
                   12901:     return;
                   12902: }
                   12903: 
                   12904: sub devalidate_slots_cache {
                   12905:     my ($cnum,$cdom)=@_;
                   12906:     my $hashid=$cnum.':'.$cdom;
                   12907:     &devalidate_cache_new('allslots',$hashid);
                   12908: }
                   12909: 
1.1172.2.8  raeburn  12910: sub get_coursechange {
                   12911:     my ($cdom,$cnum) = @_;
                   12912:     if ($cdom eq '' || $cnum eq '') {
                   12913:         return unless ($env{'request.course.id'});
                   12914:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12915:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12916:     }
                   12917:     my $hashid=$cdom.'_'.$cnum;
                   12918:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12919:     if ((defined($cached)) && ($change ne '')) {
                   12920:         return $change;
                   12921:     } else {
                   12922:         my %crshash;
                   12923:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12924:         if ($crshash{'internal.contentchange'} eq '') {
                   12925:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12926:             if ($change eq '') {
                   12927:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12928:                 $change = $crshash{'internal.created'};
                   12929:             }
                   12930:         } else {
                   12931:             $change = $crshash{'internal.contentchange'};
                   12932:         }
                   12933:         my $cachetime = 600;
                   12934:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12935:     }
                   12936:     return $change;
                   12937: }
                   12938: 
                   12939: sub devalidate_coursechange_cache {
                   12940:     my ($cnum,$cdom)=@_;
                   12941:     my $hashid=$cnum.':'.$cdom;
                   12942:     &devalidate_cache_new('crschange',$hashid);
                   12943: }
                   12944: 
1.31      www      12945: # ------------------------------------------------- Update symbolic store links
                   12946: 
                   12947: sub symblist {
                   12948:     my ($mapname,%newhash)=@_;
1.438     www      12949:     $mapname=&deversion(&declutter($mapname));
1.31      www      12950:     my %hash;
1.620     albertel 12951:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12952:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12953:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12954: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12955: 		next if ($url eq 'last_known'
                   12956: 			 && $env{'form.no_update_last_known'});
                   12957: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12958: 						    $newhash{$url}->[1],
                   12959: 						    $newhash{$url}->[0]);
1.191     harris41 12960:             }
1.31      www      12961:             if (untie(%hash)) {
                   12962: 		return 'ok';
                   12963:             }
                   12964:         }
                   12965:     }
                   12966:     return 'error';
1.212     www      12967: }
                   12968: 
                   12969: # --------------------------------------------------------------- Verify a symb
                   12970: 
                   12971: sub symbverify {
1.1172.2.11  raeburn  12972:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12973:     my $thisfn=$thisurl;
1.439     www      12974:     $thisfn=&declutter($thisfn);
1.215     www      12975: # direct jump to resource in page or to a sequence - will construct own symbs
                   12976:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12977: # check URL part
1.409     www      12978:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12979: 
1.431     www      12980:     unless ($url eq $thisfn) { return 0; }
1.213     www      12981: 
1.216     www      12982:     $symb=&symbclean($symb);
1.510     www      12983:     $thisurl=&deversion($thisurl);
1.439     www      12984:     $thisfn=&deversion($thisfn);
1.213     www      12985: 
                   12986:     my %bighash;
                   12987:     my $okay=0;
1.431     www      12988: 
1.620     albertel 12989:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12990:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12991:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12992:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12993:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12994:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12995:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12996:             }
                   12997:         }
                   12998:         my $ids;
1.1172.2.122  raeburn  12999:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13000:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13001:         } else {
                   13002:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13003:         }
1.1102    raeburn  13004:         unless ($ids) {
1.1172.2.13  raeburn  13005:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13006:             $ids=$bighash{$idkey};
1.216     www      13007:         }
                   13008:         if ($ids) {
                   13009: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13010:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13011:                 $symb =~ s/\?.+$//;
                   13012:             }
1.800     albertel 13013: 	    foreach my $id (split(/\,/,$ids)) {
                   13014: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13015:                if (
                   13016:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13017:    eq $symb) {
1.1172.2.11  raeburn  13018:                    if (ref($encstate)) {
                   13019:                        $$encstate = $bighash{'encrypted_'.$id};
                   13020:                    }
1.1172.2.13  raeburn  13021:                    if (($env{'request.role.adv'}) ||
                   13022:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13023:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13024:                        $okay=1;
                   13025:                        last;
                   13026:                    }
                   13027:                }
                   13028:            }
1.216     www      13029:         }
1.213     www      13030: 	untie(%bighash);
                   13031:     }
                   13032:     return $okay;
1.31      www      13033: }
                   13034: 
1.210     www      13035: # --------------------------------------------------------------- Clean-up symb
                   13036: 
                   13037: sub symbclean {
                   13038:     my $symb=shift;
1.568     albertel 13039:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13040: # remove version from map
                   13041:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13042: 
1.210     www      13043: # remove version from URL
                   13044:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13045: 
1.507     www      13046: # remove wrapper
                   13047: 
1.510     www      13048:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13049:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13050:     return $symb;
1.409     www      13051: }
                   13052: 
                   13053: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13054: 
                   13055: sub encode_symb {
                   13056:     my ($map,$resid,$url)=@_;
                   13057:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13058: }
1.409     www      13059: 
                   13060: sub decode_symb {
1.568     albertel 13061:     my $symb=shift;
                   13062:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13063:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13064:     return (&fixversion($map),$resid,&fixversion($url));
                   13065: }
                   13066: 
                   13067: sub fixversion {
                   13068:     my $fn=shift;
1.609     banghart 13069:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13070:     my %bighash;
                   13071:     my $uri=&clutter($fn);
1.620     albertel 13072:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13073: # is this cached?
1.599     albertel 13074:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13075:     if (defined($cached)) { return $result; }
                   13076: # unfortunately not cached, or expired
1.620     albertel 13077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13078: 	    &GDBM_READER(),0640)) {
                   13079:  	if ($bighash{'version_'.$uri}) {
                   13080:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13081:  	    unless (($version eq 'mostrecent') || 
                   13082: 		    ($version==&getversion($uri))) {
1.440     www      13083:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13084:  	    }
                   13085:  	}
                   13086:  	untie %bighash;
1.413     www      13087:     }
1.599     albertel 13088:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13089: }
                   13090: 
                   13091: sub deversion {
                   13092:     my $url=shift;
                   13093:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13094:     return $url;
1.210     www      13095: }
                   13096: 
1.31      www      13097: # ------------------------------------------------------ Return symb list entry
                   13098: 
                   13099: sub symbread {
1.1172.2.126  raeburn  13100:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13101:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13102:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13103:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13104:         unless (ref($possibles) eq 'HASH') {
                   13105:             if ($ignorecachednull) {
                   13106:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13107:             } else {
                   13108:                 return $env{$cache_str};
                   13109:             }
1.1172.2.66  raeburn  13110:         }
                   13111:     }
1.242     www      13112: # no filename provided? try from environment
1.1172.2.54  raeburn  13113:     unless ($thisfn) {
1.620     albertel 13114:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13115:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13116:         }
                   13117:         $thisfn=$env{'request.filename'};
1.44      www      13118:     }
1.569     albertel 13119:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13120: # is that filename actually a symb? Verify, clean, and return
                   13121:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13122: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13123: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13124: 	}
1.242     www      13125:     }
1.44      www      13126:     $thisfn=declutter($thisfn);
1.31      www      13127:     my %hash;
1.37      www      13128:     my %bighash;
                   13129:     my $syval='';
1.620     albertel 13130:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13131:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13132:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13133:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13134:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13135:                 untie(%hash);
                   13136:             }
1.1172.2.128  raeburn  13137:             if ($syval && $checkforblock) {
                   13138:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13139:                 if (@blockers) {
                   13140:                     $syval='';
                   13141:                 }
                   13142:             }
1.37      www      13143:         }
                   13144: # ---------------------------------------------------------- There was an entry
                   13145:         if ($syval) {
1.601     albertel 13146: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13147: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13148: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13149: 		    #return $env{$cache_str}='';
1.601     albertel 13150: 		#}    
                   13151: 		#$syval.=$1;
                   13152: 	    #}
1.37      www      13153:         } else {
                   13154: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13155:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13156:                             &GDBM_READER(),0640)) {
1.37      www      13157: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13158:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13159:               unless ($ids) { 
                   13160:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13161:               }
                   13162:               unless ($ids) {
                   13163: # alias?
                   13164: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13165:               }
1.37      www      13166:               if ($ids) {
                   13167: # ------------------------------------------------------------------- Has ID(s)
                   13168:                  my @possibilities=split(/\,/,$ids);
1.39      www      13169:                  if ($#possibilities==0) {
                   13170: # ----------------------------------------------- There is only one possibility
1.37      www      13171: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13172: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13173: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13174:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13175:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13176:                              $possibles->{$syval} = 1;
                   13177:                          }
1.1172.2.66  raeburn  13178:                      }
                   13179:                      if ($checkforblock) {
1.1172.2.126  raeburn  13180:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13181:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13182:                              if (@blockers) {
                   13183:                                  $syval = '';
                   13184:                                  untie(%bighash);
                   13185:                                  return $env{$cache_str}='';
                   13186:                              }
1.1172.2.66  raeburn  13187:                          }
                   13188:                      }
                   13189:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13190: # ------------------------------------------ There is more than one possibility
                   13191:                      my $realpossible=0;
1.800     albertel 13192:                      foreach my $id (@possibilities) {
                   13193: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13194:                          my $canaccess;
                   13195:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13196:                              $canaccess = 1;
                   13197:                          } else {
                   13198:                              $canaccess = &allowed('bre',$file);
                   13199:                          }
                   13200:                          if ($canaccess) {
                   13201:          		     my ($mapid,$resid)=split(/\./,$id);
                   13202:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13203:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13204:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13205:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13206:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13207:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13208:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13209:                                      if (@blockers > 0) {
                   13210:                                          $syval = '';
                   13211:                                      } else {
1.1172.2.66  raeburn  13212:                                          $syval = $poss_syval;
                   13213:                                          $realpossible++;
                   13214:                                      }
                   13215:                                  } else {
                   13216:                                      $syval = $poss_syval;
                   13217:                                      $realpossible++;
                   13218:                                  }
1.1172.2.126  raeburn  13219:                                  if ($syval) {
                   13220:                                      if (ref($possibles) eq 'HASH') {
                   13221:                                          $possibles->{$syval} = 1;
                   13222:                                      }
                   13223:                                  }
1.1172.2.66  raeburn  13224:                              }
1.39      www      13225: 			 }
1.191     harris41 13226:                      }
1.39      www      13227: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13228:                  } else {
                   13229:                      $syval='';
1.37      www      13230:                  }
                   13231: 	      }
1.1172.2.66  raeburn  13232:               untie(%bighash);
1.481     raeburn  13233:            }
1.31      www      13234:         }
1.62      www      13235:         if ($syval) {
1.1172.2.128  raeburn  13236: 	    return $env{$cache_str}=$syval;
1.62      www      13237:         }
1.31      www      13238:     }
1.949     raeburn  13239:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13240:     return $env{$cache_str}='';
1.31      www      13241: }
                   13242: 
                   13243: # ---------------------------------------------------------- Return random seed
                   13244: 
1.32      www      13245: sub numval {
                   13246:     my $txt=shift;
                   13247:     $txt=~tr/A-J/0-9/;
                   13248:     $txt=~tr/a-j/0-9/;
                   13249:     $txt=~tr/K-T/0-9/;
                   13250:     $txt=~tr/k-t/0-9/;
                   13251:     $txt=~tr/U-Z/0-5/;
                   13252:     $txt=~tr/u-z/0-5/;
                   13253:     $txt=~s/\D//g;
1.564     albertel 13254:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13255:     return int($txt);
1.368     albertel 13256: }
                   13257: 
1.484     albertel 13258: sub numval2 {
                   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; }
1.564     albertel 13270:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13271:     return int($total);
                   13272: }
                   13273: 
1.575     albertel 13274: sub numval3 {
                   13275:     use integer;
                   13276:     my $txt=shift;
                   13277:     $txt=~tr/A-J/0-9/;
                   13278:     $txt=~tr/a-j/0-9/;
                   13279:     $txt=~tr/K-T/0-9/;
                   13280:     $txt=~tr/k-t/0-9/;
                   13281:     $txt=~tr/U-Z/0-5/;
                   13282:     $txt=~tr/u-z/0-5/;
                   13283:     $txt=~s/\D//g;
                   13284:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13285:     my $total;
                   13286:     foreach my $val (@txts) { $total+=$val; }
                   13287:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13288:     return $total;
                   13289: }
                   13290: 
1.675     albertel 13291: sub digest {
                   13292:     my ($data)=@_;
                   13293:     my $digest=&Digest::MD5::md5($data);
                   13294:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13295:     my ($e,$f);
                   13296:     {
                   13297:         use integer;
                   13298:         $e=($a+$b);
                   13299:         $f=($c+$d);
                   13300:         if ($_64bit) {
                   13301:             $e=(($e<<32)>>32);
                   13302:             $f=(($f<<32)>>32);
                   13303:         }
                   13304:     }
                   13305:     if (wantarray) {
                   13306: 	return ($e,$f);
                   13307:     } else {
                   13308: 	my $g;
                   13309: 	{
                   13310: 	    use integer;
                   13311: 	    $g=($e+$f);
                   13312: 	    if ($_64bit) {
                   13313: 		$g=(($g<<32)>>32);
                   13314: 	    }
                   13315: 	}
                   13316: 	return $g;
                   13317:     }
                   13318: }
                   13319: 
1.368     albertel 13320: sub latest_rnd_algorithm_id {
1.675     albertel 13321:     return '64bit5';
1.366     albertel 13322: }
1.32      www      13323: 
1.503     albertel 13324: sub get_rand_alg {
                   13325:     my ($courseid)=@_;
1.790     albertel 13326:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13327:     if ($courseid) {
1.620     albertel 13328: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13329:     }
                   13330:     return &latest_rnd_algorithm_id();
                   13331: }
                   13332: 
1.562     albertel 13333: sub validCODE {
                   13334:     my ($CODE)=@_;
                   13335:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13336:     return 0;
                   13337: }
                   13338: 
1.491     albertel 13339: sub getCODE {
1.620     albertel 13340:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13341:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13342: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13343: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13344: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13345:     }
                   13346:     return undef;
                   13347: }
1.1133    foxr     13348: #
                   13349: #  Determines the random seed for a specific context:
                   13350: #
                   13351: # parameters:
                   13352: #   symb      - in course context the symb for the seed.
                   13353: #   course_id - The course id of the form domain_coursenum.
                   13354: #   domain    - Domain for the user.
                   13355: #   course    - Course for the user.
                   13356: #   cenv      - environment of the course.
                   13357: #
                   13358: # NOTE:
                   13359: #   All parameters are picked out of the environment if missing
                   13360: #   or not defined.
                   13361: #   If a symb cannot be determined the current time is used instead.
                   13362: #
                   13363: #  For a given well defined symb, courside, domain, username,
                   13364: #  and course environment, the seed is reproducible.
                   13365: #
1.31      www      13366: sub rndseed {
1.1133    foxr     13367:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13368:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13369:     if (!defined($symb)) {
1.366     albertel 13370: 	unless ($symb=$wsymb) { return time; }
                   13371:     }
1.1146    foxr     13372:     if (!defined $courseid) { 
                   13373: 	$courseid=$wcourseid; 
                   13374:     }
                   13375:     if (!defined $domain) { $domain=$wdomain; }
                   13376:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13377: 
                   13378:     my $which;
                   13379:     if (defined($cenv->{'rndseed'})) {
                   13380: 	$which = $cenv->{'rndseed'};
                   13381:     } else {
                   13382: 	$which =&get_rand_alg($courseid);
                   13383:     }
1.491     albertel 13384:     if (defined(&getCODE())) {
1.675     albertel 13385: 	if ($which eq '64bit5') {
                   13386: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13387: 	} elsif ($which eq '64bit4') {
1.575     albertel 13388: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13389: 	} else {
                   13390: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13391: 	}
1.675     albertel 13392:     } elsif ($which eq '64bit5') {
                   13393: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13394:     } elsif ($which eq '64bit4') {
                   13395: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13396:     } elsif ($which eq '64bit3') {
                   13397: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13398:     } elsif ($which eq '64bit2') {
                   13399: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13400:     } elsif ($which eq '64bit') {
                   13401: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13402:     }
                   13403:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13404: }
                   13405: 
                   13406: sub rndseed_32bit {
                   13407:     my ($symb,$courseid,$domain,$username)=@_;
                   13408:     {
                   13409: 	use integer;
                   13410: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13411: 	my $symbseed=numval($symb) << 22;
                   13412: 	my $namechck=unpack("%32C*",$username) << 17;
                   13413: 	my $nameseed=numval($username) << 12;
                   13414: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13415: 	my $courseseed=unpack("%32C*",$courseid);
                   13416: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13417: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13418: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13419: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13420: 	return $num;
                   13421:     }
                   13422: }
                   13423: 
                   13424: sub rndseed_64bit {
                   13425:     my ($symb,$courseid,$domain,$username)=@_;
                   13426:     {
                   13427: 	use integer;
                   13428: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13429: 	my $symbseed=numval($symb) << 10;
                   13430: 	my $namechck=unpack("%32S*",$username);
                   13431: 	
                   13432: 	my $nameseed=numval($username) << 21;
                   13433: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13434: 	my $courseseed=unpack("%32S*",$courseid);
                   13435: 	
                   13436: 	my $num1=$symbchck+$symbseed+$namechck;
                   13437: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13438: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13439: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13440: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13441: 	return "$num1,$num2";
1.155     albertel 13442:     }
1.366     albertel 13443: }
                   13444: 
1.443     albertel 13445: sub rndseed_64bit2 {
                   13446:     my ($symb,$courseid,$domain,$username)=@_;
                   13447:     {
                   13448: 	use integer;
                   13449: 	# strings need to be an even # of cahracters long, it it is odd the
                   13450:         # last characters gets thrown away
                   13451: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13452: 	my $symbseed=numval($symb) << 10;
                   13453: 	my $namechck=unpack("%32S*",$username.' ');
                   13454: 	
                   13455: 	my $nameseed=numval($username) << 21;
1.501     albertel 13456: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13457: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13458: 	
                   13459: 	my $num1=$symbchck+$symbseed+$namechck;
                   13460: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13461: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13462: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13463: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13464: 	return "$num1,$num2";
                   13465:     }
                   13466: }
                   13467: 
                   13468: sub rndseed_64bit3 {
                   13469:     my ($symb,$courseid,$domain,$username)=@_;
                   13470:     {
                   13471: 	use integer;
                   13472: 	# strings need to be an even # of cahracters long, it it is odd the
                   13473:         # last characters gets thrown away
                   13474: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13475: 	my $symbseed=numval2($symb) << 10;
                   13476: 	my $namechck=unpack("%32S*",$username.' ');
                   13477: 	
                   13478: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13479: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13480: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13481: 	
                   13482: 	my $num1=$symbchck+$symbseed+$namechck;
                   13483: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13484: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13485: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13486: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13487: 	
1.503     albertel 13488: 	return "$num1:$num2";
1.443     albertel 13489:     }
                   13490: }
                   13491: 
1.575     albertel 13492: sub rndseed_64bit4 {
                   13493:     my ($symb,$courseid,$domain,$username)=@_;
                   13494:     {
                   13495: 	use integer;
                   13496: 	# strings need to be an even # of cahracters long, it it is odd the
                   13497:         # last characters gets thrown away
                   13498: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13499: 	my $symbseed=numval3($symb) << 10;
                   13500: 	my $namechck=unpack("%32S*",$username.' ');
                   13501: 	
                   13502: 	my $nameseed=numval3($username) << 21;
                   13503: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13504: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13505: 	
                   13506: 	my $num1=$symbchck+$symbseed+$namechck;
                   13507: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13508: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13509: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13510: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13511: 	
1.575     albertel 13512: 	return "$num1:$num2";
                   13513:     }
                   13514: }
                   13515: 
1.675     albertel 13516: sub rndseed_64bit5 {
                   13517:     my ($symb,$courseid,$domain,$username)=@_;
                   13518:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13519:     return "$num1:$num2";
                   13520: }
                   13521: 
1.366     albertel 13522: sub rndseed_CODE_64bit {
                   13523:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13524:     {
1.366     albertel 13525: 	use integer;
1.443     albertel 13526: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13527: 	my $symbseed=numval2($symb);
1.491     albertel 13528: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13529: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13530: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13531: 	my $num1=$symbseed+$CODEchck;
                   13532: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13533: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13534: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13535: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13536: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13537: 	return "$num1:$num2";
1.366     albertel 13538:     }
                   13539: }
                   13540: 
1.575     albertel 13541: sub rndseed_CODE_64bit4 {
                   13542:     my ($symb,$courseid,$domain,$username)=@_;
                   13543:     {
                   13544: 	use integer;
                   13545: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13546: 	my $symbseed=numval3($symb);
                   13547: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13548: 	my $CODEseed=numval3(&getCODE());
                   13549: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13550: 	my $num1=$symbseed+$CODEchck;
                   13551: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13552: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13553: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13554: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13555: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13556: 	return "$num1:$num2";
                   13557:     }
                   13558: }
                   13559: 
1.675     albertel 13560: sub rndseed_CODE_64bit5 {
                   13561:     my ($symb,$courseid,$domain,$username)=@_;
                   13562:     my $code = &getCODE();
                   13563:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13564:     return "$num1:$num2";
                   13565: }
                   13566: 
1.366     albertel 13567: sub setup_random_from_rndseed {
                   13568:     my ($rndseed)=@_;
1.503     albertel 13569:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13570: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13571:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13572:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13573:         } else {
                   13574:             &Math::Random::random_set_seed($num1,$num2);
                   13575:         }
1.366     albertel 13576:     } else {
                   13577: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13578:     }
1.36      albertel 13579: }
                   13580: 
1.474     albertel 13581: sub latest_receipt_algorithm_id {
1.835     albertel 13582:     return 'receipt3';
1.474     albertel 13583: }
                   13584: 
1.480     www      13585: sub recunique {
                   13586:     my $fucourseid=shift;
                   13587:     my $unique;
1.835     albertel 13588:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13589: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13590: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13591:     } else {
                   13592: 	$unique=$perlvar{'lonReceipt'};
                   13593:     }
                   13594:     return unpack("%32C*",$unique);
                   13595: }
                   13596: 
                   13597: sub recprefix {
                   13598:     my $fucourseid=shift;
                   13599:     my $prefix;
1.835     albertel 13600:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13601: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13602: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13603:     } else {
                   13604: 	$prefix=$perlvar{'lonHostID'};
                   13605:     }
                   13606:     return unpack("%32C*",$prefix);
                   13607: }
                   13608: 
1.76      www      13609: sub ireceipt {
1.474     albertel 13610:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13611: 
                   13612:     my $return =&recprefix($fucourseid).'-';
                   13613: 
                   13614:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13615: 	$env{'request.state'} eq 'construct') {
                   13616: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13617: 	return $return;
                   13618:     }
                   13619: 
1.76      www      13620:     my $cuname=unpack("%32C*",$funame);
                   13621:     my $cudom=unpack("%32C*",$fudom);
                   13622:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13623:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13624:     my $cunique=&recunique($fucourseid);
1.474     albertel 13625:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13626:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13627: 
1.790     albertel 13628: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13629: 			       
                   13630: 	$return.= ($cunique%$cuname+
                   13631: 		   $cunique%$cudom+
                   13632: 		   $cusymb%$cuname+
                   13633: 		   $cusymb%$cudom+
                   13634: 		   $cucourseid%$cuname+
                   13635: 		   $cucourseid%$cudom+
                   13636: 		   $cpart%$cuname+
                   13637: 		   $cpart%$cudom);
                   13638:     } else {
                   13639: 	$return.= ($cunique%$cuname+
                   13640: 		   $cunique%$cudom+
                   13641: 		   $cusymb%$cuname+
                   13642: 		   $cusymb%$cudom+
                   13643: 		   $cucourseid%$cuname+
                   13644: 		   $cucourseid%$cudom);
                   13645:     }
                   13646:     return $return;
1.76      www      13647: }
                   13648: 
                   13649: sub receipt {
1.474     albertel 13650:     my ($part)=@_;
1.790     albertel 13651:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13652:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13653: }
1.260     ng       13654: 
1.790     albertel 13655: sub whichuser {
                   13656:     my ($passedsymb)=@_;
                   13657:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13658:     if (defined($env{'form.grade_symb'})) {
                   13659: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13660: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13661: 	if (!$allowed &&
                   13662: 	    exists($env{'request.course.sec'}) &&
                   13663: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13664: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13665: 			      '/'.$env{'request.course.sec'});
                   13666: 	}
                   13667: 	if ($allowed) {
                   13668: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13669: 	    $courseid=$tmp_courseid;
                   13670: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13671: 	    ($name)=&get_env_multiple('form.grade_username');
                   13672: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13673: 	}
                   13674:     }
                   13675:     if (!$passedsymb) {
                   13676: 	$symb=&symbread();
                   13677:     } else {
                   13678: 	$symb=$passedsymb;
                   13679:     }
                   13680:     $courseid=$env{'request.course.id'};
                   13681:     $domain=$env{'user.domain'};
                   13682:     $name=$env{'user.name'};
                   13683:     if ($name eq 'public' && $domain eq 'public') {
                   13684: 	if (!defined($env{'form.username'})) {
                   13685: 	    $env{'form.username'}.=time.rand(10000000);
                   13686: 	}
                   13687: 	$name.=$env{'form.username'};
                   13688:     }
                   13689:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13690: 
                   13691: }
                   13692: 
1.36      albertel 13693: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13694: # returns either the contents of the file or 
                   13695: # -1 if the file doesn't exist
1.481     raeburn  13696: #
                   13697: # if the target is a file that was uploaded via DOCS, 
                   13698: # a check will be made to see if a current copy exists on the local server,
                   13699: # if it does this will be served, otherwise a copy will be retrieved from
                   13700: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13701: # the local server.   
1.472     albertel 13702: 
1.36      albertel 13703: sub getfile {
1.538     albertel 13704:     my ($file) = @_;
1.609     banghart 13705:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13706:     &repcopy($file);
                   13707:     return &readfile($file);
                   13708: }
                   13709: 
                   13710: sub repcopy_userfile {
                   13711:     my ($file)=@_;
1.1142    raeburn  13712:     my $londocroot = $perlvar{'lonDocRoot'};
                   13713:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13714:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13715:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13716: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13717:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13718:     if (-e "$file") {
1.828     www      13719: # we already have a local copy, check it out
1.538     albertel 13720: 	my @fileinfo = stat($file);
1.828     www      13721: 	my $rtncode;
                   13722: 	my $info;
1.538     albertel 13723: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13724: 	if ($lwpresp ne 'ok') {
1.828     www      13725: # there is no such file anymore, even though we had a local copy
1.482     albertel 13726: 	    if ($rtncode eq '404') {
1.538     albertel 13727: 		unlink($file);
1.482     albertel 13728: 	    }
                   13729: 	    return -1;
                   13730: 	}
                   13731: 	if ($info < $fileinfo[9]) {
1.828     www      13732: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13733: 	    return 'ok';
1.828     www      13734: 	} else {
                   13735: # the file is outdated, get rid of it
                   13736: 	    unlink($file);
1.482     albertel 13737: 	}
1.828     www      13738:     }
                   13739: # one way or the other, at this point, we don't have the file
                   13740: # construct the correct path for the file
                   13741:     my @parts = ($cdom,$cnum); 
                   13742:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13743: 	push @parts, split(/\//,$1);
                   13744:     }
                   13745:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13746:     foreach my $part (@parts) {
                   13747: 	$path .= '/'.$part;
                   13748: 	if (!-e $path) {
                   13749: 	    mkdir($path,0770);
1.482     albertel 13750: 	}
                   13751:     }
1.828     www      13752: # now the path exists for sure
                   13753: # get a user agent
                   13754:     my $ua=new LWP::UserAgent;
                   13755:     my $transferfile=$file.'.in.transfer';
                   13756: # FIXME: this should flock
                   13757:     if (-e $transferfile) { return 'ok'; }
                   13758:     my $request;
                   13759:     $uri=~s/^\///;
1.980     raeburn  13760:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13761:     my $hostname = &hostname($homeserver);
1.980     raeburn  13762:     my $protocol = $protocol{$homeserver};
                   13763:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13764:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13765:     my $response=$ua->request($request,$transferfile);
                   13766: # did it work?
                   13767:     if ($response->is_error()) {
                   13768: 	unlink($transferfile);
                   13769: 	&logthis("Userfile repcopy failed for $uri");
                   13770: 	return -1;
                   13771:     }
                   13772: # worked, rename the transfer file
                   13773:     rename($transferfile,$file);
1.607     raeburn  13774:     return 'ok';
1.481     raeburn  13775: }
                   13776: 
1.517     albertel 13777: sub tokenwrapper {
                   13778:     my $uri=shift;
1.980     raeburn  13779:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13780:     $uri=~s|^/||;
1.620     albertel 13781:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13782:     my $token=$1;
1.552     albertel 13783:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13784:     if ($udom && $uname && $file) {
                   13785: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13786:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13787:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13788:         my $hostname = &hostname($homeserver);
1.980     raeburn  13789:         my $protocol = $protocol{$homeserver};
                   13790:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13791:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13792:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13793:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13794:     } else {
                   13795:         return '/adm/notfound.html';
                   13796:     }
                   13797: }
                   13798: 
1.828     www      13799: # call with reqtype HEAD: get last modification time
                   13800: # call with reqtype GET: get the file contents
                   13801: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13802: #
1.481     raeburn  13803: sub getuploaded {
                   13804:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13805:     $uri=~s/^\///;
1.980     raeburn  13806:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13807:     my $hostname = &hostname($homeserver);
1.980     raeburn  13808:     my $protocol = $protocol{$homeserver};
                   13809:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13810:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13811:     my $ua=new LWP::UserAgent;
                   13812:     my $request=new HTTP::Request($reqtype,$uri);
                   13813:     my $response=$ua->request($request);
                   13814:     $$rtncode = $response->code;
1.482     albertel 13815:     if (! $response->is_success()) {
                   13816: 	return 'failed';
                   13817:     }      
                   13818:     if ($reqtype eq 'HEAD') {
1.486     www      13819: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13820:     } elsif ($reqtype eq 'GET') {
                   13821: 	$$info = $response->content;
1.472     albertel 13822:     }
1.482     albertel 13823:     return 'ok';
1.36      albertel 13824: }
                   13825: 
1.481     raeburn  13826: sub readfile {
                   13827:     my $file = shift;
                   13828:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13829:     my $fh;
1.1172.2.96  raeburn  13830:     open($fh,"<",$file);
1.481     raeburn  13831:     my $a='';
1.800     albertel 13832:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13833:     return $a;
                   13834: }
                   13835: 
1.36      albertel 13836: sub filelocation {
1.590     banghart 13837:     my ($dir,$file) = @_;
                   13838:     my $location;
                   13839:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13840: 
                   13841:     if ($file =~ m-^/adm/-) {
                   13842: 	$file=~s-^/adm/wrapper/-/-;
                   13843: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13844:     }
1.882     albertel 13845: 
1.1139    www      13846:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13847:         $location = $file;
1.609     banghart 13848:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13849:         my ($udom,$uname,$filename)=
1.811     albertel 13850:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13851:         my $home=&homeserver($uname,$udom);
                   13852:         my $is_me=0;
                   13853:         my @ids=&current_machine_ids();
                   13854:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13855:         if ($is_me) {
1.1117    foxr     13856:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13857:         } else {
                   13858:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13859:   	      $udom.'/'.$uname.'/'.$filename;
                   13860:         }
1.882     albertel 13861:     } elsif ($file =~ m-^/adm/-) {
                   13862: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13863:     } else {
                   13864:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13865:         $file=~s:^/(res|priv)/:/:;
                   13866:         my $space=$1;
1.590     banghart 13867:         if ( !( $file =~ m:^/:) ) {
                   13868:             $location = $dir. '/'.$file;
                   13869:         } else {
1.1142    raeburn  13870:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13871:         }
1.59      albertel 13872:     }
1.590     banghart 13873:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13874:     while ($location=~m{/\.\./}) {
                   13875: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13876: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13877: 	} else {
                   13878: 	    $location=~ s{/\.\./}{/}g;
                   13879: 	}
                   13880:     } #remove dir/..
1.590     banghart 13881:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13882:     return $location;
1.46      www      13883: }
1.36      albertel 13884: 
1.46      www      13885: sub hreflocation {
                   13886:     my ($dir,$file)=@_;
1.980     raeburn  13887:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13888: 	$file=filelocation($dir,$file);
1.700     albertel 13889:     } elsif ($file=~m-^/adm/-) {
                   13890: 	$file=~s-^/adm/wrapper/-/-;
                   13891: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13892:     }
                   13893:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13894: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13895:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13896: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13897: 	        {/uploaded/$1/$2/}x;
1.46      www      13898:     }
1.913     albertel 13899:     if ($file=~ m{^/userfiles/}) {
                   13900: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13901:     }
1.462     albertel 13902:     return $file;
1.465     albertel 13903: }
                   13904: 
1.1139    www      13905: 
                   13906: 
                   13907: 
                   13908: 
1.465     albertel 13909: sub current_machine_domains {
1.853     albertel 13910:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13911: }
                   13912: 
                   13913: sub machine_domains {
                   13914:     my ($hostname) = @_;
1.465     albertel 13915:     my @domains;
1.838     albertel 13916:     my %hostname = &all_hostnames();
1.465     albertel 13917:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13918: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13919: 	if ($hostname eq $name) {
1.844     albertel 13920: 	    push(@domains,&host_domain($id));
1.465     albertel 13921: 	}
                   13922:     }
                   13923:     return @domains;
                   13924: }
                   13925: 
                   13926: sub current_machine_ids {
1.853     albertel 13927:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13928: }
                   13929: 
                   13930: sub machine_ids {
                   13931:     my ($hostname) = @_;
                   13932:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13933:     my @ids;
1.888     albertel 13934:     my %name_to_host = &all_names();
1.889     albertel 13935:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13936: 	return @{ $name_to_host{$hostname} };
                   13937:     }
                   13938:     return;
1.31      www      13939: }
                   13940: 
1.824     raeburn  13941: sub additional_machine_domains {
                   13942:     my @domains;
1.1172.2.142  raeburn  13943:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13944:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13945:             while( my $line = <$fh>) {
                   13946:                 chomp($line);
                   13947:                 $line =~ s/\s//g;
                   13948:                 push(@domains,$line);
                   13949:             }
                   13950:             close($fh);
                   13951:         }
1.824     raeburn  13952:     }
                   13953:     return @domains;
                   13954: }
                   13955: 
                   13956: sub default_login_domain {
                   13957:     my $domain = $perlvar{'lonDefDomain'};
                   13958:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13959:     foreach my $posdom (&current_machine_domains(),
                   13960:                         &additional_machine_domains()) {
                   13961:         if (lc($posdom) eq lc($testdomain)) {
                   13962:             $domain=$posdom;
                   13963:             last;
                   13964:         }
                   13965:     }
                   13966:     return $domain;
                   13967: }
                   13968: 
1.1172.2.106  raeburn  13969: sub shared_institution {
1.1172.2.136  raeburn  13970:     my ($dom,$lonhost) = @_;
                   13971:     if ($lonhost eq '') {
                   13972:         $lonhost = $perlvar{'lonHostID'};
                   13973:     }
1.1172.2.106  raeburn  13974:     my $same_intdom;
1.1172.2.136  raeburn  13975:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13976:     if ($hostintdom ne '') {
                   13977:         my %iphost = &get_iphost();
                   13978:         my $primary_id = &domain($dom,'primary');
                   13979:         my $primary_ip = &get_host_ip($primary_id);
                   13980:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13981:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13982:                 my $intdom = &internet_dom($id);
                   13983:                 if ($intdom eq $hostintdom) {
                   13984:                     $same_intdom = 1;
                   13985:                     last;
                   13986:                 }
                   13987:             }
                   13988:         }
                   13989:     }
                   13990:     return $same_intdom;
                   13991: }
                   13992: 
1.1172.2.120  raeburn  13993: sub uses_sts {
                   13994:     my ($ignore_cache) = @_;
                   13995:     my $lonhost = $perlvar{'lonHostID'};
                   13996:     my $hostname = &hostname($lonhost);
                   13997:     my $sts_on;
                   13998:     if ($protocol{$lonhost} eq 'https') {
                   13999:         my $cachetime = 12*3600;
                   14000:         if (!$ignore_cache) {
                   14001:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14002:             if (defined($cached)) {
                   14003:                 return $sts_on;
                   14004:             }
                   14005:         }
1.1172.2.121  raeburn  14006:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14007:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14008:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14009:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14010:         if ($response->is_success) {
                   14011:             my $has_sts = $response->header('Strict-Transport-Security');
                   14012:             if ($has_sts eq '') {
                   14013:                 $sts_on = 0;
                   14014:             } else {
                   14015:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14016:                     my $maxage = $1;
                   14017:                     if ($maxage) {
                   14018:                         $sts_on = 1;
                   14019:                     } else {
                   14020:                         $sts_on = 0;
                   14021:                     }
                   14022:                 } else {
                   14023:                     $sts_on = 0;
                   14024:                 }
                   14025:             }
                   14026:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14027:         }
                   14028:     }
                   14029:     return;
                   14030: }
                   14031: 
1.1172.2.142  raeburn  14032: sub waf_allssl {
                   14033:     my ($host_name) = @_;
                   14034:     my $alias = &get_proxy_alias();
                   14035:     if ($host_name eq '') {
                   14036:         $host_name = $ENV{'SERVER_NAME'};
                   14037:     }
                   14038:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14039:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14040:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14041:         if ($defdomdefaults{'waf_sslopt'}) {
                   14042:             return $defdomdefaults{'waf_sslopt'};
                   14043:         }
                   14044:     }
                   14045:     return;
                   14046: }
                   14047: 
1.1172.2.134  raeburn  14048: sub get_requestor_ip {
                   14049:     my ($r,$nolookup,$noproxy) = @_;
                   14050:     my $from_ip;
                   14051:     if (ref($r)) {
1.1172.2.142  raeburn  14052:         if ($r->can('useragent_ip')) {
                   14053:             if ($noproxy && $r->can('client_ip')) {
                   14054:                 $from_ip = $r->client_ip();
                   14055:             } else {
                   14056:                 $from_ip = $r->useragent_ip();
                   14057:             }
                   14058:         } elsif ($r->connection->can('remote_ip')) {
                   14059:             $from_ip = $r->connection->remote_ip();
                   14060:         } else {
                   14061:             $from_ip = $r->get_remote_host($nolookup);
                   14062:         }
1.1172.2.134  raeburn  14063:     } else {
                   14064:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14065:     }
1.1172.2.142  raeburn  14066:     return $from_ip if ($noproxy);
                   14067:    # Who controls proxy settings for server
                   14068:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14069:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14070:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14071:         if ($proxyinfo->{'vpnint'}) {
                   14072:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14073:                 return $from_ip;
                   14074:             }
                   14075:         }
                   14076:         if ($proxyinfo->{'trusted'}) {
                   14077:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14078:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14079:                 my ($ip,$xfor);
                   14080:                 if (ref($r)) {
                   14081:                     if ($ipheader) {
                   14082:                         $ip = $r->headers_in->{$ipheader};
                   14083:                     }
                   14084:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14085:                 } else {
                   14086:                     if ($ipheader) {
                   14087:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14088:                     }
                   14089:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14090:                 }
                   14091:                 if (($ip eq '') && ($xfor ne '')) {
                   14092:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14093:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14094:                             $ip = $poss_ip;
                   14095:                             last;
                   14096:                         }
                   14097:                     }
                   14098:                 }
                   14099:                 if ($ip ne '') {
                   14100:                     return $ip;
                   14101:                 }
                   14102:             }
                   14103:         }
                   14104:     }
1.1172.2.134  raeburn  14105:     return $from_ip;
                   14106: }
                   14107: 
1.1172.2.142  raeburn  14108: sub get_proxy_settings {
                   14109:     my ($dom_in_use) = @_;
                   14110:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14111:     my $proxyinfo = {
                   14112:                        ipheader => $domdefaults{'waf_ipheader'},
                   14113:                        trusted  => $domdefaults{'waf_trusted'},
                   14114:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14115:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14116:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14117:                     };
                   14118:     return $proxyinfo;
                   14119: }
                   14120: 
                   14121: sub ip_match {
                   14122:     my ($ip,$pattern_str) = @_;
                   14123:     $ip=Net::CIDR::cidrvalidate($ip);
                   14124:     if ($ip) {
                   14125:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14126:     }
                   14127:     return;
                   14128: }
                   14129: 
                   14130: sub get_proxy_alias {
                   14131:     my ($lonid) = @_;
                   14132:     if ($lonid eq '') {
                   14133:         $lonid = $perlvar{'lonHostID'};
                   14134:     }
                   14135:     if (!defined(&hostname($lonid))) {
                   14136:         return;
                   14137:     }
                   14138:     if ($lonid ne '') {
                   14139:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14140:         if ($cached) {
                   14141:             return $alias;
                   14142:         }
                   14143:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14144:         if ($dom ne '') {
                   14145:             my $cachetime = 60*60*24;
                   14146:             my %domconfig =
                   14147:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14148:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14149:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14150:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14151:                 }
                   14152:             }
                   14153:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14154:         }
                   14155:     }
                   14156:     return;
                   14157: }
                   14158: 
                   14159: sub use_proxy_alias {
                   14160:     my ($r,$lonid) = @_;
                   14161:     my $alias = &get_proxy_alias($lonid);
                   14162:     if ($alias) {
                   14163:         my $dom = &host_domain($lonid);
                   14164:         if ($dom ne '') {
                   14165:             my $proxyinfo = &get_proxy_settings($dom);
                   14166:             my ($vpnint,$remote_ip);
                   14167:             if (ref($proxyinfo) eq 'HASH') {
                   14168:                 $vpnint = $proxyinfo->{'vpnint'};
                   14169:                 if ($vpnint) {
                   14170:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14171:                 }
                   14172:             }
                   14173:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14174:                 return $alias;
                   14175:             }
                   14176:         }
                   14177:     }
                   14178:     return;
                   14179: }
                   14180: 
                   14181: sub alias_sso {
                   14182:     my ($lonid) = @_;
                   14183:     if ($lonid eq '') {
                   14184:         $lonid = $perlvar{'lonHostID'};
                   14185:     }
                   14186:     if (!defined(&hostname($lonid))) {
                   14187:         return;
                   14188:     }
                   14189:     if ($lonid ne '') {
                   14190:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14191:         if ($cached) {
                   14192:             return $use_alias;
                   14193:         }
                   14194:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14195:         if ($dom ne '') {
                   14196:             my $cachetime = 60*60*24;
                   14197:             my %domconfig =
                   14198:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14199:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14200:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14201:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14202:                 }
                   14203:             }
                   14204:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14205:         }
                   14206:     }
                   14207:     return;
                   14208: }
                   14209: 
                   14210: sub get_saml_landing {
                   14211:     my ($lonid) = @_;
                   14212:     if ($lonid eq '') {
                   14213:         my $defdom = &default_login_domain();
                   14214:         my @hosts = &current_machine_ids();
                   14215:         if (@hosts > 1) {
                   14216:             foreach my $hostid (@hosts) {
                   14217:                 if (&host_domain($hostid) eq $defdom) {
                   14218:                     $lonid = $hostid;
                   14219:                     last;
                   14220:                 }
                   14221:             }
                   14222:         } else {
                   14223:             $lonid = $perlvar{'lonHostID'};
                   14224:         }
                   14225:         if ($lonid) {
                   14226:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14227:                 return;
                   14228:             }
                   14229:         } else {
                   14230:             return;
                   14231:         }
                   14232:     } elsif (!defined(&hostname($lonid))) {
                   14233:         return;
                   14234:     }
                   14235:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14236:     if ($cached) {
                   14237:         return $landing;
                   14238:     }
                   14239:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14240:     if ($dom ne '') {
                   14241:         my $cachetime = 60*60*24;
                   14242:         my %domconfig =
                   14243:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14244:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14245:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14246:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14247:                     $landing = 1;
                   14248:                 }
                   14249:             }
                   14250:         }
                   14251:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14252:     }
                   14253:     return;
                   14254: }
                   14255: 
1.31      www      14256: # ------------------------------------------------------------- Declutters URLs
                   14257: 
                   14258: sub declutter {
                   14259:     my $thisfn=shift;
1.569     albertel 14260:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14261:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14262:         $thisfn=~s{^/home/httpd/html}{};
                   14263:     }
1.31      www      14264:     $thisfn=~s/^\///;
1.697     albertel 14265:     $thisfn=~s|^adm/wrapper/||;
                   14266:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14267:     $thisfn=~s/^res\///;
1.1172    bisitz   14268:     $thisfn=~s/^priv\///;
1.1032    raeburn  14269:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14270:         $thisfn=~s/\?.+$//;
                   14271:     }
1.268     www      14272:     return $thisfn;
                   14273: }
                   14274: 
                   14275: # ------------------------------------------------------------- Clutter up URLs
                   14276: 
                   14277: sub clutter {
                   14278:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14279:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14280: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14281:        $thisfn='/res'.$thisfn; 
                   14282:     }
1.1031    raeburn  14283:     if ($thisfn !~m|^/adm|) {
                   14284: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14285: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14286: 	} else {
                   14287: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14288: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14289: 	    if ($embstyle eq 'ssi'
                   14290: 		|| ($embstyle eq 'hdn')
                   14291: 		|| ($embstyle eq 'rat')
                   14292: 		|| ($embstyle eq 'prv')
                   14293: 		|| ($embstyle eq 'ign')) {
                   14294: 		#do nothing with these
                   14295: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14296: 		|| ($embstyle eq 'emb')
                   14297: 		|| ($embstyle eq 'wrp')) {
                   14298: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14299: 	    } elsif ($embstyle eq 'unk'
                   14300: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14301: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14302: 	    } else {
1.718     www      14303: #		&logthis("Got a blank emb style");
1.695     albertel 14304: 	    }
1.694     albertel 14305: 	}
1.1172.2.146.  .1(raebu 14306:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14307:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14308:     }
1.31      www      14309:     return $thisfn;
1.12      www      14310: }
                   14311: 
1.787     albertel 14312: sub clutter_with_no_wrapper {
                   14313:     my $uri = &clutter(shift);
                   14314:     if ($uri =~ m-^/adm/-) {
                   14315: 	$uri =~ s-^/adm/wrapper/-/-;
                   14316: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14317:     }
                   14318:     return $uri;
                   14319: }
                   14320: 
1.557     albertel 14321: sub freeze_escape {
                   14322:     my ($value)=@_;
                   14323:     if (ref($value)) {
                   14324: 	$value=&nfreeze($value);
                   14325: 	return '__FROZEN__'.&escape($value);
                   14326:     }
                   14327:     return &escape($value);
                   14328: }
                   14329: 
1.11      www      14330: 
1.557     albertel 14331: sub thaw_unescape {
                   14332:     my ($value)=@_;
                   14333:     if ($value =~ /^__FROZEN__/) {
                   14334: 	substr($value,0,10,undef);
                   14335: 	$value=&unescape($value);
                   14336: 	return &thaw($value);
                   14337:     }
                   14338:     return &unescape($value);
                   14339: }
                   14340: 
1.436     albertel 14341: sub correct_line_ends {
                   14342:     my ($result)=@_;
                   14343:     $$result =~s/\r\n/\n/mg;
                   14344:     $$result =~s/\r/\n/mg;
1.415     albertel 14345: }
1.1       albertel 14346: # ================================================================ Main Program
                   14347: 
1.184     www      14348: sub goodbye {
1.204     albertel 14349:    &logthis("Starting Shut down");
1.443     albertel 14350: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14351:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14352: #converted
1.599     albertel 14353: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14354:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14355: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14356: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14357: #1.1 only
1.870     albertel 14358: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14359: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14360: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14361: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14362:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14363:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14364:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14365:    &flushcourselogs();
                   14366:    &logthis("Shutting down");
                   14367: }
                   14368: 
1.852     albertel 14369: sub get_dns {
1.1172.2.17  raeburn  14370:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14371:     if (!$ignore_cache) {
                   14372: 	my ($content,$cached)=
                   14373: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14374: 	if ($cached) {
1.1172.2.17  raeburn  14375: 	    &$func($content,$hashref);
1.869     albertel 14376: 	    return;
                   14377: 	}
                   14378:     }
                   14379: 
                   14380:     my %alldns;
1.1172.2.96  raeburn  14381:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14382:         foreach my $dns (<$config>) {
                   14383: 	    next if ($dns !~ /^\^(\S*)/x);
                   14384:             my $line = $1;
                   14385:             my ($host,$protocol) = split(/:/,$line);
                   14386:             if ($protocol ne 'https') {
                   14387:                 $protocol = 'http';
                   14388:             }
                   14389: 	    $alldns{$host} = $protocol;
1.979     raeburn  14390:         }
1.1172.2.96  raeburn  14391:         close($config);
1.869     albertel 14392:     }
                   14393:     while (%alldns) {
1.1172.2.52  raeburn  14394: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14395:         my @content;
                   14396:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14397:             my $command = (split('/',$url))[3];
                   14398:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14399:             delete($alldns{$dns});
                   14400:             next if (($dir eq '') || ($file eq ''));
                   14401:             if (open(my $config,'<',"$dir/$file")) {
                   14402:                 @content = <$config>;
                   14403:                 close($config);
                   14404:             }
                   14405:         } else {
                   14406: 	    my $ua=new LWP::UserAgent;
                   14407:             $ua->timeout(30);
                   14408: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14409: 	    my $response=$ua->request($request);
                   14410:             delete($alldns{$dns});
                   14411: 	    next if ($response->is_error());
                   14412: 	    @content = split("\n",$response->content);
                   14413:         }
1.1172.2.17  raeburn  14414:         unless ($nocache) {
1.1172.2.23  raeburn  14415: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14416:         }
                   14417: 	&$func(\@content,$hashref);
1.869     albertel 14418: 	return;
1.852     albertel 14419:     }
1.871     albertel 14420:     my $which = (split('/',$url))[3];
                   14421:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14422:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14423:         my @content = <$config>;
                   14424:         &$func(\@content,$hashref);
                   14425:     }
1.1172.2.17  raeburn  14426:     return;
                   14427: }
                   14428: 
                   14429: # ------------------------------------------------------Get DNS checksums file
                   14430: sub parse_dns_checksums_tab {
                   14431:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14432:     my $lonhost = $perlvar{'lonHostID'};
                   14433:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14434:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14435:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14436:     my $webconfdir = '/etc/httpd/conf';
                   14437:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14438:         $webconfdir = '/etc/apache2';
                   14439:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14440:         if ($1 >= 10) {
                   14441:             $webconfdir = '/etc/apache2';
                   14442:         }
                   14443:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14444:         if ($1 >= 10.0) {
                   14445:             $webconfdir = '/etc/apache2';
                   14446:         }
                   14447:     }
1.1172.2.17  raeburn  14448:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14449:     my (%chksum,%revnum);
                   14450:     if (ref($lines) eq 'ARRAY') {
                   14451:         chomp(@{$lines});
1.1172.2.34  raeburn  14452:         my $version = shift(@{$lines});
                   14453:         if ($version eq $release) {
1.1172.2.17  raeburn  14454:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14455:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14456:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14457:                     if ($webconfdir eq '/etc/apache2') {
                   14458:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14459:                     }
                   14460:                 }
1.1172.2.34  raeburn  14461:                 $chksum{$file} = $shasum;
                   14462:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14463:             }
                   14464:             if (ref($hashref) eq 'HASH') {
                   14465:                 %{$hashref} = (
                   14466:                                 sums     => \%chksum,
                   14467:                                 versions => \%revnum,
                   14468:                               );
                   14469:             }
                   14470:         }
                   14471:     }
1.869     albertel 14472:     return;
1.852     albertel 14473: }
1.1172.2.17  raeburn  14474: 
                   14475: sub fetch_dns_checksums {
                   14476:     my %checksums;
1.1172.2.34  raeburn  14477:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14478:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14479:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14480:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14481:              \%checksums);
                   14482:     return \%checksums;
                   14483: }
                   14484: 
1.1172.2.142  raeburn  14485: sub parse_getdns_url {
                   14486:     my ($command,$url) = @_;
                   14487:     my $dir = $perlvar{'lonTabDir'};
                   14488:     my $file;
                   14489:     if ($command eq 'hosts') {
                   14490:         $file = 'dns_hosts.tab';
                   14491:     } elsif ($command eq 'domain') {
                   14492:         $file = 'dns_domain.tab';
                   14493:     } elsif ($command eq 'checksums') {
                   14494:         my $version = (split('/',$url))[4];
                   14495:         $file = "dns_checksums/$version.tab",
                   14496:     }
                   14497:     return ($dir,$file);
                   14498: }
                   14499: 
1.327     albertel 14500: # ------------------------------------------------------------ Read domain file
                   14501: {
1.852     albertel 14502:     my $loaded;
1.846     albertel 14503:     my %domain;
                   14504: 
1.852     albertel 14505:     sub parse_domain_tab {
                   14506: 	my ($lines) = @_;
                   14507: 	foreach my $line (@$lines) {
                   14508: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14509: 
1.846     albertel 14510: 	    chomp($line);
1.852     albertel 14511: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14512: 	    my %this_domain;
                   14513: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14514: 			       'lang_def', 'city', 'longi', 'lati',
                   14515: 			       'primary') {
                   14516: 		$this_domain{$field} = shift(@elements);
                   14517: 	    }
                   14518: 	    $domain{$name} = \%this_domain;
1.852     albertel 14519: 	}
                   14520:     }
1.864     albertel 14521: 
                   14522:     sub reset_domain_info {
                   14523: 	undef($loaded);
                   14524: 	undef(%domain);
                   14525:     }
                   14526: 
1.852     albertel 14527:     sub load_domain_tab {
1.1172.2.70  raeburn  14528: 	my ($ignore_cache,$nocache) = @_;
                   14529: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14530: 	my $fh;
1.1172.2.96  raeburn  14531: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14532: 	    my @lines = <$fh>;
                   14533: 	    &parse_domain_tab(\@lines);
1.448     albertel 14534: 	}
1.852     albertel 14535: 	close($fh);
                   14536: 	$loaded = 1;
1.327     albertel 14537:     }
1.846     albertel 14538: 
                   14539:     sub domain {
1.852     albertel 14540: 	&load_domain_tab() if (!$loaded);
                   14541: 
1.846     albertel 14542: 	my ($name,$what) = @_;
                   14543: 	return if ( !exists($domain{$name}) );
                   14544: 
                   14545: 	if (!$what) {
                   14546: 	    return $domain{$name}{'description'};
                   14547: 	}
                   14548: 	return $domain{$name}{$what};
                   14549:     }
1.974     raeburn  14550: 
                   14551:     sub domain_info {
                   14552:         &load_domain_tab() if (!$loaded);
                   14553:         return %domain;
                   14554:     }
                   14555: 
1.327     albertel 14556: }
                   14557: 
                   14558: 
1.1       albertel 14559: # ------------------------------------------------------------- Read hosts file
                   14560: {
1.838     albertel 14561:     my %hostname;
1.844     albertel 14562:     my %hostdom;
1.845     albertel 14563:     my %libserv;
1.852     albertel 14564:     my $loaded;
1.888     albertel 14565:     my %name_to_host;
1.1074    raeburn  14566:     my %internetdom;
1.1107    raeburn  14567:     my %LC_dns_serv;
1.852     albertel 14568: 
                   14569:     sub parse_hosts_tab {
                   14570: 	my ($file) = @_;
                   14571: 	foreach my $configline (@$file) {
                   14572: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14573:             chomp($configline);
                   14574: 	    if ($configline =~ /^\^/) {
                   14575:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14576:                     $LC_dns_serv{$1} = 1;
                   14577:                 }
                   14578:                 next;
                   14579:             }
1.1074    raeburn  14580: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14581: 	    $name=~s/\s//g;
                   14582: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14583:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14584:                     my $curr = $hostname{$id};
                   14585:                     my $skip;
                   14586:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14587:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14588:                             $skip = 1;
                   14589:                         } else {
                   14590:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14591:                         }
                   14592:                     }
                   14593:                     unless ($skip) {
                   14594:                         push(@{$name_to_host{$name}},$id);
                   14595:                     }
                   14596:                 } else {
                   14597:                     push(@{$name_to_host{$name}},$id);
                   14598:                 }
1.852     albertel 14599: 		$hostname{$id}=$name;
                   14600: 		$hostdom{$id}=$domain;
                   14601: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14602:                 if (defined($protocol)) {
                   14603:                     if ($protocol eq 'https') {
                   14604:                         $protocol{$id} = $protocol;
                   14605:                     } else {
                   14606:                         $protocol{$id} = 'http'; 
                   14607:                     }
1.968     raeburn  14608:                 } else {
1.969     raeburn  14609:                     $protocol{$id} = 'http';
1.968     raeburn  14610:                 }
1.1074    raeburn  14611:                 if (defined($intdom)) {
                   14612:                     $internetdom{$id} = $intdom;
                   14613:                 }
1.852     albertel 14614: 	    }
                   14615: 	}
                   14616:     }
1.864     albertel 14617:     
                   14618:     sub reset_hosts_info {
1.897     albertel 14619: 	&purge_remembered();
1.864     albertel 14620: 	&reset_domain_info();
                   14621: 	&reset_hosts_ip_info();
1.892     albertel 14622: 	undef(%name_to_host);
1.864     albertel 14623: 	undef(%hostname);
                   14624: 	undef(%hostdom);
                   14625: 	undef(%libserv);
                   14626: 	undef($loaded);
                   14627:     }
1.1       albertel 14628: 
1.852     albertel 14629:     sub load_hosts_tab {
1.1172.2.70  raeburn  14630: 	my ($ignore_cache,$nocache) = @_;
                   14631: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14632: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14633: 	my @config = <$config>;
                   14634: 	&parse_hosts_tab(\@config);
                   14635: 	close($config);
                   14636: 	$loaded=1;
1.1       albertel 14637:     }
1.852     albertel 14638: 
1.838     albertel 14639:     sub hostname {
1.852     albertel 14640: 	&load_hosts_tab() if (!$loaded);
                   14641: 
1.838     albertel 14642: 	my ($lonid) = @_;
                   14643: 	return $hostname{$lonid};
                   14644:     }
1.845     albertel 14645: 
1.838     albertel 14646:     sub all_hostnames {
1.852     albertel 14647: 	&load_hosts_tab() if (!$loaded);
                   14648: 
1.838     albertel 14649: 	return %hostname;
                   14650:     }
1.845     albertel 14651: 
1.888     albertel 14652:     sub all_names {
1.1172.2.70  raeburn  14653:         my ($ignore_cache,$nocache) = @_;
                   14654: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14655: 
                   14656: 	return %name_to_host;
                   14657:     }
                   14658: 
1.974     raeburn  14659:     sub all_host_domain {
                   14660:         &load_hosts_tab() if (!$loaded);
                   14661:         return %hostdom;
                   14662:     }
                   14663: 
1.845     albertel 14664:     sub is_library {
1.852     albertel 14665: 	&load_hosts_tab() if (!$loaded);
                   14666: 
1.845     albertel 14667: 	return exists($libserv{$_[0]});
                   14668:     }
                   14669: 
                   14670:     sub all_library {
1.852     albertel 14671: 	&load_hosts_tab() if (!$loaded);
                   14672: 
1.845     albertel 14673: 	return %libserv;
                   14674:     }
                   14675: 
1.1062    droeschl 14676:     sub unique_library {
                   14677: 	#2x reverse removes all hostnames that appear more than once
                   14678:         my %unique = reverse &all_library();
                   14679:         return reverse %unique;
                   14680:     }
                   14681: 
1.841     albertel 14682:     sub get_servers {
1.852     albertel 14683: 	&load_hosts_tab() if (!$loaded);
                   14684: 
1.841     albertel 14685: 	my ($domain,$type) = @_;
                   14686: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14687: 	                                          : %hostname;
                   14688: 	my %result;
1.842     albertel 14689: 	if (ref($domain) eq 'ARRAY') {
                   14690: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14691: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14692: 		    $result{$host} = $hostname;
                   14693: 		}
                   14694: 	    }
                   14695: 	} else {
                   14696: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14697: 		if ($hostdom{$host} eq $domain) {
                   14698: 		    $result{$host} = $hostname;
                   14699: 		}
1.841     albertel 14700: 	    }
                   14701: 	}
                   14702: 	return %result;
                   14703:     }
1.845     albertel 14704: 
1.1062    droeschl 14705:     sub get_unique_servers {
                   14706:         my %unique = reverse &get_servers(@_);
                   14707: 	return reverse %unique;
                   14708:     }
                   14709: 
1.844     albertel 14710:     sub host_domain {
1.852     albertel 14711: 	&load_hosts_tab() if (!$loaded);
                   14712: 
1.844     albertel 14713: 	my ($lonid) = @_;
                   14714: 	return $hostdom{$lonid};
                   14715:     }
                   14716: 
1.841     albertel 14717:     sub all_domains {
1.852     albertel 14718: 	&load_hosts_tab() if (!$loaded);
                   14719: 
1.841     albertel 14720: 	my %seen;
                   14721: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14722: 	return @uniq;
                   14723:     }
1.1074    raeburn  14724: 
                   14725:     sub internet_dom {
                   14726:         &load_hosts_tab() if (!$loaded);
                   14727: 
                   14728:         my ($lonid) = @_;
                   14729:         return $internetdom{$lonid};
                   14730:     }
1.1107    raeburn  14731: 
                   14732:     sub is_LC_dns {
                   14733:         &load_hosts_tab() if (!$loaded);
                   14734: 
                   14735:         my ($hostname) = @_;
                   14736:         return exists($LC_dns_serv{$hostname});
                   14737:     }
                   14738: 
1.1       albertel 14739: }
                   14740: 
1.847     albertel 14741: { 
                   14742:     my %iphost;
1.856     albertel 14743:     my %name_to_ip;
                   14744:     my %lonid_to_ip;
1.869     albertel 14745: 
1.847     albertel 14746:     sub get_hosts_from_ip {
                   14747: 	my ($ip) = @_;
                   14748: 	my %iphosts = &get_iphost();
                   14749: 	if (ref($iphosts{$ip})) {
                   14750: 	    return @{$iphosts{$ip}};
                   14751: 	}
                   14752: 	return;
1.839     albertel 14753:     }
1.864     albertel 14754:     
                   14755:     sub reset_hosts_ip_info {
                   14756: 	undef(%iphost);
                   14757: 	undef(%name_to_ip);
                   14758: 	undef(%lonid_to_ip);
                   14759:     }
1.856     albertel 14760: 
                   14761:     sub get_host_ip {
                   14762: 	my ($lonid) = @_;
                   14763: 	if (exists($lonid_to_ip{$lonid})) {
                   14764: 	    return $lonid_to_ip{$lonid};
                   14765: 	}
                   14766: 	my $name=&hostname($lonid);
                   14767:    	my $ip = gethostbyname($name);
                   14768: 	return if (!$ip || length($ip) ne 4);
                   14769: 	$ip=inet_ntoa($ip);
                   14770: 	$name_to_ip{$name}   = $ip;
                   14771: 	$lonid_to_ip{$lonid} = $ip;
                   14772: 	return $ip;
                   14773:     }
1.847     albertel 14774:     
                   14775:     sub get_iphost {
1.1172.2.70  raeburn  14776: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14777: 
1.869     albertel 14778: 	if (!$ignore_cache) {
                   14779: 	    if (%iphost) {
                   14780: 		return %iphost;
                   14781: 	    }
                   14782: 	    my ($ip_info,$cached)=
                   14783: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14784: 	    if ($cached) {
                   14785: 		%iphost      = %{$ip_info->[0]};
                   14786: 		%name_to_ip  = %{$ip_info->[1]};
                   14787: 		%lonid_to_ip = %{$ip_info->[2]};
                   14788: 		return %iphost;
                   14789: 	    }
                   14790: 	}
1.894     albertel 14791: 
                   14792: 	# get yesterday's info for fallback
                   14793: 	my %old_name_to_ip;
                   14794: 	my ($ip_info,$cached)=
                   14795: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14796: 	if ($cached) {
                   14797: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14798: 	}
                   14799: 
1.1172.2.70  raeburn  14800: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14801: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14802: 	    my $ip;
                   14803: 	    if (!exists($name_to_ip{$name})) {
                   14804: 		$ip = gethostbyname($name);
                   14805: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14806: 		    if (defined($old_name_to_ip{$name})) {
                   14807: 			$ip = $old_name_to_ip{$name};
                   14808: 			&logthis("Can't find $name defaulting to old $ip");
                   14809: 		    } else {
                   14810: 			&logthis("Name $name no IP found");
                   14811: 			next;
                   14812: 		    }
                   14813: 		} else {
                   14814: 		    $ip=inet_ntoa($ip);
1.847     albertel 14815: 		}
                   14816: 		$name_to_ip{$name} = $ip;
                   14817: 	    } else {
                   14818: 		$ip = $name_to_ip{$name};
1.653     albertel 14819: 	    }
1.888     albertel 14820: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14821: 		$lonid_to_ip{$id} = $ip;
                   14822: 	    }
                   14823: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14824: 	}
1.1172.2.70  raeburn  14825:         unless ($nocache) {
                   14826: 	    &do_cache_new('iphost','iphost',
                   14827: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14828: 		          48*60*60);
                   14829:         }
1.869     albertel 14830: 
1.847     albertel 14831: 	return %iphost;
1.598     albertel 14832:     }
                   14833: 
1.992     raeburn  14834:     #
                   14835:     #  Given a DNS returns the loncapa host name for that DNS 
                   14836:     # 
                   14837:     sub host_from_dns {
                   14838:         my ($dns) = @_;
                   14839:         my @hosts;
                   14840:         my $ip;
                   14841: 
1.993     raeburn  14842:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14843:             $ip = $name_to_ip{$dns};
                   14844:         }
                   14845:         if (!$ip) {
                   14846:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14847:             if (length($ip) == 4) { 
                   14848: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14849:             }
                   14850:         }
                   14851:         if ($ip) {
                   14852: 	    @hosts = get_hosts_from_ip($ip);
                   14853: 	    return $hosts[0];
                   14854:         }
                   14855:         return undef;
1.986     foxr     14856:     }
1.992     raeburn  14857: 
1.1074    raeburn  14858:     sub get_internet_names {
                   14859:         my ($lonid) = @_;
                   14860:         return if ($lonid eq '');
                   14861:         my ($idnref,$cached)=
                   14862:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14863:         if ($cached) {
                   14864:             return $idnref;
                   14865:         }
                   14866:         my $ip = &get_host_ip($lonid);
                   14867:         my @hosts = &get_hosts_from_ip($ip);
                   14868:         my %iphost = &get_iphost();
                   14869:         my (@idns,%seen);
                   14870:         foreach my $id (@hosts) {
                   14871:             my $dom = &host_domain($id);
                   14872:             my $prim_id = &domain($dom,'primary');
                   14873:             my $prim_ip = &get_host_ip($prim_id);
                   14874:             next if ($seen{$prim_ip});
                   14875:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14876:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14877:                     my $intdom = &internet_dom($id);
                   14878:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14879:                         push(@idns,$intdom);
                   14880:                     }
                   14881:                 }
                   14882:             }
                   14883:             $seen{$prim_ip} = 1;
                   14884:         }
1.1172.2.23  raeburn  14885:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14886:     }
                   14887: 
1.986     foxr     14888: }
                   14889: 
1.1079    raeburn  14890: sub all_loncaparevs {
1.1172.2.39  raeburn  14891:     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  14892: }
                   14893: 
1.1172.2.27  raeburn  14894: # ------------------------------------------------------- Read loncaparev table
                   14895: {
                   14896:     sub load_loncaparevs {
                   14897:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14898:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14899:                 while (my $configline=<$config>) {
                   14900:                     chomp($configline);
                   14901:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14902:                     $loncaparevs{$hostid}=$loncaparev;
                   14903:                 }
                   14904:                 close($config);
                   14905:             }
                   14906:         }
                   14907:     }
                   14908: }
                   14909: 
                   14910: # ----------------------------------------------------- Read serverhostID table
                   14911: {
                   14912:     sub load_serverhomeIDs {
                   14913:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14914:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14915:                 while (my $configline=<$config>) {
                   14916:                     chomp($configline);
                   14917:                     my ($name,$id)=split(/:/,$configline);
                   14918:                     $serverhomeIDs{$name}=$id;
                   14919:                 }
                   14920:                 close($config);
                   14921:             }
                   14922:         }
                   14923:     }
                   14924: }
                   14925: 
                   14926: 
1.862     albertel 14927: BEGIN {
                   14928: 
                   14929: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14930:     unless ($readit) {
                   14931: {
                   14932:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14933:     %perlvar = (%perlvar,%{$configvars});
                   14934: }
                   14935: 
                   14936: 
1.1       albertel 14937: # ------------------------------------------------------ Read spare server file
                   14938: {
1.1172.2.96  raeburn  14939:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14940: 
                   14941:     while (my $configline=<$config>) {
                   14942:        chomp($configline);
1.284     matthew  14943:        if ($configline) {
1.784     albertel 14944: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14945: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14946: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14947:        }
                   14948:     }
1.448     albertel 14949:     close($config);
1.1       albertel 14950: }
1.11      www      14951: # ------------------------------------------------------------ Read permissions
                   14952: {
1.1172.2.96  raeburn  14953:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14954: 
                   14955:     while (my $configline=<$config>) {
1.448     albertel 14956: 	chomp($configline);
                   14957: 	if ($configline) {
                   14958: 	    my ($role,$perm)=split(/ /,$configline);
                   14959: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14960: 	}
1.11      www      14961:     }
1.448     albertel 14962:     close($config);
1.11      www      14963: }
                   14964: 
                   14965: # -------------------------------------------- Read plain texts for permissions
                   14966: {
1.1172.2.96  raeburn  14967:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14968: 
                   14969:     while (my $configline=<$config>) {
1.448     albertel 14970: 	chomp($configline);
                   14971: 	if ($configline) {
1.742     raeburn  14972: 	    my ($short,@plain)=split(/:/,$configline);
                   14973:             %{$prp{$short}} = ();
                   14974: 	    if (@plain > 0) {
                   14975:                 $prp{$short}{'std'} = $plain[0];
                   14976:                 for (my $i=1; $i<@plain; $i++) {
                   14977:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14978:                 }
                   14979:             }
1.448     albertel 14980: 	}
1.135     www      14981:     }
1.448     albertel 14982:     close($config);
1.135     www      14983: }
                   14984: 
                   14985: # ---------------------------------------------------------- Read package table
                   14986: {
1.1172.2.96  raeburn  14987:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14988: 
                   14989:     while (my $configline=<$config>) {
1.483     albertel 14990: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14991: 	chomp($configline);
                   14992: 	my ($short,$plain)=split(/:/,$configline);
                   14993: 	my ($pack,$name)=split(/\&/,$short);
                   14994: 	if ($plain ne '') {
                   14995: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14996: 	    $packagetab{$short}=$plain; 
                   14997: 	}
1.11      www      14998:     }
1.448     albertel 14999:     close($config);
1.329     matthew  15000: }
                   15001: 
1.1172.2.27  raeburn  15002: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15003: 
1.1172.2.27  raeburn  15004: &load_loncaparevs();
                   15005: 
                   15006: # ------------------------------------------------------- Read serverhostID table
                   15007: 
                   15008: &load_serverhomeIDs();
1.1074    raeburn  15009: 
1.1172.2.27  raeburn  15010: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15011: {
                   15012:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15013:     if (-e $file) {
                   15014:         my $parser = HTML::LCParser->new($file);
                   15015:         while (my $token = $parser->get_token()) {
                   15016:             if ($token->[0] eq 'S') {
                   15017:                 my $item = $token->[1];
                   15018:                 my $name = $token->[2]{'name'};
                   15019:                 my $value = $token->[2]{'value'};
                   15020:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15021:                     my $release = $parser->get_text();
                   15022:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15023:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15024:                 }
                   15025:             }
                   15026:         }
                   15027:     }
1.1073    raeburn  15028: }
                   15029: 
1.1138    raeburn  15030: # ---------------------------------------------------------- Read managers table
                   15031: {
                   15032:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15033:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15034:             while (my $configline=<$config>) {
                   15035:                 chomp($configline);
                   15036:                 next if ($configline =~ /^\#/);
                   15037:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15038:                     $managerstab{$configline} = 1;
                   15039:                 }
                   15040:             }
                   15041:             close($config);
                   15042:         }
                   15043:     }
                   15044: }
                   15045: 
1.329     matthew  15046: # ------------- set up temporary directory
                   15047: {
1.1117    foxr     15048:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15049: 
1.11      www      15050: }
                   15051: 
1.1172.2.104  raeburn  15052: # ------------- set default texengine (domain default overrides this)
                   15053: {
                   15054:     $deftex = LONCAPA::texengine();
                   15055: }
                   15056: 
1.1172.2.114  raeburn  15057: # ------------- set default minimum length for passwords for internal auth users
                   15058: {
                   15059:     $passwdmin = LONCAPA::passwd_min();
                   15060: }
                   15061: 
1.794     albertel 15062: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15063: 				'compress_threshold'=> 20_000,
                   15064:  			        });
1.185     www      15065: 
1.281     www      15066: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15067: $dumpcount=0;
1.958     www      15068: $locknum=0;
1.22      www      15069: 
1.163     harris41 15070: &logtouch();
1.672     albertel 15071: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15072: $readit=1;
1.564     albertel 15073:     {
                   15074: 	use integer;
                   15075: 	my $test=(2**32)+1;
1.568     albertel 15076: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15077: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15078:     }
1.195     www      15079: }
1.1       albertel 15080: }
1.179     www      15081: 
1.1       albertel 15082: 1;
1.191     harris41 15083: __END__
                   15084: 
1.243     albertel 15085: =pod
                   15086: 
1.191     harris41 15087: =head1 NAME
                   15088: 
1.243     albertel 15089: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15090: 
                   15091: =head1 SYNOPSIS
                   15092: 
1.243     albertel 15093: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15094: 
                   15095:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15096: 
1.243     albertel 15097: Common parameters:
                   15098: 
                   15099: =over 4
                   15100: 
                   15101: =item *
                   15102: 
                   15103: $uname : an internal username (if $cname expecting a course Id specifically)
                   15104: 
                   15105: =item *
                   15106: 
                   15107: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15108: 
                   15109: =item *
                   15110: 
                   15111: $symb : a resource instance identifier
                   15112: 
                   15113: =item *
                   15114: 
                   15115: $namespace : the name of a .db file that contains the data needed or
                   15116: being set.
                   15117: 
                   15118: =back
                   15119: 
1.394     bowersj2 15120: =head1 OVERVIEW
1.191     harris41 15121: 
1.394     bowersj2 15122: lonnet provides subroutines which interact with the
                   15123: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15124: about classes, users, and resources.
1.243     albertel 15125: 
                   15126: For many of these objects you can also use this to store data about
                   15127: them or modify them in various ways.
1.191     harris41 15128: 
1.394     bowersj2 15129: =head2 Symbs
1.191     harris41 15130: 
1.394     bowersj2 15131: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15132: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15133: map, the resource number of the resource in the map, and the URL of
                   15134: the resource itself. The latter is somewhat redundant, but might help
                   15135: if maps change.
                   15136: 
                   15137: An example is
                   15138: 
                   15139:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15140: 
                   15141: The respective map entry is
                   15142: 
                   15143:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15144:   title="Problem 2">
                   15145:  </resource>
                   15146: 
                   15147: Symbs are used by the random number generator, as well as to store and
                   15148: restore data specific to a certain instance of for example a problem.
                   15149: 
                   15150: =head2 Storing And Retrieving Data
                   15151: 
                   15152: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15153: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15154: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15155: is is the non-critical message twin of cstore. These functions are for
                   15156: handlers to store a perl hash to a user's permanent data space in an
                   15157: easy manner, and to retrieve it again on another call. It is expected
                   15158: that a handler would use this once at the beginning to retrieve data,
                   15159: and then again once at the end to send only the new data back.
                   15160: 
                   15161: The data is stored in the user's data directory on the user's
                   15162: homeserver under the ID of the course.
                   15163: 
                   15164: The hash that is returned by restore will have all of the previous
                   15165: value for all of the elements of the hash.
                   15166: 
                   15167: Example:
                   15168: 
                   15169:  #creating a hash
                   15170:  my %hash;
                   15171:  $hash{'foo'}='bar';
                   15172: 
                   15173:  #storing it
                   15174:  &Apache::lonnet::cstore(\%hash);
                   15175: 
                   15176:  #changing a value
                   15177:  $hash{'foo'}='notbar';
                   15178: 
                   15179:  #adding a new value
                   15180:  $hash{'bar'}='foo';
                   15181:  &Apache::lonnet::cstore(\%hash);
                   15182: 
                   15183:  #retrieving the hash
                   15184:  my %history=&Apache::lonnet::restore();
                   15185: 
                   15186:  #print the hash
                   15187:  foreach my $key (sort(keys(%history))) {
                   15188:    print("\%history{$key} = $history{$key}");
                   15189:  }
                   15190: 
                   15191: Will print out:
1.191     harris41 15192: 
1.394     bowersj2 15193:  %history{1:foo} = bar
                   15194:  %history{1:keys} = foo:timestamp
                   15195:  %history{1:timestamp} = 990455579
                   15196:  %history{2:bar} = foo
                   15197:  %history{2:foo} = notbar
                   15198:  %history{2:keys} = foo:bar:timestamp
                   15199:  %history{2:timestamp} = 990455580
                   15200:  %history{bar} = foo
                   15201:  %history{foo} = notbar
                   15202:  %history{timestamp} = 990455580
                   15203:  %history{version} = 2
                   15204: 
                   15205: Note that the special hash entries C<keys>, C<version> and
                   15206: C<timestamp> were added to the hash. C<version> will be equal to the
                   15207: total number of versions of the data that have been stored. The
                   15208: C<timestamp> attribute will be the UNIX time the hash was
                   15209: stored. C<keys> is available in every historical section to list which
                   15210: keys were added or changed at a specific historical revision of a
                   15211: hash.
                   15212: 
                   15213: B<Warning>: do not store the hash that restore returns directly. This
                   15214: will cause a mess since it will restore the historical keys as if the
                   15215: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15216: 
1.394     bowersj2 15217: Calling convention:
1.191     harris41 15218: 
1.1172.2.27  raeburn  15219:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15220:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15221: 
1.394     bowersj2 15222: For more detailed information, see lonnet specific documentation.
1.191     harris41 15223: 
1.394     bowersj2 15224: =head1 RETURN MESSAGES
1.191     harris41 15225: 
1.394     bowersj2 15226: =over 4
1.191     harris41 15227: 
1.394     bowersj2 15228: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15229: 
1.394     bowersj2 15230: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15231: when the connection is brought back up
1.191     harris41 15232: 
1.394     bowersj2 15233: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15234: for later delivery
1.191     harris41 15235: 
1.967     bisitz   15236: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15237: 
1.394     bowersj2 15238: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15239: that was requested
1.191     harris41 15240: 
1.243     albertel 15241: =back
1.191     harris41 15242: 
1.243     albertel 15243: =head1 PUBLIC SUBROUTINES
1.191     harris41 15244: 
1.243     albertel 15245: =head2 Session Environment Functions
1.191     harris41 15246: 
1.243     albertel 15247: =over 4
1.191     harris41 15248: 
1.394     bowersj2 15249: =item * 
                   15250: X<appenv()>
1.949     raeburn  15251: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15252: the user envirnoment file, and will be restored for each access this
1.620     albertel 15253: user makes during this session, also modifies the %env for the current
1.949     raeburn  15254: process. Optional rolesarrayref - if defined contains a reference to an array
                   15255: of roles which are exempt from the restriction on modifying user.role entries 
                   15256: in the user's environment.db and in %env.    
1.191     harris41 15257: 
                   15258: =item *
1.394     bowersj2 15259: X<delenv()>
1.987     raeburn  15260: B<delenv($delthis,$regexp)>: removes all items from the session
                   15261: environment file that begin with $delthis. If the 
                   15262: optional second arg - $regexp - is true, $delthis is treated as a 
                   15263: regular expression, otherwise \Q$delthis\E is used. 
                   15264: The values are also deleted from the current processes %env.
1.191     harris41 15265: 
1.795     albertel 15266: =item * get_env_multiple($name) 
                   15267: 
                   15268: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15269: values may be defined and end up as an array ref.
                   15270: 
                   15271: returns an array of values
                   15272: 
1.243     albertel 15273: =back
                   15274: 
                   15275: =head2 User Information
1.191     harris41 15276: 
1.243     albertel 15277: =over 4
1.191     harris41 15278: 
                   15279: =item *
1.394     bowersj2 15280: X<queryauthenticate()>
                   15281: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15282: authentication scheme
                   15283: 
                   15284: =item *
1.394     bowersj2 15285: X<authenticate()>
1.1073    raeburn  15286: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15287: authenticate user from domain's lib servers (first use the current
                   15288: one). C<$upass> should be the users password.
1.1073    raeburn  15289: $checkdefauth is optional (value is 1 if a check should be made to
                   15290:    authenticate user using default authentication method, and allow
                   15291:    account creation if username does not have account in the domain).
                   15292: $clientcancheckhost is optional (value is 1 if checking whether the
                   15293:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15294: 
                   15295: =item *
1.394     bowersj2 15296: X<homeserver()>
                   15297: B<homeserver($uname,$udom)>: find the server which has
                   15298: the user's directory and files (there must be only one), this caches
                   15299: the answer, and also caches if there is a borken connection.
1.191     harris41 15300: 
                   15301: =item *
1.394     bowersj2 15302: X<idget()>
                   15303: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15304: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15305: username, and only 1 username per ID in a specific domain) (returns
                   15306: hash: id=>name,id=>name)
1.191     harris41 15307: 
                   15308: =item *
1.394     bowersj2 15309: X<idrget()>
                   15310: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15311: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15312: 
                   15313: =item *
1.394     bowersj2 15314: X<idput()>
                   15315: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15316: 
                   15317: =item *
1.394     bowersj2 15318: X<rolesinit()>
1.1169    droeschl 15319: B<rolesinit($udom,$username)>: get user privileges.
                   15320: returns user role, first access and timer interval hashes
1.243     albertel 15321: 
                   15322: =item *
1.1171    droeschl 15323: X<privileged()>
                   15324: B<privileged($username,$domain)>: returns a true if user has a
                   15325: privileged and active role (i.e. su or dc), false otherwise.
                   15326: 
                   15327: =item *
1.551     albertel 15328: X<getsection()>
                   15329: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15330: course $cname, return section name/number or '' for "not in course"
                   15331: and '-1' for "no section"
                   15332: 
                   15333: =item *
1.394     bowersj2 15334: X<userenvironment()>
                   15335: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15336: passed in @what from the requested user's environment, returns a hash
                   15337: 
1.858     raeburn  15338: =item * 
                   15339: X<userlog_query()>
1.859     albertel 15340: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15341: activity.log file. %filters defines filters applied when parsing the
                   15342: log file. These can be start or end timestamps, or the type of action
                   15343: - log to look for Login or Logout events, check for Checkin or
                   15344: Checkout, role for role selection. The response is in the form
                   15345: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15346: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15347: 
1.243     albertel 15348: =back
                   15349: 
                   15350: =head2 User Roles
                   15351: 
                   15352: =over 4
                   15353: 
                   15354: =item *
                   15355: 
1.1172.2.65  raeburn  15356: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15357: returns codes for allowed actions.
                   15358: 
                   15359: The first argument is required, all others are optional.
                   15360: 
                   15361: $priv is the privilege being checked.
                   15362: $uri contains additional information about what is being checked for access (e.g.,
                   15363: URL, course ID etc.).
                   15364: $symb is the unique resource instance identifier in a course; if needed,
                   15365: but not provided, it will be retrieved via a call to &symbread().
                   15366: $role is the role for which a priv is being checked (only used if priv is evb).
                   15367: $clientip is the user's IP address (only used when checking for access to portfolio
                   15368: files).
                   15369: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15370: prevents recursive calls to &allowed.
                   15371: 
1.243     albertel 15372:  F: full access
                   15373:  U,I,K: authentication modes (cxx only)
                   15374:  '': forbidden
                   15375:  1: user needs to choose course
                   15376:  2: browse allowed
1.766     albertel 15377:  A: passphrase authentication needed
1.1172.2.65  raeburn  15378:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15379:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15380: 
                   15381: =item *
                   15382: 
1.1172.2.13  raeburn  15383: constructaccess($url,$setpriv) : check for access to construction space URL
                   15384: 
                   15385: See if the owner domain and name in the URL match those in the
                   15386: expected environment.  If so, return three element list
                   15387: ($ownername,$ownerdomain,$ownerhome).
                   15388: 
                   15389: Otherwise return the null string.
                   15390: 
                   15391: If second argument 'setpriv' is true, it assigns the privileges,
                   15392: and returns the same three element list, unless the owner has
                   15393: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15394: in which case the null string is returned.
                   15395: 
                   15396: =item *
                   15397: 
1.1172.2.84  raeburn  15398: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15399: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15400: for system, domain, and course level. $uname and $udom are optional (current
                   15401: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15402: 
                   15403: =item *
                   15404: 
1.988     raeburn  15405: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15406: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15407: $type is Course (default) or Community.
1.988     raeburn  15408: If $forcedefault evaluates to true, text returned will be default 
                   15409: text for $type. Otherwise, if this is a course, the text returned 
                   15410: will be a custom name for the role (if defined in the course's 
                   15411: environment).  If no custom name is defined the default is returned.
                   15412:    
1.832     raeburn  15413: =item *
                   15414: 
1.1172.2.23  raeburn  15415: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15416: All arguments are optional. Returns a hash of a roles, either for
                   15417: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15418: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15419: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15420: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15421: For each key, value is set to colon-separated start and end times for
                   15422: the role.  If no username and domain are specified, will default to
1.934     raeburn  15423: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15424: of role statuses (active, future or previous), roles 
                   15425: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15426: to restrict the list of roles reported. If no array ref is 
                   15427: provided for types, will default to return only active roles.
1.834     albertel 15428: 
1.1172.2.13  raeburn  15429: =item *
                   15430: 
                   15431: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15432: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15433: 
                   15434: Additional optional arguments are: $type (if role checking is to be restricted
                   15435: to certain user status types -- previous (expired roles), active (currently
                   15436: available roles) or future (roles available in the future), and
                   15437: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15438: have active Domain Coordinator role in course's domain or in additional
                   15439: domains (specified in 'Domains to check for privileged users' in course
                   15440: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15441: 
                   15442: =item *
                   15443: 
                   15444: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15445: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15446: $possdomains and $possroles are optional array refs -- to domains to check and
                   15447: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15448: users' roles.db to check for a dc or su role in any domain. This can be
                   15449: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15450: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15451: this then allows &privileged_by_domain() to be used, which caches the identity
                   15452: of privileged users, eliminating the need for repeated calls to &dump().
                   15453: 
                   15454: =item *
                   15455: 
                   15456: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15457: where the outer hash keys are domains specified in the $possdomains array ref,
                   15458: next inner hash keys are privileged roles specified in the $roles array ref,
                   15459: and the innermost hash contains key = value pairs for username:domain = end:start
                   15460: for active or future "privileged" users with that role in that domain. To avoid
                   15461: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15462: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15463: 
1.243     albertel 15464: =back
                   15465: 
                   15466: =head2 User Modification
                   15467: 
                   15468: =over 4
                   15469: 
                   15470: =item *
                   15471: 
1.957     raeburn  15472: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15473: user for the level given by URL.  Optional start and end dates (leave empty
                   15474: string or zero for "no date")
1.191     harris41 15475: 
                   15476: =item *
                   15477: 
1.243     albertel 15478: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15479: change a users, password, possible return values are: ok,
                   15480: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15481: refused
1.191     harris41 15482: 
                   15483: =item *
                   15484: 
1.243     albertel 15485: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15486: 
                   15487: =item *
                   15488: 
1.1058    raeburn  15489: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15490:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15491: 
                   15492: will update user information (firstname,middlename,lastname,generation,
                   15493: permanentemail), and if forceid is true, student/employee ID also.
                   15494: A user's institutional affiliation(s) can also be updated.
                   15495: User information fields will not be overwritten with empty entries 
                   15496: unless the field is included in the $candelete array reference.
                   15497: This array is included when a single user is modified via "Manage Users",
                   15498: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15499: 
                   15500: =item *
                   15501: 
1.286     matthew  15502: modifystudent
                   15503: 
1.957     raeburn  15504: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15505: The course id is resolved based on the current user's environment.  
                   15506: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15507: associated with a course.
                   15508: 
1.297     matthew  15509: This call is essentially a wrapper for lonnet::modifyuser and
                   15510: lonnet::modify_student_enrollment
1.286     matthew  15511: 
                   15512: Inputs: 
                   15513: 
                   15514: =over 4
                   15515: 
1.957     raeburn  15516: =item B<$udom> Student's loncapa domain
1.286     matthew  15517: 
1.957     raeburn  15518: =item B<$uname> Student's loncapa login name
1.286     matthew  15519: 
1.964     bisitz   15520: =item B<$uid> Student/Employee ID
1.286     matthew  15521: 
1.957     raeburn  15522: =item B<$umode> Student's authentication mode
1.286     matthew  15523: 
1.957     raeburn  15524: =item B<$upass> Student's password
1.286     matthew  15525: 
1.957     raeburn  15526: =item B<$first> Student's first name
1.286     matthew  15527: 
1.957     raeburn  15528: =item B<$middle> Student's middle name
1.286     matthew  15529: 
1.957     raeburn  15530: =item B<$last> Student's last name
1.286     matthew  15531: 
1.957     raeburn  15532: =item B<$gene> Student's generation
1.286     matthew  15533: 
1.957     raeburn  15534: =item B<$usec> Student's section in course
1.286     matthew  15535: 
                   15536: =item B<$end> Unix time of the roles expiration
                   15537: 
                   15538: =item B<$start> Unix time of the roles start date
                   15539: 
                   15540: =item B<$forceid> If defined, allow $uid to be changed
                   15541: 
                   15542: =item B<$desiredhome> server to use as home server for student
                   15543: 
1.957     raeburn  15544: =item B<$email> Student's permanent e-mail address
                   15545: 
                   15546: =item B<$type> Type of enrollment (auto or manual)
                   15547: 
1.963     raeburn  15548: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15549: 
                   15550: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15551: 
1.963     raeburn  15552: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15553: 
1.963     raeburn  15554: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15555: 
1.1172.2.19  raeburn  15556: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15557: 
                   15558: =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  15559: 
1.286     matthew  15560: =back
1.297     matthew  15561: 
                   15562: =item *
                   15563: 
                   15564: modify_student_enrollment
                   15565: 
1.1172.2.31  raeburn  15566: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15567: 'role.request.course' must be defined for this function to proceed.
                   15568: 
                   15569: Inputs:
                   15570: 
                   15571: =over 4
                   15572: 
1.1172.2.31  raeburn  15573: =item $udom, student's domain
1.297     matthew  15574: 
1.1172.2.31  raeburn  15575: =item $uname, student's name
1.297     matthew  15576: 
1.1172.2.31  raeburn  15577: =item $uid, student's user id
1.297     matthew  15578: 
1.1172.2.31  raeburn  15579: =item $first, student's first name
1.297     matthew  15580: 
                   15581: =item $middle
                   15582: 
                   15583: =item $last
                   15584: 
                   15585: =item $gene
                   15586: 
                   15587: =item $usec
                   15588: 
                   15589: =item $end
                   15590: 
                   15591: =item $start
                   15592: 
1.957     raeburn  15593: =item $type
                   15594: 
                   15595: =item $locktype
                   15596: 
                   15597: =item $cid
                   15598: 
                   15599: =item $selfenroll
                   15600: 
                   15601: =item $context
                   15602: 
1.1172.2.19  raeburn  15603: =item $credits, number of credits student will earn from this class
                   15604: 
1.1172.2.76  raeburn  15605: =item $instsec, institutional course section code for student
                   15606: 
1.297     matthew  15607: =back
                   15608: 
1.191     harris41 15609: 
                   15610: =item *
                   15611: 
1.243     albertel 15612: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15613: custom role; give a custom role to a user for the level given by URL.  Specify
                   15614: name and domain of role author, and role name
1.191     harris41 15615: 
                   15616: =item *
                   15617: 
1.243     albertel 15618: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15619: 
                   15620: =item *
                   15621: 
1.243     albertel 15622: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15623: 
                   15624: =back
                   15625: 
                   15626: =head2 Course Infomation
                   15627: 
                   15628: =over 4
1.191     harris41 15629: 
                   15630: =item *
                   15631: 
1.1118    foxr     15632: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15633: specified course id, including all environment settings for the
                   15634: course, the description of the course will be in the hash under the
                   15635: key 'description'
1.191     harris41 15636: 
1.1118    foxr     15637: $options is an optional parameter that if supplied is a hash reference that controls
                   15638: what how this function works.  It has the following key/values:
                   15639: 
                   15640: =over 4
                   15641: 
                   15642: =item freshen_cache
                   15643: 
                   15644: If defined, and the environment cache for the course is valid, it is 
                   15645: returned in the returned hash.
                   15646: 
                   15647: =item one_time
                   15648: 
                   15649: If defined, the last cache time is set to _now_
                   15650: 
                   15651: =item user
                   15652: 
                   15653: If defined, the supplied username is used instead of the current user.
                   15654: 
                   15655: 
                   15656: =back
                   15657: 
1.191     harris41 15658: =item *
                   15659: 
1.624     albertel 15660: resdata($name,$domain,$type,@which) : request for current parameter
                   15661: setting for a specific $type, where $type is either 'course' or 'user',
                   15662: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15663: answers for 10 minutes.
1.243     albertel 15664: 
1.877     foxr     15665: =item *
                   15666: 
                   15667: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15668: data base, returning a hash that is keyed by the resource name and has
                   15669: values that are the resource value.  I believe that the timestamps and
                   15670: versions are also returned.
                   15671: 
1.1172.2.31  raeburn  15672: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15673: supplemental content area. This routine caches the number of files for
                   15674: 10 minutes.
                   15675: 
1.243     albertel 15676: =back
                   15677: 
                   15678: =head2 Course Modification
                   15679: 
                   15680: =over 4
1.191     harris41 15681: 
                   15682: =item *
                   15683: 
1.243     albertel 15684: writecoursepref($courseid,%prefs) : write preferences (environment
                   15685: database) for a course
1.191     harris41 15686: 
                   15687: =item *
                   15688: 
1.1011    raeburn  15689: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15690: 
                   15691: =item *
                   15692: 
1.1038    raeburn  15693: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15694: 
1.1167    droeschl 15695: =item *
                   15696: 
                   15697: is_course($courseid), is_course($cdom, $cnum)
                   15698: 
                   15699: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15700: two component version $cdom, $cnum. It checks if the specified course exists.
                   15701: 
                   15702: Returns:
                   15703:     undef if the course doesn't exist, otherwise
                   15704:     in scalar context the combined courseid.
                   15705:     in list context the two components of the course identifier, domain and 
                   15706:     courseid.    
                   15707: 
1.243     albertel 15708: =back
                   15709: 
1.1172.2.109  raeburn  15710: =head2 Bubblesheet Configuration
                   15711: 
                   15712: =over 4
                   15713: 
                   15714: =item *
                   15715: 
                   15716: get_scantron_config($which)
                   15717: 
                   15718: $which - the name of the configuration to parse from the file.
                   15719: 
                   15720: Parses and returns the bubblesheet configuration line selected as a
                   15721: hash of configuration file fields.
                   15722: 
                   15723: 
                   15724: Returns:
                   15725:     If the named configuration is not in the file, an empty
                   15726:     hash is returned.
                   15727: 
                   15728:     a hash with the fields
                   15729:       name         - internal name for the this configuration setup
                   15730:       description  - text to display to operator that describes this config
                   15731:       CODElocation - if 0 or the string 'none'
                   15732:                           - no CODE exists for this config
                   15733:                      if -1 || the string 'letter'
                   15734:                           - a CODE exists for this config and is
                   15735:                             a string of letters
                   15736:                      Unsupported value (but planned for future support)
                   15737:                           if a positive integer
                   15738:                                - The CODE exists as the first n items from
                   15739:                                  the question section of the form
                   15740:                           if the string 'number'
                   15741:                                - The CODE exists for this config and is
                   15742:                                  a string of numbers
                   15743:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15744:                      the CODE starts
                   15745:       CODElength  - length of the CODE
                   15746:       IDstart     - column where the student/employee ID starts
                   15747:       IDlength    - length of the student/employee ID info
                   15748:       Qstart      - column where the information from the bubbled
                   15749:                     'questions' start
                   15750:       Qlength     - number of columns comprising a single bubble line from
                   15751:                     the sheet. (usually either 1 or 10)
                   15752:       Qon         - either a single character representing the character used
                   15753:                     to signal a bubble was chosen in the positional setup, or
                   15754:                     the string 'letter' if the letter of the chosen bubble is
                   15755:                     in the final, or 'number' if a number representing the
                   15756:                     chosen bubble is in the file (1->A 0->J)
                   15757:       Qoff        - the character used to represent that a bubble was
                   15758:                     left blank
                   15759:       PaperID     - if the scanning process generates a unique number for each
                   15760:                     sheet scanned the column that this ID number starts in
                   15761:       PaperIDlength - number of columns that comprise the unique ID number
                   15762:                       for the sheet of paper
                   15763:       FirstName   - column that the first name starts in
                   15764:       FirstNameLength - number of columns that the first name spans
                   15765:       LastName    - column that the last name starts in
                   15766:       LastNameLength - number of columns that the last name spans
                   15767:       BubblesPerRow - number of bubbles available in each row used to
                   15768:                       bubble an answer. (If not specified, 10 assumed).
                   15769: 
                   15770: 
                   15771: =item *
                   15772: 
                   15773: get_scantronformat_file($cdom)
                   15774: 
                   15775: $cdom - the course's domain (optional); if not supplied, uses
                   15776: domain for current $env{'request.course.id'}.
                   15777: 
                   15778: Returns an array containing lines from the scantron format file for
                   15779: the domain of the course.
                   15780: 
                   15781: If a url for a custom.tab file is listed in domain's configuration.db,
                   15782: lines are from this file.
                   15783: 
                   15784: Otherwise, if a default.tab has been published in RES space by the
                   15785: domainconfig user, lines are from this file.
                   15786: 
                   15787: Otherwise, fall back to getting lines from the legacy file on the
                   15788: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15789: 
                   15790: =back
                   15791: 
1.243     albertel 15792: =head2 Resource Subroutines
                   15793: 
                   15794: =over 4
1.191     harris41 15795: 
                   15796: =item *
                   15797: 
1.243     albertel 15798: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15799: 
                   15800: =item *
                   15801: 
1.243     albertel 15802: repcopy($filename) : subscribes to the requested file, and attempts to
                   15803: replicate from the owning library server, Might return
1.607     raeburn  15804: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15805: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15806: resource. Expects the local filesystem pathname
                   15807: (/home/httpd/html/res/....)
                   15808: 
                   15809: =back
                   15810: 
                   15811: =head2 Resource Information
                   15812: 
                   15813: =over 4
1.191     harris41 15814: 
                   15815: =item *
                   15816: 
1.1172.2.28  raeburn  15817: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15818: and returns the value of a variety of different possible values,
                   15819: $varname should be a request string, and the other parameters can be
                   15820: used to specify who and what one is asking about. Ordinarily, $cid 
                   15821: does not need to be specified, as it is retrived from 
                   15822: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15823: within lonuserstate::loadmap() when initializing a course, before
                   15824: $env{'request.course.id'} has been set, so it needs to be provided
                   15825: in that one case.
1.243     albertel 15826: 
                   15827: Possible values for $varname are environment.lastname (or other item
                   15828: from the envirnment hash), user.name (or someother aspect about the
                   15829: user), resource.0.maxtries (or some other part and parameter of a
                   15830: resource)
1.204     albertel 15831: 
                   15832: =item *
                   15833: 
1.243     albertel 15834: directcondval($number) : get current value of a condition; reads from a state
                   15835: string
1.204     albertel 15836: 
                   15837: =item *
                   15838: 
1.243     albertel 15839: condval($condidx) : value of condition index based on state
1.204     albertel 15840: 
                   15841: =item *
                   15842: 
1.243     albertel 15843: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15844: resource's metadata, $what should be either a specific key, or either
                   15845: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15846: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15847: 
                   15848: this function automatically caches all requests
1.191     harris41 15849: 
                   15850: =item *
                   15851: 
1.243     albertel 15852: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15853: network of library servers; returns file handle of where SQL and regex results
                   15854: will be stored for query
1.191     harris41 15855: 
                   15856: =item *
                   15857: 
1.1172.2.66  raeburn  15858: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15859: return symbolic list entry (all arguments optional).
                   15860: 
                   15861: Args: filename is the filename (including path) for the file for which a symb
                   15862: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15863: to check access status if more than one resource was found in the bighash
                   15864: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15865: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15866: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15867: cause possible symbs to be checked to determine if they are subject to content
                   15868: blocking, if so they will not be included as possible symbs; possibles is a
                   15869: ref to a hash, which, as a side effect, will be populated with all possible
                   15870: symbs (content blocking not tested).
                   15871: 
1.243     albertel 15872: returns the data handle
1.191     harris41 15873: 
                   15874: =item *
                   15875: 
1.1172.2.17  raeburn  15876: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15877: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15878: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15879: on failure, user must be in a course, as it assumes the existence of
                   15880: the course initial hash, and uses $env('request.course.id'}.  The third
                   15881: arg is an optional reference to a scalar.  If this arg is passed in the
                   15882: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15883: encrypted; otherwise it will be null.
1.243     albertel 15884: 
1.191     harris41 15885: =item *
                   15886: 
1.243     albertel 15887: symbclean($symb) : removes versions numbers from a symb, returns the
                   15888: cleaned symb
1.191     harris41 15889: 
                   15890: =item *
                   15891: 
1.243     albertel 15892: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15893: course map, user must be in a course for it to work.
1.191     harris41 15894: 
                   15895: =item *
                   15896: 
1.243     albertel 15897: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15898: 
                   15899: =item *
                   15900: 
1.243     albertel 15901: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15902: a random seed, all arguments are optional, if they aren't sent it uses the
                   15903: environment to derive them. Note: if symb isn't sent and it can't get one
                   15904: from &symbread it will use the current time as its return value
1.191     harris41 15905: 
                   15906: =item *
                   15907: 
1.243     albertel 15908: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15909: unfakeable, receipt
1.191     harris41 15910: 
                   15911: =item *
                   15912: 
1.620     albertel 15913: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15914: 
                   15915: =item *
                   15916: 
1.243     albertel 15917: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15918: 
                   15919: =item *
                   15920: 
1.243     albertel 15921: 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 15922: 
                   15923: =item *
                   15924: 
1.243     albertel 15925: 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 15926: 
                   15927: =item *
                   15928: 
1.243     albertel 15929: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15930: 
                   15931: =item *
                   15932: 
1.243     albertel 15933: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15934: forcing spreadsheet to reevaluate the resource scores next time.
                   15935: 
1.1172.2.13  raeburn  15936: =item *
                   15937: 
                   15938: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15939: when viewing in course context.
                   15940: 
                   15941:  input: six args -- filename (decluttered), course number, course domain,
                   15942:                     url, symb (if registered) and group (if this is a
                   15943:                     group item -- e.g., bulletin board, group page etc.).
                   15944: 
                   15945:  output: array of five scalars --
                   15946:          $cfile -- url for file editing if editable on current server
                   15947:          $home -- homeserver of resource (i.e., for author if published,
                   15948:                                           or course if uploaded.).
                   15949:          $switchserver --  1 if server switch will be needed.
                   15950:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15951:          $forceview -- 1 if icon/link should be to go to view mode
                   15952: 
                   15953: =item *
                   15954: 
                   15955: is_course_upload($file,$cnum,$cdom)
                   15956: 
                   15957: Used in course context to determine if current file was uploaded to
                   15958: the course (i.e., would be found in /userfiles/docs on the course's
                   15959: homeserver.
                   15960: 
                   15961:   input: 3 args -- filename (decluttered), course number and course domain.
                   15962:   output: boolean -- 1 if file was uploaded.
                   15963: 
1.243     albertel 15964: =back
                   15965: 
                   15966: =head2 Storing/Retreiving Data
                   15967: 
                   15968: =over 4
1.191     harris41 15969: 
                   15970: =item *
                   15971: 
1.1172.2.64  raeburn  15972: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15973: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15974: the remaining args aren't required and if they aren't passed or are '' they will
                   15975: be derived from the env (with the exception of $laststore, which is an
                   15976: optional arg used when a user's submission is stored in grading).
                   15977: $laststore is $version=$timestamp, where $version is the most recent version
                   15978: number retrieved for the corresponding $symb in the $namespace db file, and
                   15979: $timestamp is the timestamp for that transaction (UNIX time).
                   15980: $laststore is currently only passed when cstore() is called by
                   15981: structuretags::finalize_storage().
1.191     harris41 15982: 
                   15983: =item *
                   15984: 
1.1172.2.64  raeburn  15985: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15986: but uses critical subroutine
1.191     harris41 15987: 
                   15988: =item *
                   15989: 
1.243     albertel 15990: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15991: all args are optional
1.191     harris41 15992: 
                   15993: =item *
                   15994: 
1.717     albertel 15995: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15996: dumps the complete (or key matching regexp) namespace into a hash
                   15997: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15998: normally &store()ed into
                   15999: 
                   16000: $range should be either an integer '100' (give me the first 100
                   16001:                                            matching records)
                   16002:               or be  two integers sperated by a - with no spaces
                   16003:                  '30-50' (give me the 30th through the 50th matching
                   16004:                           records)
                   16005: 
                   16006: 
                   16007: =item *
                   16008: 
1.1172.2.59  raeburn  16009: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16010: replaces a &store() version of data with a replacement set of data
                   16011: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16012: reference. If $tolog is true, the transaction is logged in the courselog
                   16013: with an action=PUTSTORE.
1.717     albertel 16014: 
                   16015: =item *
                   16016: 
1.243     albertel 16017: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16018: works very similar to store/cstore, but all data is stored in a
                   16019: temporary location and can be reset using tmpreset, $storehash should
                   16020: be a hash reference, returns nothing on success
1.191     harris41 16021: 
                   16022: =item *
                   16023: 
1.243     albertel 16024: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16025: similar to restore, but all data is stored in a temporary location and
                   16026: can be reset using tmpreset. Returns a hash of values on success,
                   16027: error string otherwise.
1.191     harris41 16028: 
                   16029: =item *
                   16030: 
1.243     albertel 16031: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16032: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16033: 
                   16034: =item *
                   16035: 
1.243     albertel 16036: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16037: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16038: 
                   16039: =item *
                   16040: 
1.243     albertel 16041: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16042: namesp ($udom and $uname are optional)
1.191     harris41 16043: 
                   16044: =item *
                   16045: 
1.702     albertel 16046: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16047: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16048: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16049: 
1.702     albertel 16050: $range should be either an integer '100' (give me the first 100
                   16051:                                            matching records)
                   16052:               or be  two integers sperated by a - with no spaces
                   16053:                  '30-50' (give me the 30th through the 50th matching
                   16054:                           records)
1.449     matthew  16055: =item *
                   16056: 
                   16057: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16058: $store can be a scalar, an array reference, or if the amount to be 
                   16059: incremented is > 1, a hash reference.
                   16060: 
                   16061: ($udom and $uname are optional)
1.191     harris41 16062: 
                   16063: =item *
                   16064: 
1.243     albertel 16065: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16066: ($udom and $uname are optional)
1.191     harris41 16067: 
                   16068: =item *
                   16069: 
1.243     albertel 16070: cput($namespace,$storehash,$udom,$uname) : critical put
                   16071: ($udom and $uname are optional)
1.191     harris41 16072: 
                   16073: =item *
                   16074: 
1.748     albertel 16075: newput($namespace,$storehash,$udom,$uname) :
                   16076: 
                   16077: Attempts to store the items in the $storehash, but only if they don't
                   16078: currently exist, if this succeeds you can be certain that you have 
                   16079: successfully created a new key value pair in the $namespace db.
                   16080: 
                   16081: 
                   16082: Args:
                   16083:  $namespace: name of database to store values to
                   16084:  $storehash: hashref to store to the db
                   16085:  $udom: (optional) domain of user containing the db
                   16086:  $uname: (optional) name of user caontaining the db
                   16087: 
                   16088: Returns:
                   16089:  'ok' -> succeeded in storing all keys of $storehash
                   16090:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16091:                         least <key> already existed in the db (other
                   16092:                         requested keys may also already exist)
1.967     bisitz   16093:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16094:  'con_lost' -> unable to contact request server
                   16095:  'refused' -> action was not allowed by remote machine
                   16096: 
                   16097: 
                   16098: =item *
                   16099: 
1.243     albertel 16100: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16101: reference filled in from namesp (encrypts the return communication)
                   16102: ($udom and $uname are optional)
1.191     harris41 16103: 
                   16104: =item *
                   16105: 
1.243     albertel 16106: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16107: critical subroutine
                   16108: 
1.806     raeburn  16109: =item *
                   16110: 
1.860     raeburn  16111: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16112: array reference filled in from namespace found in domain level on either
                   16113: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16114: 
                   16115: =item *
                   16116: 
1.860     raeburn  16117: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16118: domain level either on specified domain server ($uhome) or primary domain 
                   16119: server ($udom and $uhome are optional)
1.806     raeburn  16120: 
1.943     raeburn  16121: =item * 
                   16122: 
1.1172.2.35  raeburn  16123: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16124: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16125: the target domain.
                   16126: 
                   16127: May also include additional key => value pairs for the following groups:
                   16128: 
                   16129: =over
                   16130: 
                   16131: =item
                   16132: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16133: 
                   16134: =over
                   16135: 
                   16136: =item defaultquota, authorquota
                   16137: 
                   16138: =back
                   16139: 
                   16140: =item
                   16141: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16142: portfolio for users).
                   16143: 
                   16144: =over
                   16145: 
                   16146: =item
                   16147: aboutme, blog, webdav, portfolio
                   16148: 
                   16149: =back
                   16150: 
                   16151: =item
                   16152: requestcourses: ability to request courses, and how requests are processed.
                   16153: 
                   16154: =over
                   16155: 
                   16156: =item
1.1172.2.37  raeburn  16157: official, unofficial, community, textbook
1.1172.2.35  raeburn  16158: 
                   16159: =back
                   16160: 
                   16161: =item
                   16162: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16163: 
                   16164: =over
                   16165: 
                   16166: =item
1.1172.2.44  raeburn  16167: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16168: 
                   16169: =back
                   16170: 
                   16171: =item
                   16172: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16173: for course's uploaded content.
                   16174: 
                   16175: =over
                   16176: 
                   16177: =item
1.1172.2.68  raeburn  16178: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16179: communityquota, textbookquota
1.1172.2.35  raeburn  16180: 
                   16181: =back
                   16182: 
                   16183: =item
                   16184: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16185: on your servers.
                   16186: 
                   16187: =over
                   16188: 
                   16189: =item
                   16190: remotesessions, hostedsessions
                   16191: 
                   16192: =back
                   16193: 
                   16194: =back
                   16195: 
                   16196: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16197: utility to create a configuration.db file on a domain's primary library server
                   16198: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16199: -- corresponding values are authentication type (internal, krb4, krb5,
                   16200: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16201: will be available. Values are retrieved from cache (if current), unless the
                   16202: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16203: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16204: 
                   16205: Typical usage:
1.943     raeburn  16206: 
1.1172.2.35  raeburn  16207: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16208: 
1.243     albertel 16209: =back
                   16210: 
                   16211: =head2 Network Status Functions
                   16212: 
                   16213: =over 4
1.191     harris41 16214: 
                   16215: =item *
                   16216: 
1.1137    raeburn  16217: dirlist() : return directory list based on URI (first arg).
                   16218: 
                   16219: Inputs: 1 required, 5 optional.
                   16220: 
                   16221: =over
                   16222: 
                   16223: =item 
                   16224: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16225: 
                   16226: =item
                   16227: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16228: 
                   16229: =item
                   16230: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16231: 
                   16232: =item
                   16233: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16234: 
                   16235: =item
                   16236: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16237: 
                   16238: =item 
                   16239: $alternateRoot - path to prepend in place of path from $uri.
                   16240: 
                   16241: =back
                   16242: 
                   16243: Returns: Array of up to two items.
                   16244: 
                   16245: =over
                   16246: 
                   16247: a reference to an array of files/subdirectories
                   16248: 
                   16249: =over
                   16250: 
                   16251: Each element in the array of files/subdirectories is a & separated list of
                   16252: item name and the result of running stat on the item.  If dirlist was requested
                   16253: for a file instead of a directory, the item name will be ''. For a directory 
                   16254: listing, if the item is a metadata file, the element will end &N&M 
                   16255: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16256: default copyright set (1).  
                   16257: 
                   16258: =back
                   16259: 
                   16260: a scalar containing error condition (if encountered).
                   16261: 
                   16262: =over
                   16263: 
                   16264: =item 
                   16265: no_host (no homeserver identified for $username:$domain).
                   16266: 
                   16267: =item 
                   16268: no_such_host (server contacted for listing not identified as valid host).
                   16269: 
                   16270: =item 
                   16271: con_lost (connection to remote server failed).
                   16272: 
                   16273: =item 
                   16274: refused (invalid $username:$domain received on lond side).
                   16275: 
                   16276: =item 
                   16277: no_such_dir (directory at specified path on lond side does not exist). 
                   16278: 
                   16279: =item 
                   16280: empty (directory at specified path on lond side is empty).
                   16281: 
                   16282: =over
                   16283: 
                   16284: This is currently not encountered because the &ls3, &ls2, 
                   16285: &ls (_handler) routines on the lond side do not filter out
                   16286: . and .. from a directory listing. 
                   16287: 
                   16288: =back
                   16289: 
                   16290: =back
                   16291: 
                   16292: =back
1.191     harris41 16293: 
                   16294: =item *
                   16295: 
1.243     albertel 16296: spareserver() : find server with least workload from spare.tab
                   16297: 
1.986     foxr     16298: 
                   16299: =item *
                   16300: 
                   16301: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16302: if there is no corresponding loncapa host.
                   16303: 
1.243     albertel 16304: =back
                   16305: 
1.986     foxr     16306: 
1.243     albertel 16307: =head2 Apache Request
                   16308: 
                   16309: =over 4
1.191     harris41 16310: 
                   16311: =item *
                   16312: 
1.243     albertel 16313: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16314: localhost, posts hash
                   16315: 
                   16316: =back
                   16317: 
                   16318: =head2 Data to String to Data
                   16319: 
                   16320: =over 4
1.191     harris41 16321: 
                   16322: =item *
                   16323: 
1.243     albertel 16324: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16325: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16326: 
                   16327: =item *
                   16328: 
1.243     albertel 16329: hashref2str($hashref) : convert a hashref into a string complete with
                   16330: escaping and '=' and '&' separators, supports elements that are
                   16331: arrayrefs and hashrefs
1.191     harris41 16332: 
                   16333: =item *
                   16334: 
1.243     albertel 16335: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16336: with escaping and '&' separators, supports elements that are arrayrefs
                   16337: and hashrefs
1.191     harris41 16338: 
                   16339: =item *
                   16340: 
1.243     albertel 16341: str2hash($string) : convert string to hash using unescaping and
                   16342: splitting on '=' and '&', supports elements that are arrayrefs and
                   16343: hashrefs
1.191     harris41 16344: 
                   16345: =item *
                   16346: 
1.243     albertel 16347: str2array($string) : convert string to hash using unescaping and
                   16348: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16349: 
                   16350: =back
                   16351: 
                   16352: =head2 Logging Routines
                   16353: 
                   16354: 
                   16355: These routines allow one to make log messages in the lonnet.log and
                   16356: lonnet.perm logfiles.
1.191     harris41 16357: 
1.1119    foxr     16358: =over 4
                   16359: 
1.191     harris41 16360: =item *
                   16361: 
1.243     albertel 16362: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16363: 
                   16364: =item *
                   16365: 
1.243     albertel 16366: logthis() : append message to the normal lonnet.log file, it gets
                   16367: preiodically rolled over and deleted.
1.191     harris41 16368: 
                   16369: =item *
                   16370: 
1.243     albertel 16371: logperm() : append a permanent message to lonnet.perm.log, this log
                   16372: file never gets deleted by any automated portion of the system, only
                   16373: messages of critical importance should go in here.
                   16374: 
1.1119    foxr     16375: 
1.243     albertel 16376: =back
                   16377: 
                   16378: =head2 General File Helper Routines
                   16379: 
                   16380: =over 4
1.191     harris41 16381: 
                   16382: =item *
                   16383: 
1.481     raeburn  16384: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16385: (a) files in /uploaded
                   16386:   (i) If a local copy of the file exists - 
                   16387:       compares modification date of local copy with last-modified date for 
                   16388:       definitive version stored on home server for course. If local copy is 
                   16389:       stale, requests a new version from the home server and stores it. 
                   16390:       If the original has been removed from the home server, then local copy 
                   16391:       is unlinked.
                   16392:   (ii) If local copy does not exist -
                   16393:       requests the file from the home server and stores it. 
                   16394:   
                   16395:   If $caller is 'uploadrep':  
                   16396:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16397:     for request for files originally uploaded via DOCS. 
                   16398:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16399:   
                   16400:   Otherwise:
                   16401:      This indicates a call from the content generation phase of the request.
                   16402:      -  returns the entire contents of the file or -1.
                   16403:      
                   16404: (b) files in /res
                   16405:    - returns the entire contents of a file or -1; 
                   16406:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16407: 
1.712     albertel 16408: 
                   16409: =item *
                   16410: 
                   16411: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16412:                   reference
                   16413: 
                   16414: returns either a stat() list of data about the file or an empty list
                   16415: if the file doesn't exist or couldn't find out about it (connection
                   16416: problems or user unknown)
                   16417: 
1.191     harris41 16418: =item *
                   16419: 
1.243     albertel 16420: filelocation($dir,$file) : returns file system location of a file
                   16421: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16422: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16423: and a file of ../bob will become /a/bob)
1.191     harris41 16424: 
                   16425: =item *
                   16426: 
                   16427: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16428: filelocation except for hrefs
                   16429: 
                   16430: =item *
                   16431: 
1.1172.2.49  raeburn  16432: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16433: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16434: 
1.243     albertel 16435: =back
                   16436: 
1.608     albertel 16437: =head2 Usererfile file routines (/uploaded*)
                   16438: 
                   16439: =over 4
                   16440: 
                   16441: =item *
                   16442: 
                   16443: userfileupload(): main rotine for putting a file in a user or course's
                   16444:                   filespace, arguments are,
                   16445: 
1.620     albertel 16446:  formname - required - this is the name of the element in $env where the
1.608     albertel 16447:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16448:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16449:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16450:  context - if coursedoc, store the file in the course of the active role
                   16451:              of the current user; 
                   16452:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16453:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16454:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16455:          if undefined, it will be placed in "unknown"
                   16456: 
                   16457:  (This routine calls clean_filename() to remove any dangerous
                   16458:  characters from the filename, and then calls finuserfileupload() to
                   16459:  complete the transaction)
                   16460: 
                   16461:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16462:  and /adm/notfound.html if unsuccessful
                   16463: 
                   16464: =item *
                   16465: 
                   16466: clean_filename(): routine for cleaing a filename up for storage in
                   16467:                  userfile space, argument is:
                   16468: 
                   16469:  filename - proposed filename
                   16470: 
                   16471: returns: the new clean filename
                   16472: 
                   16473: =item *
                   16474: 
1.1090    raeburn  16475: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16476: userspace, probably shouldn't be called directly
                   16477: 
                   16478:   docuname: username or courseid of destination for the file
                   16479:   docudom: domain of user/course of destination for the file
                   16480:   formname: same as for userfileupload()
1.1090    raeburn  16481:   fname: filename (including subdirectories) for the file
                   16482:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16483:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16484:   allfiles: reference to hash used to store objects found by parser
                   16485:   codebase: reference to hash used for codebases of java objects found by parser
                   16486:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16487:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16488:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16489:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16490:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16491:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16492:   mimetype: reference to scalar to accommodate mime type determined
                   16493:             from File::MMagic if $parser = parse.
1.608     albertel 16494: 
                   16495:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16496:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16497:  was 'overwrite').
                   16498:  
1.608     albertel 16499: 
                   16500: =item *
                   16501: 
                   16502: renameuserfile(): renames an existing userfile to a new name
                   16503: 
                   16504:   Args:
                   16505:    docuname: username or courseid of destination for the file
                   16506:    docudom: domain of user/course of destination for the file
                   16507:    old: current file name (including any subdirs under userfiles)
                   16508:    new: desired file name (including any subdirs under userfiles)
                   16509: 
                   16510: =item *
                   16511: 
                   16512: mkdiruserfile(): creates a directory is a userfiles dir
                   16513: 
                   16514:   Args:
                   16515:    docuname: username or courseid of destination for the file
                   16516:    docudom: domain of user/course of destination for the file
                   16517:    dir: dir to create (including any subdirs under userfiles)
                   16518: 
                   16519: =item *
                   16520: 
                   16521: removeuserfile(): removes a file that exists in userfiles
                   16522: 
                   16523:   Args:
                   16524:    docuname: username or courseid of destination for the file
                   16525:    docudom: domain of user/course of destination for the file
                   16526:    fname: filname to delete (including any subdirs under userfiles)
                   16527: 
                   16528: =item *
                   16529: 
                   16530: removeuploadedurl(): convience function for removeuserfile()
                   16531: 
                   16532:   Args:
                   16533:    url:  a full /uploaded/... url to delete
                   16534: 
1.747     albertel 16535: =item * 
                   16536: 
                   16537: get_portfile_permissions():
                   16538:   Args:
                   16539:     domain: domain of user or course contain the portfolio files
                   16540:     user: name of user or num of course contain the portfolio files
                   16541:   Returns:
                   16542:     hashref of a dump of the proper file_permissions.db
                   16543:    
                   16544: 
                   16545: =item * 
                   16546: 
                   16547: get_access_controls():
                   16548: 
                   16549: Args:
                   16550:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16551:   group: (optional) the group you want the files associated with
                   16552:   file: (optional) the file you want access info on
                   16553: 
                   16554: Returns:
1.749     raeburn  16555:     a hash (keys are file names) of hashes containing
                   16556:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16557:         values are XML containing access control settings (see below) 
1.747     albertel 16558: 
                   16559: Internal notes:
                   16560: 
1.749     raeburn  16561:  access controls are stored in file_permissions.db as key=value pairs.
                   16562:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16563:         where scope -> public,guest,course,group,domains or users.
                   16564:               end -> UNIX time for end of access (0 -> no end date)
                   16565:               start -> UNIX time for start of access
                   16566: 
                   16567:     value -> XML description of access control
                   16568:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16569:             <start></start>
                   16570:             <end></end>
                   16571: 
                   16572:             <password></password>  for scope type = guest
                   16573: 
                   16574:             <domain></domain>     for scope type = course or group
                   16575:             <number></number>
                   16576:             <roles id="">
                   16577:              <role></role>
                   16578:              <access></access>
                   16579:              <section></section>
                   16580:              <group></group>
                   16581:             </roles>
                   16582: 
                   16583:             <dom></dom>         for scope type = domains
                   16584: 
                   16585:             <users>             for scope type = users
                   16586:              <user>
                   16587:               <uname></uname>
                   16588:               <udom></udom>
                   16589:              </user>
                   16590:             </users>
                   16591:            </scope> 
                   16592:               
                   16593:  Access data is also aggregated for each file in an additional key=value pair:
                   16594:  key -> path to file/file_name\0accesscontrol 
                   16595:  value -> reference to hash
                   16596:           hash contains key = value pairs
                   16597:           where key = uniqueID:scope_end_start
                   16598:                 value = UNIX time record was last updated
                   16599: 
                   16600:           Used to improve speed of look-ups of access controls for each file.  
                   16601:  
                   16602:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16603: 
1.1172.2.13  raeburn  16604: =item *
                   16605: 
1.749     raeburn  16606: modify_access_controls():
                   16607: 
                   16608: Modifies access controls for a portfolio file
                   16609: Args
                   16610: 1. file name
                   16611: 2. reference to hash of required changes,
                   16612: 3. domain
                   16613: 4. username
                   16614:   where domain,username are the domain of the portfolio owner 
                   16615:   (either a user or a course) 
                   16616: 
                   16617: Returns:
                   16618: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16619: 2. result of deletions ('ok' or 'error', with error message).
                   16620: 3. reference to hash of any new or updated access controls.
                   16621: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16622:    key = integer (inbound ID)
1.1172.2.13  raeburn  16623:    value = uniqueID
                   16624: 
                   16625: =item *
                   16626: 
                   16627: get_timebased_id():
                   16628: 
                   16629: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16630: course via the Course Editor (e.g., folders, composite pages,
                   16631: group bulletin boards).
                   16632: 
                   16633: Args: (first three required; six others optional)
                   16634: 
                   16635: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16636:    docssequence, or name of group
                   16637: 
                   16638: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16639:    e.g., num, boardids
                   16640: 
                   16641: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16642:    file will be named nohist_namespace.db
                   16643: 
                   16644: 4. cdom: domain of course; default is current course domain from %env
                   16645: 
                   16646: 5. cnum: course number; default is current course number from %env
                   16647: 
                   16648: 6. idtype: set to concat if an additional digit is to be appended to the
                   16649:    unix timestamp to form the suffix, if the plain timestamp is already
                   16650:    in use.  Default is to not do this, but simply increment the unix
                   16651:    timestamp by 1 until a unique key is obtained.
                   16652: 
                   16653: 7. who: holder of locking key; defaults to user:domain for user.
                   16654: 
                   16655: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16656:    retrying); default is 3.
                   16657: 
                   16658: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16659: 
                   16660: Returns:
                   16661: 
                   16662: 1. suffix obtained (numeric)
                   16663: 
                   16664: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16665: 
                   16666: 3. error: contains (localized) error message if an error occurred.
                   16667: 
1.747     albertel 16668: 
1.608     albertel 16669: =back
                   16670: 
1.243     albertel 16671: =head2 HTTP Helper Routines
                   16672: 
                   16673: =over 4
                   16674: 
1.191     harris41 16675: =item *
                   16676: 
                   16677: escape() : unpack non-word characters into CGI-compatible hex codes
                   16678: 
                   16679: =item *
                   16680: 
                   16681: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16682: 
1.243     albertel 16683: =back
                   16684: 
                   16685: =head1 PRIVATE SUBROUTINES
                   16686: 
                   16687: =head2 Underlying communication routines (Shouldn't call)
                   16688: 
                   16689: =over 4
                   16690: 
                   16691: =item *
                   16692: 
                   16693: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16694: 
                   16695: =item *
                   16696: 
                   16697: reply() : uses subreply to send a message to remote machine, logs all failures
                   16698: 
                   16699: =item *
                   16700: 
                   16701: critical() : passes a critical message to another server; if cannot
                   16702: get through then place message in connection buffer directory and
                   16703: returns con_delayed, if incapable of saving message, returns
                   16704: con_failed
                   16705: 
                   16706: =item *
                   16707: 
                   16708: reconlonc() : tries to reconnect lonc client processes.
                   16709: 
                   16710: =back
                   16711: 
                   16712: =head2 Resource Access Logging
                   16713: 
                   16714: =over 4
                   16715: 
                   16716: =item *
                   16717: 
                   16718: flushcourselogs() : flush (save) buffer logs and access logs
                   16719: 
                   16720: =item *
                   16721: 
                   16722: courselog($what) : save message for course in hash
                   16723: 
                   16724: =item *
                   16725: 
                   16726: courseacclog($what) : save message for course using &courselog().  Perform
                   16727: special processing for specific resource types (problems, exams, quizzes, etc).
                   16728: 
1.191     harris41 16729: =item *
                   16730: 
                   16731: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16732: as a PerlChildExitHandler
1.243     albertel 16733: 
                   16734: =back
                   16735: 
                   16736: =head2 Other
                   16737: 
                   16738: =over 4
                   16739: 
                   16740: =item *
                   16741: 
                   16742: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16743: 
                   16744: =back
                   16745: 
                   16746: =cut
1.877     foxr     16747: 

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