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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .9(raebu    4:23): # $Id: lonnet.pm,v 1.1172.2.146.2.8 2023/01/16 19:10:08 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:         }
1.1172.2.146.  .8(raebu 4662:23):         chomp(@lines);
1.1172.2.109  raeburn  4663:     }
                   4664:     return @lines;
                   4665: }
                   4666: 
1.493     albertel 4667: sub removeuploadedurl {
1.984     neumanie 4668:     my ($url)=@_;	
                   4669:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4670:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4671: }
                   4672: 
                   4673: sub removeuserfile {
                   4674:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4675:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4676:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4677:     if ($result eq 'ok') {	
1.798     raeburn  4678:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4679:             my $metafile = $fname.'.meta';
                   4680:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4681: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4682:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4683:             my $sqlresult = 
1.823     albertel 4684:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4685:                                         'portfolio_metadata',$group,
                   4686:                                         'delete');
1.798     raeburn  4687:         }
                   4688:     }
                   4689:     return $result;
1.257     www      4690: }
1.15      www      4691: 
1.530     albertel 4692: sub mkdiruserfile {
                   4693:     my ($docuname,$docudom,$dir)=@_;
                   4694:     my $home=&homeserver($docuname,$docudom);
                   4695:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4696: }
                   4697: 
1.531     albertel 4698: sub renameuserfile {
                   4699:     my ($docuname,$docudom,$old,$new)=@_;
                   4700:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4701:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4702:                         &escape("$old").':'.&escape("$new"),$home);
                   4703:     if ($result eq 'ok') {
                   4704:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4705:             my $oldmeta = $old.'.meta';
                   4706:             my $newmeta = $new.'.meta';
                   4707:             my $metaresult = 
                   4708:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4709: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4710:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4711:             my $sqlresult = 
1.823     albertel 4712:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4713:                                         'portfolio_metadata',$group,
                   4714:                                         'delete');
1.798     raeburn  4715:         }
                   4716:     }
                   4717:     return $result;
1.531     albertel 4718: }
                   4719: 
1.14      www      4720: # ------------------------------------------------------------------------- Log
                   4721: 
                   4722: sub log {
                   4723:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4724:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4725: }
                   4726: 
                   4727: # ------------------------------------------------------------------ Course Log
1.352     www      4728: #
                   4729: # This routine flushes several buffers of non-mission-critical nature
                   4730: #
1.157     www      4731: 
                   4732: sub flushcourselogs {
1.352     www      4733:     &logthis('Flushing log buffers');
                   4734: #
                   4735: # course logs
                   4736: # This is a log of all transactions in a course, which can be used
                   4737: # for data mining purposes
                   4738: #
                   4739: # It also collects the courseid database, which lists last transaction
                   4740: # times and course titles for all courseids
                   4741: #
                   4742:     my %courseidbuffer=();
1.921     raeburn  4743:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4744:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4745: 		          &escape($courselogs{$crsid}),
                   4746: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4747: 	    delete $courselogs{$crsid};
                   4748:         } else {
                   4749:             &logthis('Failed to flush log buffer for '.$crsid);
                   4750:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4751:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4752:                         " exceeded maximum size, deleting.</font>");
                   4753:                delete $courselogs{$crsid};
                   4754:             }
1.352     www      4755:         }
1.920     raeburn  4756:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4757:             'description' => $coursedescrbuf{$crsid},
                   4758:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4759:             'type'        => $coursetypebuf{$crsid},
                   4760:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4761:         };
1.191     harris41 4762:     }
1.352     www      4763: #
                   4764: # Write course id database (reverse lookup) to homeserver of courses 
                   4765: # Is used in pickcourse
                   4766: #
1.840     albertel 4767:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4768:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4769:                                     $courseidbuffer{$crs_home},
                   4770:                                     $crs_home,'timeonly');
1.352     www      4771:     }
                   4772: #
                   4773: # File accesses
                   4774: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4775: #
1.449     matthew  4776:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4777:         if ($entry =~ /___count$/) {
                   4778:             my ($dom,$name);
1.807     albertel 4779:             ($dom,$name,undef)=
1.811     albertel 4780: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4781:             if (! defined($dom) || $dom eq '' || 
                   4782:                 ! defined($name) || $name eq '') {
1.620     albertel 4783:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4784: #
                   4785: # FIXME 11/29/2021
                   4786: # Typo in rev. 1.458 (2003/12/09)??
                   4787: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4788: #
                   4789: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4790: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4791: # in a nohist_accesscount.db file for the user rather than the course.
                   4792: #
                   4793: # That said there is a lot of noise in the data being stored.
                   4794: # So counts for prtspool/  and adm/ etc. are recorded.
                   4795: #
                   4796: # A review of which items ending '___count' are written to %accesshash should likely be
                   4797: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4798: #
                   4799: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4800: # accesses for things which are not published resources, regardless of course, and
                   4801: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4802: # anyone in the course for things which are not published resources.
                   4803: #
                   4804: # For an author, nohist_accesscount.db ends up having records for other items
                   4805: # mixed up with the legitimate access counts for the author's published resources.
                   4806: #
1.620     albertel 4807:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4808:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4809:             }
1.450     matthew  4810:             my $value = $accesshash{$entry};
                   4811:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4812:             my %temphash=($url => $value);
1.449     matthew  4813:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4814:             if ($result eq 'ok') {
                   4815:                 delete $accesshash{$entry};
                   4816:             }
                   4817:         } else {
1.811     albertel 4818:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4819:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4820:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4821:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4822:                 delete $accesshash{$entry};
                   4823:             }
1.185     www      4824:         }
1.191     harris41 4825:     }
1.352     www      4826: #
                   4827: # Roles
                   4828: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4829: #
1.800     albertel 4830:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4831:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4832: 	    split(/\:/,$entry);
                   4833:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4834:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4835:                 $rudom,$runame) eq 'ok') {
                   4836: 	    delete $userrolehash{$entry};
                   4837:         }
                   4838:     }
1.662     raeburn  4839: #
1.1172.2.90  raeburn  4840: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4841: #
                   4842:     my %domrolebuffer = ();
1.1000    raeburn  4843:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4844:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4845:         if ($domrolebuffer{$rudom}) {
                   4846:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4847:                       '='.&escape($domainrolehash{$entry});
                   4848:         } else {
                   4849:             $domrolebuffer{$rudom}.=&escape($entry).
                   4850:                       '='.&escape($domainrolehash{$entry});
                   4851:         }
                   4852:         delete $domainrolehash{$entry};
                   4853:     }
                   4854:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4855:         my %servers;
                   4856:         if (defined(&domain($dom,'primary'))) {
                   4857:             my $primary=&domain($dom,'primary');
                   4858:             my $hostname=&hostname($primary);
                   4859:             $servers{$primary} = $hostname;
                   4860:         } else {
                   4861:             %servers = &get_servers($dom,'library');
                   4862:         }
1.841     albertel 4863: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4864: 	    if (&reply('domroleput:'.$dom.':'.
                   4865: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4866: 	        last;
                   4867: 	    } else {
1.841     albertel 4868: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4869: 	    }
1.662     raeburn  4870:         }
                   4871:     }
1.186     www      4872:     $dumpcount++;
1.157     www      4873: }
                   4874: 
                   4875: sub courselog {
                   4876:     my $what=shift;
1.158     www      4877:     $what=time.':'.$what;
1.620     albertel 4878:     unless ($env{'request.course.id'}) { return ''; }
                   4879:     $coursedombuf{$env{'request.course.id'}}=
                   4880:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4881:     $coursenumbuf{$env{'request.course.id'}}=
                   4882:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4883:     $coursehombuf{$env{'request.course.id'}}=
                   4884:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4885:     $coursedescrbuf{$env{'request.course.id'}}=
                   4886:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4887:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4888:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4889:     $courseownerbuf{$env{'request.course.id'}}=
                   4890:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4891:     $coursetypebuf{$env{'request.course.id'}}=
                   4892:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4893:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4894: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4895:     } else {
1.620     albertel 4896: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4897:     }
1.620     albertel 4898:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4899: 	&flushcourselogs();
                   4900:     }
1.158     www      4901: }
                   4902: 
                   4903: sub courseacclog {
                   4904:     my $fnsymb=shift;
1.620     albertel 4905:     unless ($env{'request.course.id'}) { return ''; }
                   4906:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4907:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4908:         $what.=':POST';
1.583     matthew  4909:         # FIXME: Probably ought to escape things....
1.800     albertel 4910: 	foreach my $key (keys(%env)) {
                   4911:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4912:                 my $formitem = $1;
                   4913:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4914:                     $what.=':'.$formitem.'='.$env{$key};
                   4915:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4916:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4917:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4918:                     } else {
                   4919:                         $what.=':'.$formitem.'='.$env{$key};
                   4920:                     }
1.975     raeburn  4921:                 }
1.158     www      4922:             }
1.191     harris41 4923:         }
1.583     matthew  4924:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4925:         # FIXME: We should not be depending on a form parameter that someone
                   4926:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4927:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4928:             $what.= ':POST';
                   4929:             # FIXME: Probably ought to escape things....
                   4930:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4931:                                  'crsdiscuss') {
1.620     albertel 4932:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4933:             }
                   4934:         }
1.158     www      4935:     }
                   4936:     &courselog($what);
1.149     www      4937: }
                   4938: 
1.185     www      4939: sub countacc {
                   4940:     my $url=&declutter(shift);
1.458     matthew  4941:     return if (! defined($url) || $url eq '');
1.620     albertel 4942:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4943: #
                   4944: # Mark that this url was used in this course
                   4945: #
1.620     albertel 4946:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4947: #
                   4948: # Increase the access count for this resource in this child process
                   4949: #
1.281     www      4950:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4951:     $accesshash{$key}++;
1.185     www      4952: }
1.349     www      4953: 
1.361     www      4954: sub linklog {
                   4955:     my ($from,$to)=@_;
                   4956:     $from=&declutter($from);
                   4957:     $to=&declutter($to);
                   4958:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4959:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4960: }
1.1160    www      4961: 
                   4962: sub statslog {
                   4963:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4964:     if ($users<2) { return; }
                   4965:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4966:             'course'       => $env{'request.course.id'},
                   4967:             'sections'     => '"all"',
                   4968:             'num_students' => $users,
                   4969:             'part'         => $part,
                   4970:             'symb'         => $symb,
                   4971:             'mean_tries'   => $av_attempts,
                   4972:             'deg_of_diff'  => $degdiff});
                   4973:     foreach my $key (keys(%dynstore)) {
                   4974:         $accesshash{$key}=$dynstore{$key};
                   4975:     }
                   4976: }
1.361     www      4977:   
1.349     www      4978: sub userrolelog {
                   4979:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4980:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4981:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4982:        $userrolehash
                   4983:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4984:                     =$tend.':'.$tstart;
1.662     raeburn  4985:     }
1.1169    droeschl 4986:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4987:        $userrolehash
                   4988:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4989:                     =$tend.':'.$tstart;
                   4990:     }
1.1172.2.90  raeburn  4991:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4992:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4993:        $domainrolehash
                   4994:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4995:                     = $tend.':'.$tstart;
                   4996:     }
1.351     www      4997: }
                   4998: 
1.957     raeburn  4999: sub courserolelog {
                   5000:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5001:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5002:         my $cdom = $1;
                   5003:         my $cnum = $2;
                   5004:         my $sec = $3;
                   5005:         my $namespace = 'rolelog';
                   5006:         my %storehash = (
                   5007:                            role    => $trole,
                   5008:                            start   => $tstart,
                   5009:                            end     => $tend,
                   5010:                            selfenroll => $selfenroll,
                   5011:                            context    => $context,
                   5012:                         );
                   5013:         if ($trole eq 'gr') {
                   5014:             $namespace = 'groupslog';
                   5015:             $storehash{'group'} = $sec;
                   5016:         } else {
                   5017:             $storehash{'section'} = $sec;
                   5018:         }
                   5019:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5020:                    $domain,$cnum,$cdom);
                   5021:         if (($trole ne 'st') || ($sec ne '')) {
                   5022:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5023:         }
                   5024:     }
                   5025:     return;
                   5026: }
                   5027: 
1.1172.2.9  raeburn  5028: sub domainrolelog {
                   5029:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5030:     if ($area =~ m{^/($match_domain)/$}) {
                   5031:         my $cdom = $1;
                   5032:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5033:         my $namespace = 'rolelog';
                   5034:         my %storehash = (
                   5035:                            role    => $trole,
                   5036:                            start   => $tstart,
                   5037:                            end     => $tend,
                   5038:                            context => $context,
                   5039:                         );
                   5040:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5041:                    $domain,$domconfiguser,$cdom);
                   5042:     }
                   5043:     return;
                   5044: 
                   5045: }
                   5046: 
                   5047: sub coauthorrolelog {
                   5048:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5049:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5050:         my $audom = $1;
                   5051:         my $auname = $2;
                   5052:         my $namespace = 'rolelog';
                   5053:         my %storehash = (
                   5054:                            role    => $trole,
                   5055:                            start   => $tstart,
                   5056:                            end     => $tend,
                   5057:                            context => $context,
                   5058:                         );
                   5059:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5060:                    $domain,$auname,$audom);
                   5061:     }
                   5062:     return;
                   5063: }
                   5064: 
1.351     www      5065: sub get_course_adv_roles {
1.948     raeburn  5066:     my ($cid,$codes) = @_;
1.620     albertel 5067:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5068:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5069:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5070:     my %nothide=();
1.800     albertel 5071:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5072:         if ($user !~ /:/) {
                   5073: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5074:         } else {
                   5075:             $nothide{$user}=1;
                   5076:         }
1.470     www      5077:     }
1.1172.2.23  raeburn  5078:     my @possdoms = ($coursehash{'domain'});
                   5079:     if ($coursehash{'checkforpriv'}) {
                   5080:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5081:     }
1.351     www      5082:     my %returnhash=();
                   5083:     my %dumphash=
                   5084:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5085:     my $now=time;
1.997     raeburn  5086:     my %privileged;
1.1000    raeburn  5087:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5088: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5089:         if (($tstart) && ($tstart<0)) { next; }
                   5090:         if (($tend) && ($tend<$now)) { next; }
                   5091:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5092:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5093: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5094:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5095:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5096: 	if ($role eq 'cr') { next; }
1.948     raeburn  5097:         if ($codes) {
                   5098:             if ($section) { $role .= ':'.$section; }
                   5099:             if ($returnhash{$role}) {
                   5100:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5101:             } else {
                   5102:                 $returnhash{$role}=$username.':'.$domain;
                   5103:             }
1.351     www      5104:         } else {
1.988     raeburn  5105:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5106:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5107:             if ($returnhash{$key}) {
                   5108: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5109:             } else {
                   5110:                 $returnhash{$key}=$username.':'.$domain;
                   5111:             }
1.351     www      5112:         }
1.948     raeburn  5113:     }
1.400     www      5114:     return %returnhash;
                   5115: }
                   5116: 
                   5117: sub get_my_roles {
1.937     raeburn  5118:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5119:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5120:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5121:     my (%dumphash,%nothide);
1.1086    raeburn  5122:     if ($context eq 'userroles') {
1.1166    raeburn  5123:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5124:     } else {
1.1172.2.23  raeburn  5125:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5126:         if ($hidepriv) {
                   5127:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5128:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5129:                 if ($user !~ /:/) {
                   5130:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5131:                 } else {
                   5132:                     $nothide{$user} = 1;
                   5133:                 }
                   5134:             }
                   5135:         }
1.858     raeburn  5136:     }
1.400     www      5137:     my %returnhash=();
                   5138:     my $now=time;
1.999     raeburn  5139:     my %privileged;
1.800     albertel 5140:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5141:         my ($role,$tend,$tstart);
                   5142:         if ($context eq 'userroles') {
1.1149    raeburn  5143:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5144: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5145:         } else {
                   5146:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5147:         }
1.400     www      5148:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5149:         my $status = 'active';
1.939     raeburn  5150:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5151:             $status = 'previous';
                   5152:         } 
                   5153:         if (($tstart) && ($now<$tstart)) {
                   5154:             $status = 'future';
                   5155:         }
                   5156:         if (ref($types) eq 'ARRAY') {
                   5157:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5158:                 next;
                   5159:             } 
                   5160:         } else {
                   5161:             if ($status ne 'active') {
                   5162:                 next;
                   5163:             }
                   5164:         }
1.867     raeburn  5165:         my ($rolecode,$username,$domain,$section,$area);
                   5166:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5167:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5168:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5169:         } else {
                   5170:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5171:         }
1.832     raeburn  5172:         if (ref($roledoms) eq 'ARRAY') {
                   5173:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5174:                 next;
                   5175:             }
                   5176:         }
                   5177:         if (ref($roles) eq 'ARRAY') {
                   5178:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5179:                 if ($role =~ /^cr\//) {
                   5180:                     if (!grep(/^cr$/,@{$roles})) {
                   5181:                         next;
                   5182:                     }
1.1104    raeburn  5183:                 } elsif ($role =~ /^gr\//) {
                   5184:                     if (!grep(/^gr$/,@{$roles})) {
                   5185:                         next;
                   5186:                     }
1.922     raeburn  5187:                 } else {
                   5188:                     next;
                   5189:                 }
1.832     raeburn  5190:             }
1.867     raeburn  5191:         }
1.937     raeburn  5192:         if ($hidepriv) {
1.1172.2.23  raeburn  5193:             my @privroles = ('dc','su');
1.999     raeburn  5194:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5195:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5196:             } else {
1.1172.2.23  raeburn  5197:                 my $possdoms = [$domain];
                   5198:                 if (ref($roledoms) eq 'ARRAY') {
                   5199:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5200:                 }
1.1172.2.23  raeburn  5201:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5202:                     if (!$nothide{$username.':'.$domain}) {
                   5203:                         next;
                   5204:                     }
                   5205:                 }
1.937     raeburn  5206:             }
                   5207:         }
1.933     raeburn  5208:         if ($withsec) {
                   5209:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5210:                 $tstart.':'.$tend;
                   5211:         } else {
                   5212:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5213:         }
1.832     raeburn  5214:     }
1.373     www      5215:     return %returnhash;
1.399     www      5216: }
                   5217: 
1.1172.2.89  raeburn  5218: sub get_all_adhocroles {
                   5219:     my ($dom) = @_;
                   5220:     my @roles_by_num = ();
                   5221:     my %domdefaults = &get_domain_defaults($dom);
                   5222:     my (%description,%access_in_dom,%access_info);
                   5223:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5224:         my $count = 0;
                   5225:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5226:         my %ordered;
                   5227:         foreach my $role (sort(keys(%domcurrent))) {
                   5228:             my ($order,$desc,$access_in_dom);
                   5229:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5230:                 $order = $domcurrent{$role}{'order'};
                   5231:                 $desc = $domcurrent{$role}{'desc'};
                   5232:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5233:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5234:             }
                   5235:             if ($order eq '') {
                   5236:                 $order = $count;
                   5237:             }
                   5238:             $ordered{$order} = $role;
                   5239:             if ($desc ne '') {
                   5240:                 $description{$role} = $desc;
                   5241:             } else {
                   5242:                 $description{$role}= $role;
                   5243:             }
                   5244:             $count++;
                   5245:         }
                   5246:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5247:             push(@roles_by_num,$ordered{$item});
                   5248:         }
                   5249:     }
                   5250:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5251: }
                   5252: 
                   5253: sub get_my_adhocroles {
                   5254:     my ($cid,$checkreg) = @_;
                   5255:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5256:     if ($env{'request.course.id'} eq $cid) {
                   5257:         $cdom = $env{'course.'.$cid.'.domain'};
                   5258:         $cnum = $env{'course.'.$cid.'.num'};
                   5259:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5260:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5261:         $cdom = $1;
                   5262:         $cnum = $2;
                   5263:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5264:                                      $cdom,$cnum);
                   5265:     }
                   5266:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5267:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5268:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5269:         if ($rosterhash{$user} ne '') {
                   5270:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5271:             return ([],{}) if ($type eq 'auto');
                   5272:         }
                   5273:     }
                   5274:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5275:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5276:             my $then=$env{'user.login.time'};
                   5277:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5278:             if (!$update) {
                   5279:                 $update = $then;
                   5280:             }
                   5281:             my @liveroles;
                   5282:             foreach my $role ('dh','da') {
                   5283:                 if ($env{"user.role.$role./$cdom/"}) {
                   5284:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5285:                     my $limit = $update;
                   5286:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5287:                         $limit = $then;
                   5288:                     }
                   5289:                     my $activerole = 1;
                   5290:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5291:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5292:                     if ($activerole) {
                   5293:                         push(@liveroles,$role);
                   5294:                     }
                   5295:                 }
                   5296:             }
                   5297:             if (@liveroles) {
1.1172.2.89  raeburn  5298:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5299:                     my ($accessref,$accessinfo,%access_in_dom);
                   5300:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5301:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5302:                         if (@{$roles_by_num}) {
                   5303:                             my %settings;
                   5304:                             if ($env{'request.course.id'} eq $cid) {
                   5305:                                 foreach my $envkey (keys(%env)) {
                   5306:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5307:                                         $settings{$1} = $env{$envkey};
                   5308:                                     }
                   5309:                                 }
                   5310:                             } else {
                   5311:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5312:                             }
                   5313:                             my %setincrs;
                   5314:                             if ($settings{'internal.adhocaccess'}) {
                   5315:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5316:                             }
                   5317:                             my @statuses;
                   5318:                             if ($env{'environment.inststatus'}) {
                   5319:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5320:                             }
                   5321:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5322:                             if (ref($accessref) eq 'HASH') {
                   5323:                                 %access_in_dom = %{$accessref};
                   5324:                             }
                   5325:                             foreach my $role (@{$roles_by_num}) {
                   5326:                                 my ($curraccess,@okstatus,@personnel);
                   5327:                                 if ($setincrs{$role}) {
                   5328:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5329:                                     if ($curraccess eq 'status') {
                   5330:                                         @okstatus = split(/\&/,$rest);
                   5331:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5332:                                         @personnel = split(/\&/,$rest);
                   5333:                                     }
                   5334:                                 } else {
                   5335:                                     $curraccess = $access_in_dom{$role};
                   5336:                                     if (ref($accessinfo) eq 'HASH') {
                   5337:                                         if ($curraccess eq 'status') {
                   5338:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5339:                                                 @okstatus = @{$accessinfo->{$role}};
                   5340:                                             }
                   5341:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5342:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5343:                                                 @personnel = @{$accessinfo->{$role}};
                   5344:                                             }
                   5345:                                         }
                   5346:                                     }
                   5347:                                 }
                   5348:                                 if ($curraccess eq 'none') {
                   5349:                                     next;
                   5350:                                 } elsif ($curraccess eq 'all') {
                   5351:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5352:                                 } elsif ($curraccess eq 'dh') {
                   5353:                                     if (grep(/^dh$/,@liveroles)) {
                   5354:                                         push(@possroles,$role);
                   5355:                                     } else {
                   5356:                                         next;
                   5357:                                     }
                   5358:                                 } elsif ($curraccess eq 'da') {
                   5359:                                     if (grep(/^da$/,@liveroles)) {
                   5360:                                         push(@possroles,$role);
                   5361:                                     } else {
                   5362:                                         next;
                   5363:                                     }
1.1172.2.89  raeburn  5364:                                 } elsif ($curraccess eq 'status') {
                   5365:                                     if (@okstatus) {
                   5366:                                         if (!@statuses) {
                   5367:                                             if (grep(/^default$/,@okstatus)) {
                   5368:                                                 push(@possroles,$role);
                   5369:                                             }
                   5370:                                         } else {
                   5371:                                             foreach my $status (@okstatus) {
                   5372:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5373:                                                     push(@possroles,$role);
                   5374:                                                     last;
                   5375:                                                 }
                   5376:                                             }
                   5377:                                         }
                   5378:                                     }
                   5379:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5380:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5381:                                         if ($curraccess eq 'exc') {
                   5382:                                             push(@possroles,$role);
                   5383:                                         }
                   5384:                                     } elsif ($curraccess eq 'inc') {
                   5385:                                         push(@possroles,$role);
                   5386:                                     }
                   5387:                                 }
                   5388:                             }
                   5389:                         }
                   5390:                     }
                   5391:                 }
                   5392:             }
                   5393:         }
                   5394:     }
                   5395:     unless (ref($description) eq 'HASH') {
                   5396:         if (ref($roles_by_num) eq 'ARRAY') {
                   5397:             my %desc;
                   5398:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5399:             $description = \%desc;
                   5400:         } else {
                   5401:             $description = {};
                   5402:         }
                   5403:     }
                   5404:     return (\@possroles,$description);
                   5405: }
                   5406: 
1.399     www      5407: # ----------------------------------------------------- Frontpage Announcements
                   5408: #
                   5409: #
                   5410: 
                   5411: sub postannounce {
                   5412:     my ($server,$text)=@_;
1.844     albertel 5413:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5414:     unless ($text=~/\w/) { $text=''; }
                   5415:     return &reply('setannounce:'.&escape($text),$server);
                   5416: }
                   5417: 
                   5418: sub getannounce {
1.448     albertel 5419: 
1.1172.2.96  raeburn  5420:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5421: 	my $announcement='';
1.800     albertel 5422: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5423: 	close($fh);
1.399     www      5424: 	if ($announcement=~/\w/) { 
                   5425: 	    return 
                   5426:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5427:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5428: 	} else {
                   5429: 	    return '';
                   5430: 	}
                   5431:     } else {
                   5432: 	return '';
                   5433:     }
1.351     www      5434: }
1.353     www      5435: 
                   5436: # ---------------------------------------------------------- Course ID routines
                   5437: # Deal with domain's nohist_courseid.db files
                   5438: #
                   5439: 
                   5440: sub courseidput {
1.921     raeburn  5441:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5442:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5443:     my $outcome;
                   5444:     if ($caller eq 'timeonly') {
                   5445:         my $cids = '';
                   5446:         foreach my $item (keys(%$storehash)) {
                   5447:             $cids.=&escape($item).'&';
                   5448:         }
                   5449:         $cids=~s/\&$//;
                   5450:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5451:                           $coursehome);       
                   5452:     } else {
                   5453:         my $items = '';
                   5454:         foreach my $item (keys(%$storehash)) {
                   5455:             $items.= &escape($item).'='.
                   5456:                      &freeze_escape($$storehash{$item}).'&';
                   5457:         }
                   5458:         $items=~s/\&$//;
                   5459:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5460:                           $coursehome);
1.918     raeburn  5461:     }
                   5462:     if ($outcome eq 'unknown_cmd') {
                   5463:         my $what;
                   5464:         foreach my $cid (keys(%$storehash)) {
                   5465:             $what .= &escape($cid).'=';
1.921     raeburn  5466:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5467:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5468:             }
                   5469:             $what =~ s/\:$/&/;
                   5470:         }
                   5471:         $what =~ s/\&$//;  
                   5472:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5473:     } else {
                   5474:         return $outcome;
                   5475:     }
1.353     www      5476: }
                   5477: 
                   5478: sub courseiddump {
1.921     raeburn  5479:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5480:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5481:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5482:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5483:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5484:     my $as_hash = 1;
                   5485:     my %returnhash;
                   5486:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5487:     my %libserv = &all_library();
                   5488:     foreach my $tryserver (keys(%libserv)) {
                   5489:         if ( (  $hostidflag == 1 
                   5490: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5491: 	     || (!defined($hostidflag)) ) {
                   5492: 
1.918     raeburn  5493: 	    if (($domfilter eq '') ||
                   5494: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5495:                 my $rep;
                   5496:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5497:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5498:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5499:                                 &escape($descfilter), &escape($instcodefilter),
                   5500:                                 &escape($ownerfilter), &escape($coursefilter),
                   5501:                                 &escape($typefilter), &escape($regexp_ok),
                   5502:                                 $as_hash, &escape($selfenrollonly),
                   5503:                                 &escape($catfilter), $showhidden, $caller,
                   5504:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5505:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5506:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5507:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5508:                 } else {
                   5509:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5510:                              $sincefilter.':'.&escape($descfilter).':'.
                   5511:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5512:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5513:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5514:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5515:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5516:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5517:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5518:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5519:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5520:                 }
                   5521: 
1.918     raeburn  5522:                 my @pairs=split(/\&/,$rep);
                   5523:                 foreach my $item (@pairs) {
                   5524:                     my ($key,$value)=split(/\=/,$item,2);
                   5525:                     $key = &unescape($key);
                   5526:                     next if ($key =~ /^error: 2 /);
                   5527:                     my $result = &thaw_unescape($value);
                   5528:                     if (ref($result) eq 'HASH') {
                   5529:                         $returnhash{$key}=$result;
                   5530:                     } else {
1.921     raeburn  5531:                         my @responses = split(/:/,$value);
                   5532:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5533:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5534:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5535:                         }
1.1008    raeburn  5536:                     }
1.353     www      5537:                 }
                   5538:             }
                   5539:         }
                   5540:     }
                   5541:     return %returnhash;
                   5542: }
                   5543: 
1.1055    raeburn  5544: sub courselastaccess {
                   5545:     my ($cdom,$cnum,$hostidref) = @_;
                   5546:     my %returnhash;
                   5547:     if ($cdom && $cnum) {
                   5548:         my $chome = &homeserver($cnum,$cdom);
                   5549:         if ($chome ne 'no_host') {
                   5550:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5551:             &extract_lastaccess(\%returnhash,$rep);
                   5552:         }
                   5553:     } else {
                   5554:         if (!$cdom) { $cdom=''; }
                   5555:         my %libserv = &all_library();
                   5556:         foreach my $tryserver (keys(%libserv)) {
                   5557:             if (ref($hostidref) eq 'ARRAY') {
                   5558:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5559:             } 
                   5560:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5561:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5562:                 &extract_lastaccess(\%returnhash,$rep);
                   5563:             }
                   5564:         }
                   5565:     }
                   5566:     return %returnhash;
                   5567: }
                   5568: 
                   5569: sub extract_lastaccess {
                   5570:     my ($returnhash,$rep) = @_;
                   5571:     if (ref($returnhash) eq 'HASH') {
                   5572:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5573:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5574:                  $rep eq '') {
                   5575:             my @pairs=split(/\&/,$rep);
                   5576:             foreach my $item (@pairs) {
                   5577:                 my ($key,$value)=split(/\=/,$item,2);
                   5578:                 $key = &unescape($key);
                   5579:                 next if ($key =~ /^error: 2 /);
                   5580:                 $returnhash->{$key} = &thaw_unescape($value);
                   5581:             }
                   5582:         }
                   5583:     }
                   5584:     return;
                   5585: }
                   5586: 
1.658     raeburn  5587: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5588: 
                   5589: sub dcmailput {
1.685     raeburn  5590:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5591:     my $status = &Apache::lonnet::critical(
1.740     www      5592:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5593:        &escape($message),$server);
1.662     raeburn  5594:     return $status;
                   5595: }
                   5596: 
1.658     raeburn  5597: sub dcmaildump {
                   5598:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5599:     my %returnhash=();
1.846     albertel 5600: 
                   5601:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5602:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5603:                                                          &escape($enddate).':';
                   5604: 	my @esc_senders=map { &escape($_)} @$senders;
                   5605: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5606: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5607:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5608:             if (($key) && ($value)) {
                   5609:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5610:             }
                   5611:         }
                   5612:     }
                   5613:     return %returnhash;
                   5614: }
1.662     raeburn  5615: # ---------------------------------------------------------- Domain roles
                   5616: 
                   5617: sub get_domain_roles {
                   5618:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5619:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5620:         $startdate = '.';
                   5621:     }
1.1018    raeburn  5622:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5623:         $enddate = '.';
                   5624:     }
1.922     raeburn  5625:     my $rolelist;
                   5626:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5627:         $rolelist = join('&',@{$roles});
1.922     raeburn  5628:     }
1.662     raeburn  5629:     my %personnel = ();
1.841     albertel 5630: 
                   5631:     my %servers = &get_servers($dom,'library');
                   5632:     foreach my $tryserver (keys(%servers)) {
                   5633: 	%{$personnel{$tryserver}}=();
                   5634: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5635: 					    &escape($startdate).':'.
                   5636: 					    &escape($enddate).':'.
                   5637: 					    &escape($rolelist), $tryserver))) {
                   5638: 	    my ($key,$value) = split(/\=/,$line,2);
                   5639: 	    if (($key) && ($value)) {
                   5640: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5641: 	    }
                   5642: 	}
1.662     raeburn  5643:     }
                   5644:     return %personnel;
                   5645: }
1.658     raeburn  5646: 
1.1172.2.89  raeburn  5647: sub get_active_domroles {
                   5648:     my ($dom,$roles) = @_;
                   5649:     return () unless (ref($roles) eq 'ARRAY');
                   5650:     my $now = time;
                   5651:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5652:     my %domroles;
                   5653:     foreach my $server (keys(%dompersonnel)) {
                   5654:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5655:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5656:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5657:         }
                   5658:     }
                   5659:     return %domroles;
                   5660: }
                   5661: 
1.1057    www      5662: # ----------------------------------------------------------- Interval timing 
1.149     www      5663: 
1.1153    www      5664: {
                   5665: # Caches needed for speedup of navmaps
                   5666: # We don't want to cache this for very long at all (5 seconds at most)
                   5667: # 
                   5668: # The user for whom we cache
                   5669: my $cachedkey='';
                   5670: # The cached times for this user
                   5671: my %cachedtimes=();
                   5672: # When this was last done
1.1172.2.66  raeburn  5673: my $cachedtime='';
1.1153    www      5674: 
                   5675: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5676:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5677:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5678:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5679:22):         (!$ignorecache)) {
1.1154    raeburn  5680:         return;
                   5681:     }
                   5682:     $cachedtime=time;
                   5683:     $cachedkey=$uname.':'.$udom;
                   5684:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5685: }
                   5686: 
1.504     albertel 5687: sub get_first_access {
1.1172.2.146.  .1(raebu 5688:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5689:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5690:     if ($argsymb) { $symb=$argsymb; }
                   5691:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5692:     if ($argmap) { $map = $argmap; }
1.926     albertel 5693:     if ($type eq 'course') {
                   5694: 	$res='course';
                   5695:     } elsif ($type eq 'map') {
1.588     albertel 5696: 	$res=&symbread($map);
                   5697:     } else {
                   5698: 	$res=$symb;
                   5699:     }
1.1172.2.146.  .1(raebu 5700:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5701:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5702: }
                   5703: 
                   5704: sub set_first_access {
1.1162    raeburn  5705:     my ($type,$interval)=@_;
1.790     albertel 5706:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5707:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5708:     if ($type eq 'course') {
                   5709: 	$res='course';
                   5710:     } elsif ($type eq 'map') {
1.588     albertel 5711: 	$res=&symbread($map);
                   5712:     } else {
                   5713: 	$res=$symb;
                   5714:     }
1.1153    www      5715:     $cachedkey='';
1.1162    raeburn  5716:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5717:     if ($firstaccess) {
                   5718:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5719:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5720:                  "in $courseid");
                   5721:         return 'already_set';
                   5722:     } else {
1.1162    raeburn  5723:         my $start = time;
                   5724: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5725:                           $udom,$uname);
                   5726:         if ($putres eq 'ok') {
                   5727:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5728:                  $udom,$uname); 
                   5729:             &appenv(
                   5730:                      {
                   5731:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5732:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5733:                      }
                   5734:                   );
1.1172.2.97  raeburn  5735:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5736:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5737:             }
1.1172.2.102  raeburn  5738:         } elsif ($putres ne 'refused') {
                   5739:             &logthis("Result: $putres when attempting to set first access time ".
                   5740:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5741:         }
                   5742:         return $putres;
1.505     albertel 5743:     }
                   5744:     return 'already_set';
1.504     albertel 5745: }
1.1153    www      5746: }
1.1172.2.32  raeburn  5747: 
                   5748: sub checkout {
                   5749:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5750:     my $now=time;
                   5751:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5752:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5753:     my $infostr=&escape(
                   5754:                  'CHECKOUTTOKEN&'.
                   5755:                  $tuname.'&'.
                   5756:                  $tudom.'&'.
                   5757:                  $tcrsid.'&'.
                   5758:                  $symb.'&'.
1.1172.2.134  raeburn  5759:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5760:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5761:     if ($token=~/^error\:/) {
                   5762:         &logthis("<font color=\"blue\">WARNING: ".
                   5763:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5764:                  "</font>");
                   5765:         return '';
                   5766:     }
                   5767: 
                   5768:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5769:     $token=~tr/a-z/A-Z/;
                   5770: 
                   5771:     my %infohash=('resource.0.outtoken' => $token,
                   5772:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5773:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5774: 
                   5775:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5776:        return '';
                   5777:     } else {
                   5778:         &logthis("<font color=\"blue\">WARNING: ".
                   5779:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5780:                  "</font>");
                   5781:     }
                   5782: 
                   5783:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5784:                          &escape('Checkout '.$infostr.' - '.
                   5785:                                                  $token)) ne 'ok') {
                   5786:         return '';
                   5787:     } else {
                   5788:         &logthis("<font color=\"blue\">WARNING: ".
                   5789:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5790:                  "</font>");
                   5791:     }
                   5792:     return $token;
                   5793: }
                   5794: 
                   5795: # ------------------------------------------------------------ Check in an item
                   5796: 
                   5797: sub checkin {
                   5798:     my $token=shift;
                   5799:     my $now=time;
                   5800:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5801:     $lonhost=~tr/A-Z/a-z/;
                   5802:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5803:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5804:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5805:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5806:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5807: 
                   5808:     unless (($tuname) && ($tudom)) {
                   5809:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5810:         return '';
                   5811:     }
                   5812: 
                   5813:     unless (&allowed('mgr',$tcrsid)) {
                   5814:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5815:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5816:         return '';
                   5817:     }
                   5818: 
                   5819:     my %infohash=('resource.0.intoken' => $token,
                   5820:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5821:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5822: 
                   5823:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5824:        return '';
                   5825:     }
                   5826: 
                   5827:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5828:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5829:         return '';
                   5830:     }
                   5831: 
                   5832:     return ($symb,$tuname,$tudom,$tcrsid);
                   5833: }
                   5834: 
1.110     www      5835: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5836: 
                   5837: sub expirespread {
                   5838:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5839:     my $cid=$env{'request.course.id'}; 
1.110     www      5840:     if ($cid) {
                   5841:        my $now=time;
                   5842:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5843:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5844:                             $env{'course.'.$cid.'.num'}.
1.110     www      5845: 	        	    ':nohist_expirationdates:'.
                   5846:                             &escape($key).'='.$now,
1.620     albertel 5847:                             $env{'course.'.$cid.'.home'})
1.110     www      5848:     }
                   5849:     return 'ok';
1.14      www      5850: }
                   5851: 
1.109     www      5852: # ----------------------------------------------------- Devalidate Spreadsheets
                   5853: 
                   5854: sub devalidate {
1.325     www      5855:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5856:     my $cid=$env{'request.course.id'}; 
1.109     www      5857:     if ($cid) {
1.391     matthew  5858:         # delete the stored spreadsheets for
                   5859:         # - the student level sheet of this user in course's homespace
                   5860:         # - the assessment level sheet for this resource 
                   5861:         #   for this user in user's homespace
1.553     albertel 5862: 	# - current conditional state info
1.325     www      5863: 	my $key=$uname.':'.$udom.':';
1.109     www      5864:         my $status=
1.299     matthew  5865: 	    &del('nohist_calculatedsheets',
1.391     matthew  5866: 		 [$key.'studentcalc:'],
1.620     albertel 5867: 		 $env{'course.'.$cid.'.domain'},
                   5868: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5869: 		.' '.
                   5870: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5871: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5872:         unless ($status eq 'ok ok') {
                   5873:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5874:                     $uname.' at '.$udom.' for '.
1.109     www      5875: 		    $symb.': '.$status);
1.133     albertel 5876:         }
1.553     albertel 5877: 	&delenv('user.state.'.$cid);
1.109     www      5878:     }
                   5879: }
                   5880: 
1.265     albertel 5881: sub get_scalar {
                   5882:     my ($string,$end) = @_;
                   5883:     my $value;
                   5884:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5885: 	$value = $1;
                   5886:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5887: 	$value = $1;
                   5888:     }
                   5889:     return &unescape($value);
                   5890: }
                   5891: 
                   5892: sub array2str {
                   5893:   my (@array) = @_;
                   5894:   my $result=&arrayref2str(\@array);
                   5895:   $result=~s/^__ARRAY_REF__//;
                   5896:   $result=~s/__END_ARRAY_REF__$//;
                   5897:   return $result;
                   5898: }
                   5899: 
1.204     albertel 5900: sub arrayref2str {
                   5901:   my ($arrayref) = @_;
1.265     albertel 5902:   my $result='__ARRAY_REF__';
1.204     albertel 5903:   foreach my $elem (@$arrayref) {
1.265     albertel 5904:     if(ref($elem) eq 'ARRAY') {
                   5905:       $result.=&arrayref2str($elem).'&';
                   5906:     } elsif(ref($elem) eq 'HASH') {
                   5907:       $result.=&hashref2str($elem).'&';
                   5908:     } elsif(ref($elem)) {
                   5909:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5910:     } else {
                   5911:       $result.=&escape($elem).'&';
                   5912:     }
                   5913:   }
                   5914:   $result=~s/\&$//;
1.265     albertel 5915:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5916:   return $result;
                   5917: }
                   5918: 
1.168     albertel 5919: sub hash2str {
1.204     albertel 5920:   my (%hash) = @_;
                   5921:   my $result=&hashref2str(\%hash);
1.265     albertel 5922:   $result=~s/^__HASH_REF__//;
                   5923:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5924:   return $result;
                   5925: }
                   5926: 
                   5927: sub hashref2str {
                   5928:   my ($hashref)=@_;
1.265     albertel 5929:   my $result='__HASH_REF__';
1.800     albertel 5930:   foreach my $key (sort(keys(%$hashref))) {
                   5931:     if (ref($key) eq 'ARRAY') {
                   5932:       $result.=&arrayref2str($key).'=';
                   5933:     } elsif (ref($key) eq 'HASH') {
                   5934:       $result.=&hashref2str($key).'=';
                   5935:     } elsif (ref($key)) {
1.265     albertel 5936:       $result.='=';
1.800     albertel 5937:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5938:     } else {
1.1132    raeburn  5939: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5940:     }
                   5941: 
1.800     albertel 5942:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5943:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5944:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5945:       $result.=&hashref2str($hashref->{$key}).'&';
                   5946:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5947:        $result.='&';
1.800     albertel 5948:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5949:     } else {
1.800     albertel 5950:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5951:     }
                   5952:   }
1.168     albertel 5953:   $result=~s/\&$//;
1.265     albertel 5954:   $result .= '__END_HASH_REF__';
1.168     albertel 5955:   return $result;
                   5956: }
                   5957: 
                   5958: sub str2hash {
1.265     albertel 5959:     my ($string)=@_;
                   5960:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5961:     return %$hash;
                   5962: }
                   5963: 
                   5964: sub str2hashref {
1.168     albertel 5965:   my ($string) = @_;
1.265     albertel 5966: 
                   5967:   my %hash;
                   5968: 
                   5969:   if($string !~ /^__HASH_REF__/) {
                   5970:       if (! ($string eq '' || !defined($string))) {
                   5971: 	  $hash{'error'}='Not hash reference';
                   5972:       }
                   5973:       return (\%hash, $string);
                   5974:   }
                   5975: 
                   5976:   $string =~ s/^__HASH_REF__//;
                   5977: 
                   5978:   while($string !~ /^__END_HASH_REF__/) {
                   5979:       #key
                   5980:       my $key='';
                   5981:       if($string =~ /^__HASH_REF__/) {
                   5982:           ($key, $string)=&str2hashref($string);
                   5983:           if(defined($key->{'error'})) {
                   5984:               $hash{'error'}='Bad data';
                   5985:               return (\%hash, $string);
                   5986:           }
                   5987:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5988:           ($key, $string)=&str2arrayref($string);
                   5989:           if($key->[0] eq 'Array reference error') {
                   5990:               $hash{'error'}='Bad data';
                   5991:               return (\%hash, $string);
                   5992:           }
                   5993:       } else {
                   5994:           $string =~ s/^(.*?)=//;
1.267     albertel 5995: 	  $key=&unescape($1);
1.265     albertel 5996:       }
                   5997:       $string =~ s/^=//;
                   5998: 
                   5999:       #value
                   6000:       my $value='';
                   6001:       if($string =~ /^__HASH_REF__/) {
                   6002:           ($value, $string)=&str2hashref($string);
                   6003:           if(defined($value->{'error'})) {
                   6004:               $hash{'error'}='Bad data';
                   6005:               return (\%hash, $string);
                   6006:           }
                   6007:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6008:           ($value, $string)=&str2arrayref($string);
                   6009:           if($value->[0] eq 'Array reference error') {
                   6010:               $hash{'error'}='Bad data';
                   6011:               return (\%hash, $string);
                   6012:           }
                   6013:       } else {
                   6014: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6015:       }
                   6016:       $string =~ s/^&//;
                   6017: 
                   6018:       $hash{$key}=$value;
1.204     albertel 6019:   }
1.265     albertel 6020: 
                   6021:   $string =~ s/^__END_HASH_REF__//;
                   6022: 
                   6023:   return (\%hash, $string);
1.204     albertel 6024: }
                   6025: 
                   6026: sub str2array {
1.265     albertel 6027:     my ($string)=@_;
                   6028:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6029:     return @$array;
                   6030: }
                   6031: 
                   6032: sub str2arrayref {
1.204     albertel 6033:   my ($string) = @_;
1.265     albertel 6034:   my @array;
                   6035: 
                   6036:   if($string !~ /^__ARRAY_REF__/) {
                   6037:       if (! ($string eq '' || !defined($string))) {
                   6038: 	  $array[0]='Array reference error';
                   6039:       }
                   6040:       return (\@array, $string);
                   6041:   }
                   6042: 
                   6043:   $string =~ s/^__ARRAY_REF__//;
                   6044: 
                   6045:   while($string !~ /^__END_ARRAY_REF__/) {
                   6046:       my $value='';
                   6047:       if($string =~ /^__HASH_REF__/) {
                   6048:           ($value, $string)=&str2hashref($string);
                   6049:           if(defined($value->{'error'})) {
                   6050:               $array[0] ='Array reference error';
                   6051:               return (\@array, $string);
                   6052:           }
                   6053:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6054:           ($value, $string)=&str2arrayref($string);
                   6055:           if($value->[0] eq 'Array reference error') {
                   6056:               $array[0] ='Array reference error';
                   6057:               return (\@array, $string);
                   6058:           }
                   6059:       } else {
                   6060: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6061:       }
                   6062:       $string =~ s/^&//;
                   6063: 
                   6064:       push(@array, $value);
1.191     harris41 6065:   }
1.265     albertel 6066: 
                   6067:   $string =~ s/^__END_ARRAY_REF__//;
                   6068: 
                   6069:   return (\@array, $string);
1.168     albertel 6070: }
                   6071: 
1.167     albertel 6072: # -------------------------------------------------------------------Temp Store
                   6073: 
1.168     albertel 6074: sub tmpreset {
                   6075:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6076:   if (!$symb) {
                   6077:     $symb=&symbread();
1.620     albertel 6078:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6079:   }
                   6080:   $symb=escape($symb);
                   6081: 
1.620     albertel 6082:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6083:   $namespace=~s/\//\_/g;
                   6084:   $namespace=~s/\W//g;
                   6085: 
1.620     albertel 6086:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6087:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6088:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6089:       $stuname=&get_requestor_ip();
1.591     albertel 6090:   }
1.1117    foxr     6091:   my $path=LONCAPA::tempdir();
1.168     albertel 6092:   my %hash;
                   6093:   if (tie(%hash,'GDBM_File',
                   6094: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6095: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6096:     foreach my $key (keys(%hash)) {
1.180     albertel 6097:       if ($key=~ /:$symb/) {
1.168     albertel 6098: 	delete($hash{$key});
                   6099:       }
                   6100:     }
                   6101:   }
                   6102: }
                   6103: 
1.167     albertel 6104: sub tmpstore {
1.168     albertel 6105:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6106: 
                   6107:   if (!$symb) {
                   6108:     $symb=&symbread();
1.620     albertel 6109:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6110:   }
                   6111:   $symb=escape($symb);
                   6112: 
                   6113:   if (!$namespace) {
                   6114:     # I don't think we would ever want to store this for a course.
                   6115:     # it seems this will only be used if we don't have a course.
1.620     albertel 6116:     #$namespace=$env{'request.course.id'};
1.168     albertel 6117:     #if (!$namespace) {
1.620     albertel 6118:       $namespace=$env{'request.state'};
1.168     albertel 6119:     #}
                   6120:   }
                   6121:   $namespace=~s/\//\_/g;
                   6122:   $namespace=~s/\W//g;
1.620     albertel 6123:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6124:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6125:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6126:       $stuname=&get_requestor_ip();
1.591     albertel 6127:   }
1.168     albertel 6128:   my $now=time;
                   6129:   my %hash;
1.1117    foxr     6130:   my $path=LONCAPA::tempdir();
1.168     albertel 6131:   if (tie(%hash,'GDBM_File',
                   6132: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6133: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6134:     $hash{"version:$symb"}++;
                   6135:     my $version=$hash{"version:$symb"};
                   6136:     my $allkeys=''; 
                   6137:     foreach my $key (keys(%$storehash)) {
                   6138:       $allkeys.=$key.':';
1.591     albertel 6139:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6140:     }
                   6141:     $hash{"$version:$symb:timestamp"}=$now;
                   6142:     $allkeys.='timestamp';
                   6143:     $hash{"$version:keys:$symb"}=$allkeys;
                   6144:     if (untie(%hash)) {
                   6145:       return 'ok';
                   6146:     } else {
                   6147:       return "error:$!";
                   6148:     }
                   6149:   } else {
                   6150:     return "error:$!";
                   6151:   }
                   6152: }
1.167     albertel 6153: 
1.168     albertel 6154: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6155: 
1.168     albertel 6156: sub tmprestore {
                   6157:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6158: 
1.168     albertel 6159:   if (!$symb) {
                   6160:     $symb=&symbread();
1.620     albertel 6161:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6162:   }
                   6163:   $symb=escape($symb);
                   6164: 
1.620     albertel 6165:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6166: 
1.620     albertel 6167:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6168:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6169:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6170:       $stuname=&get_requestor_ip();
1.591     albertel 6171:   }
1.168     albertel 6172:   my %returnhash;
                   6173:   $namespace=~s/\//\_/g;
                   6174:   $namespace=~s/\W//g;
                   6175:   my %hash;
1.1117    foxr     6176:   my $path=LONCAPA::tempdir();
1.168     albertel 6177:   if (tie(%hash,'GDBM_File',
                   6178: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6179: 	  &GDBM_READER(),0640)) {
1.168     albertel 6180:     my $version=$hash{"version:$symb"};
                   6181:     $returnhash{'version'}=$version;
                   6182:     my $scope;
                   6183:     for ($scope=1;$scope<=$version;$scope++) {
                   6184:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6185:       my @keys=split(/:/,$vkeys);
                   6186:       my $key;
                   6187:       $returnhash{"$scope:keys"}=$vkeys;
                   6188:       foreach $key (@keys) {
1.591     albertel 6189: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6190: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6191:       }
                   6192:     }
1.168     albertel 6193:     if (!(untie(%hash))) {
                   6194:       return "error:$!";
                   6195:     }
                   6196:   } else {
                   6197:     return "error:$!";
                   6198:   }
                   6199:   return %returnhash;
1.167     albertel 6200: }
                   6201: 
1.9       www      6202: # ----------------------------------------------------------------------- Store
                   6203: 
                   6204: sub store {
1.1172.2.64  raeburn  6205:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6206:     my $home='';
                   6207: 
1.168     albertel 6208:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6209: 
1.213     www      6210:     $symb=&symbclean($symb);
1.122     albertel 6211:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6212: 
1.620     albertel 6213:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6214:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6215: 
                   6216:     &devalidate($symb,$stuname,$domain);
1.109     www      6217: 
                   6218:     $symb=escape($symb);
1.187     www      6219:     if (!$namespace) { 
1.620     albertel 6220:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6221:           return ''; 
                   6222:        } 
                   6223:     }
1.620     albertel 6224:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6225: 
1.1172.2.138  raeburn  6226:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6227:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6228: 
1.12      www      6229:     my $namevalue='';
1.800     albertel 6230:     foreach my $key (keys(%$storehash)) {
                   6231:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6232:     }
1.12      www      6233:     $namevalue=~s/\&$//;
1.187     www      6234:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6235:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6236: }
                   6237: 
1.47      www      6238: # -------------------------------------------------------------- Critical Store
                   6239: 
                   6240: sub cstore {
1.1172.2.64  raeburn  6241:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6242:     my $home='';
                   6243: 
1.168     albertel 6244:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6245: 
1.213     www      6246:     $symb=&symbclean($symb);
1.122     albertel 6247:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6248: 
1.620     albertel 6249:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6250:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6251: 
                   6252:     &devalidate($symb,$stuname,$domain);
1.109     www      6253: 
                   6254:     $symb=escape($symb);
1.187     www      6255:     if (!$namespace) { 
1.620     albertel 6256:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6257:           return ''; 
                   6258:        } 
                   6259:     }
1.620     albertel 6260:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6261: 
1.1172.2.138  raeburn  6262:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6263:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6264: 
1.47      www      6265:     my $namevalue='';
1.800     albertel 6266:     foreach my $key (keys(%$storehash)) {
                   6267:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6268:     }
1.47      www      6269:     $namevalue=~s/\&$//;
1.187     www      6270:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6271:     return critical
1.1172.2.64  raeburn  6272:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6273: }
                   6274: 
1.9       www      6275: # --------------------------------------------------------------------- Restore
                   6276: 
                   6277: sub restore {
1.124     www      6278:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6279:     my $home='';
                   6280: 
1.168     albertel 6281:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6282: 
1.122     albertel 6283:     if (!$symb) {
1.1172.2.26  raeburn  6284:         return if ($namespace eq 'courserequests');
                   6285:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6286:     } else {
1.1172.2.26  raeburn  6287:         unless ($namespace eq 'courserequests') {
                   6288:             $symb=&escape(&symbclean($symb));
                   6289:         }
1.122     albertel 6290:     }
1.188     www      6291:     if (!$namespace) { 
1.620     albertel 6292:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6293:           return ''; 
                   6294:        } 
                   6295:     }
1.620     albertel 6296:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6297:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6298:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6299:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6300: 
1.12      www      6301:     my %returnhash=();
1.800     albertel 6302:     foreach my $line (split(/\&/,$answer)) {
                   6303: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6304:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6305:     }
1.75      www      6306:     my $version;
                   6307:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6308:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6309:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6310:        }
1.75      www      6311:     }
1.13      www      6312:     return %returnhash;
1.34      www      6313: }
                   6314: 
                   6315: # ---------------------------------------------------------- Course Description
1.1118    foxr     6316: #
                   6317: #  
1.34      www      6318: 
                   6319: sub coursedescription {
1.731     albertel 6320:     my ($courseid,$args)=@_;
1.34      www      6321:     $courseid=~s/^\///;
1.49      www      6322:     $courseid=~s/\_/\//g;
1.34      www      6323:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6324:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6325:     my $normalid=$cdomain.'_'.$cnum;
                   6326:     # need to always cache even if we get errors otherwise we keep 
                   6327:     # trying and trying and trying to get the course description.
                   6328:     my %envhash=();
                   6329:     my %returnhash=();
1.731     albertel 6330:     
                   6331:     my $expiretime=600;
                   6332:     if ($env{'request.course.id'} eq $normalid) {
                   6333: 	$expiretime=120;
                   6334:     }
                   6335: 
                   6336:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6337:     if (!$args->{'freshen_cache'}
                   6338: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6339: 	foreach my $key (keys(%env)) {
                   6340: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6341: 	    my ($setting) = $1;
                   6342: 	    $returnhash{$setting} = $env{$key};
                   6343: 	}
                   6344: 	return %returnhash;
                   6345:     }
                   6346: 
1.1118    foxr     6347:     # get the data again
                   6348: 
1.731     albertel 6349:     if (!$args->{'one_time'}) {
                   6350: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6351:     }
1.811     albertel 6352: 
1.34      www      6353:     if ($chome ne 'no_host') {
1.302     albertel 6354:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6355:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6356: 	   my $username = $env{'user.name'}; # Defult username
                   6357: 	   if(defined $args->{'user'}) {
                   6358: 	       $username = $args->{'user'};
                   6359: 	   }
1.129     albertel 6360:            $returnhash{'home'}= $chome;
                   6361: 	   $returnhash{'domain'} = $cdomain;
                   6362: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6363:            if (!defined($returnhash{'type'})) {
                   6364:                $returnhash{'type'} = 'Course';
                   6365:            }
1.130     albertel 6366:            while (my ($name,$value) = each %returnhash) {
1.53      www      6367:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6368:            }
1.270     www      6369:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6370:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6371: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6372:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6373:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6374:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6375:        }
                   6376:     }
1.731     albertel 6377:     if (!$args->{'one_time'}) {
1.949     raeburn  6378: 	&appenv(\%envhash);
1.731     albertel 6379:     }
1.302     albertel 6380:     return %returnhash;
1.461     www      6381: }
                   6382: 
1.1080    raeburn  6383: sub update_released_required {
                   6384:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6385:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6386:         $cid = $env{'request.course.id'};
                   6387:         $cdom = $env{'course.'.$cid.'.domain'};
                   6388:         $cnum = $env{'course.'.$cid.'.num'};
                   6389:         $chome = $env{'course.'.$cid.'.home'};
                   6390:     }
                   6391:     if ($needsrelease) {
                   6392:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6393:         my $needsupdate;
                   6394:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6395:             $needsupdate = 1;
                   6396:         } else {
                   6397:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6398:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6399:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6400:                 $needsupdate = 1;
                   6401:             }
                   6402:         }
                   6403:         if ($needsupdate) {
                   6404:             my %needshash = (
                   6405:                              'internal.releaserequired' => $needsrelease,
                   6406:                             );
                   6407:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6408:             if ($putresult eq 'ok') {
                   6409:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6410:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6411:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6412:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6413:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6414:                 }
                   6415:             }
                   6416:         }
                   6417:     }
                   6418:     return;
                   6419: }
                   6420: 
1.461     www      6421: # -------------------------------------------------See if a user is privileged
                   6422: 
                   6423: sub privileged {
1.1172.2.23  raeburn  6424:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6425:     my $now = time;
1.1172.2.23  raeburn  6426:     my $roles;
                   6427:     if (ref($possroles) eq 'ARRAY') {
                   6428:         $roles = $possroles;
                   6429:     } else {
                   6430:         $roles = ['dc','su'];
                   6431:     }
                   6432:     if (ref($possdomains) eq 'ARRAY') {
                   6433:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6434:         foreach my $dom (@{$possdomains}) {
                   6435:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6436:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6437:                 foreach my $role (@{$roles}) {
                   6438:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6439:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6440:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6441:                             return 1 unless (($end && $end < $now) ||
                   6442:                                              ($start && $start > $now));
                   6443:                         }
                   6444:                     }
                   6445:                 }
                   6446:             }
                   6447:         }
                   6448:     } else {
                   6449:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6450:         my $now = time;
1.1170    droeschl 6451: 
1.1172.2.58  raeburn  6452:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6453:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6454:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6455:                 return 1 unless ($tend && $tend < $now)
                   6456:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6457:             }
1.1172.2.23  raeburn  6458:         }
                   6459:     }
1.461     www      6460:     return 0;
1.9       www      6461: }
1.1       albertel 6462: 
1.1172.2.23  raeburn  6463: sub privileged_by_domain {
                   6464:     my ($domains,$roles) = @_;
                   6465:     my %privileged = ();
                   6466:     my $cachetime = 60*60*24;
                   6467:     my $now = time;
                   6468:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6469:         return %privileged;
                   6470:     }
                   6471:     foreach my $dom (@{$domains}) {
                   6472:         next if (ref($privileged{$dom}) eq 'HASH');
                   6473:         my $needroles;
                   6474:         foreach my $role (@{$roles}) {
                   6475:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6476:             if (defined($cached)) {
                   6477:                 if (ref($result) eq 'HASH') {
                   6478:                     $privileged{$dom}{$role} = $result;
                   6479:                 }
                   6480:             } else {
                   6481:                 $needroles = 1;
                   6482:             }
                   6483:         }
                   6484:         if ($needroles) {
                   6485:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6486:             $privileged{$dom} = {};
                   6487:             foreach my $server (keys(%dompersonnel)) {
                   6488:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6489:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6490:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6491:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6492:                         next if ($end && $end < $now);
                   6493:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6494:                             $dompersonnel{$server}{$item};
                   6495:                     }
                   6496:                 }
                   6497:             }
                   6498:             if (ref($privileged{$dom}) eq 'HASH') {
                   6499:                 foreach my $role (@{$roles}) {
                   6500:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6501:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6502:                     } else {
                   6503:                         my %hash = ();
                   6504:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6505:                     }
                   6506:                 }
                   6507:             }
                   6508:         }
                   6509:     }
                   6510:     return %privileged;
                   6511: }
                   6512: 
1.103     harris41 6513: # -------------------------------------------------------- Get user privileges
1.11      www      6514: 
                   6515: sub rolesinit {
1.1169    droeschl 6516:     my ($domain, $username) = @_;
                   6517:     my %userroles = ('user.login.time' => time);
                   6518:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6519: 
                   6520:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6521:     # also, blocking can be triggered by an activating timer
                   6522:     # it's saved in the user's %env.
                   6523:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6524:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6525:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6526:         %timerintchk, %timerintenv);
                   6527: 
1.1162    raeburn  6528:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6529:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6530:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6531:     }
1.1169    droeschl 6532: 
1.1162    raeburn  6533:     foreach my $key (keys(%timerinterval)) {
                   6534:         my ($cid,$rest) = split(/\0/,$key);
                   6535:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6536:     }
1.1169    droeschl 6537: 
1.11      www      6538:     my %allroles=();
1.1162    raeburn  6539:     my %allgroups=();
1.11      www      6540: 
1.1172.2.58  raeburn  6541:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6542:         my $role = $rolesdump{$area};
                   6543:         $area =~ s/\_\w\w$//;
                   6544: 
                   6545:         my ($trole, $tend, $tstart, $group_privs);
                   6546: 
                   6547:         if ($role =~ /^cr/) {
                   6548:         # Custom role, defined by a user 
                   6549:         # e.g., user.role.cr/msu/smith/mynewrole
                   6550:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6551:                 $trole = $1;
                   6552:                 ($tend, $tstart) = split('_', $2);
                   6553:             } else {
                   6554:                 $trole = $role;
                   6555:             }
                   6556:         } elsif ($role =~ m|^gr/|) {
                   6557:         # Role of member in a group, defined within a course/community
                   6558:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6559:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6560:             next if $tstart eq '-1';
                   6561:             ($trole, $group_privs) = split(/\//, $trole);
                   6562:             $group_privs = &unescape($group_privs);
                   6563:         } else {
                   6564:         # Just a normal role, defined in roles.tab
                   6565:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6566:         }
                   6567: 
                   6568:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6569:                  $username);
                   6570:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6571: 
                   6572:         # role expired or not available yet?
                   6573:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6574:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6575: 
                   6576:         next if $area eq '' or $trole eq '';
                   6577: 
                   6578:         my $spec = "$trole.$area";
                   6579:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6580: 
                   6581:         if ($trole =~ /^cr\//) {
                   6582:         # Custom role, defined by a user
                   6583:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6584:         } elsif ($trole eq 'gr') {
                   6585:         # Role of a member in a group, defined within a course/community
                   6586:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6587:             next;
                   6588:         } else {
                   6589:         # Normal role, defined in roles.tab
                   6590:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6591:         }
                   6592: 
                   6593:         my $cid = $tdomain.'_'.$trest;
                   6594:         unless ($firstaccchk{$cid}) {
                   6595:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6596:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6597:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6598:                         $coursetimerstarts{$cid}{$item}; 
                   6599:                 }
                   6600:             }
                   6601:             $firstaccchk{$cid} = 1;
                   6602:         }
                   6603:         unless ($timerintchk{$cid}) {
                   6604:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6605:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6606:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6607:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6608:                 }
1.12      www      6609:             }
1.1169    droeschl 6610:             $timerintchk{$cid} = 1;
1.191     harris41 6611:         }
1.11      www      6612:     }
1.1169    droeschl 6613: 
1.1172.2.91  raeburn  6614:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6615:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6616:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6617:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6618: 
1.1162    raeburn  6619:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6620: }
                   6621: 
1.567     raeburn  6622: sub set_arearole {
1.1172.2.19  raeburn  6623:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6624:     unless ($nolog) {
1.567     raeburn  6625: # log the associated role with the area
1.1172.2.19  raeburn  6626:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6627:     }
1.743     albertel 6628:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6629: }
                   6630: 
                   6631: sub custom_roleprivs {
                   6632:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6633:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6634:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6635:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6636:         my ($rdummy,$roledef)=
                   6637:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6638:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6639:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6640:             if (defined($syspriv)) {
1.1043    raeburn  6641:                 if ($trest =~ /^$match_community$/) {
                   6642:                     $syspriv =~ s/bre\&S//; 
                   6643:                 }
1.567     raeburn  6644:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6645:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6646:             }
                   6647:             if ($tdomain ne '') {
                   6648:                 if (defined($dompriv)) {
                   6649:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6650:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6651:                 }
                   6652:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6653:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6654:                         my $rolename = $1;
                   6655:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6656:                     }
1.567     raeburn  6657:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6658:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6659:                 }
                   6660:             }
                   6661:         }
                   6662:     }
                   6663: }
                   6664: 
1.1172.2.89  raeburn  6665: sub course_adhocrole_privs {
                   6666:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6667:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6668:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6669:         my (%currprivs,%storeprivs);
                   6670:         foreach my $item (split(/:/,$coursepriv)) {
                   6671:             my ($priv,$restrict) = split(/\&/,$item);
                   6672:             $currprivs{$priv} = $restrict;
                   6673:         }
                   6674:         my (%possadd,%possremove,%full);
                   6675:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6676:             my ($priv,$restrict)=split(/\&/,$item);
                   6677:             $full{$priv} = $restrict;
                   6678:         }
                   6679:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6680:22):             next if ($item eq '');
                   6681:22):             my ($rule,$rest) = split(/=/,$item);
                   6682:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6683:22):             foreach my $priv (split(/:/,$rest)) {
                   6684:22):                 if ($priv ne '') {
                   6685:22):                     if ($rule eq 'off') {
                   6686:22):                         $possremove{$priv} = 1;
                   6687:22):                     } else {
                   6688:22):                         $possadd{$priv} = 1;
                   6689:22):                     }
                   6690:22):                 }
                   6691:22):             }
                   6692:22):         }
                   6693:22):         foreach my $priv (sort(keys(%full))) {
                   6694:22):             if (exists($currprivs{$priv})) {
                   6695:22):                 unless (exists($possremove{$priv})) {
                   6696:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6697:22):                 }
                   6698:22):             } elsif (exists($possadd{$priv})) {
                   6699:22):                 $storeprivs{$priv} = $full{$priv};
                   6700:22):             }
                   6701:22):         }
                   6702:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6703:22):     }
                   6704:22):     return $coursepriv;
1.1172.2.89  raeburn  6705: }
                   6706: 
1.678     raeburn  6707: sub group_roleprivs {
                   6708:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6709:     my $access = 1;
                   6710:     my $now = time;
                   6711:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6712:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6713:     if ($access) {
1.811     albertel 6714:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6715:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6716:     }
                   6717: }
1.567     raeburn  6718: 
                   6719: sub standard_roleprivs {
                   6720:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6721:     if (defined($pr{$trole.':s'})) {
                   6722:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6723:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6724:     }
                   6725:     if ($tdomain ne '') {
                   6726:         if (defined($pr{$trole.':d'})) {
                   6727:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6728:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6729:         }
                   6730:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6731:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6732:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6733:         }
                   6734:     }
                   6735: }
                   6736: 
                   6737: sub set_userprivs {
1.1064    raeburn  6738:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6739:     my $author=0;
                   6740:     my $adv=0;
1.1172.2.91  raeburn  6741:     my $rar=0;
1.678     raeburn  6742:     my %grouproles = ();
                   6743:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6744:         my @groupkeys; 
1.1000    raeburn  6745:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6746:             push(@groupkeys,$role);
                   6747:         }
                   6748:         if (ref($groups_roles) eq 'HASH') {
                   6749:             foreach my $key (keys(%{$groups_roles})) {
                   6750:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6751:                     push(@groupkeys,$key);
                   6752:                 }
                   6753:             }
                   6754:         }
                   6755:         if (@groupkeys > 0) {
                   6756:             foreach my $role (@groupkeys) {
                   6757:                 my ($trole,$area,$sec,$extendedarea);
                   6758:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6759:                     $trole = $1;
                   6760:                     $area = $2;
                   6761:                     $sec = $3;
                   6762:                     $extendedarea = $area.$sec;
                   6763:                     if (exists($$allgroups{$area})) {
                   6764:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6765:                             my $spec = $trole.'.'.$extendedarea;
                   6766:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6767:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6768:                         }
1.678     raeburn  6769:                     }
                   6770:                 }
                   6771:             }
                   6772:         }
                   6773:     }
1.800     albertel 6774:     foreach my $group (keys(%grouproles)) {
                   6775:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6776:     }
1.800     albertel 6777:     foreach my $role (keys(%{$allroles})) {
                   6778:         my %thesepriv;
1.941     raeburn  6779:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6780:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6781:             if ($item ne '') {
                   6782:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6783:                 if ($restrictions eq '') {
                   6784:                     $thesepriv{$privilege}='F';
                   6785:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6786:                     $thesepriv{$privilege}.=$restrictions;
                   6787:                 }
                   6788:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6789:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6790:             }
                   6791:         }
                   6792:         my $thesestr='';
1.1104    raeburn  6793:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6794: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6795: 	}
                   6796:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6797:     }
1.1172.2.91  raeburn  6798:     return ($author,$adv,$rar);
1.567     raeburn  6799: }
                   6800: 
1.994     raeburn  6801: sub role_status {
1.1104    raeburn  6802:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6803:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6804:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6805:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6806:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6807:             $$where = '/'.$two;
1.994     raeburn  6808:             $$trolecode=$$role.'.'.$$where;
                   6809:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6810:             $$tstatus='is';
1.1104    raeburn  6811:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6812:                 $$tstatus='future';
1.1034    raeburn  6813:                 if ($$tstart<$now) {
                   6814:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6815:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6816:                             my (%allroles,%allgroups,$group_privs,
                   6817:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6818:                             my %userroles = (
                   6819:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6820:                             );
1.1064    raeburn  6821:                             @rolecodes = ('cm'); 
1.1002    raeburn  6822:                             my $spec=$$role.'.'.$$where;
                   6823:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6824:                             if ($$role =~ /^cr\//) {
                   6825:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6826:                                 push(@rolecodes,'cr');
1.1002    raeburn  6827:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6828:                                 push(@rolecodes,$$role);
1.1002    raeburn  6829:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6830:                                                     $env{'user.name'});
1.1064    raeburn  6831:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6832:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6833:                                 $group_privs = &unescape($group_privs);
                   6834:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6835:                                 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  6836:                                 &get_groups_roles($tdomain,$trest,
                   6837:                                                   \%course_roles,\@rolecodes,
                   6838:                                                   \%groups_roles);
1.1002    raeburn  6839:                             } else {
1.1064    raeburn  6840:                                 push(@rolecodes,$$role);
1.1002    raeburn  6841:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6842:                             }
1.1172.2.91  raeburn  6843:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6844:                                                                    \%groups_roles);
1.1064    raeburn  6845:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6846:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6847:                         }
                   6848:                     }
1.1034    raeburn  6849:                     $$tstatus = 'is';
1.1002    raeburn  6850:                 }
1.994     raeburn  6851:             }
                   6852:             if ($$tend) {
1.1104    raeburn  6853:                 if ($$tend<$update) {
1.994     raeburn  6854:                     $$tstatus='expired';
                   6855:                 } elsif ($$tend<$now) {
                   6856:                     $$tstatus='will_not';
                   6857:                 }
                   6858:             }
                   6859:         }
                   6860:     }
                   6861: }
                   6862: 
1.1104    raeburn  6863: sub get_groups_roles {
                   6864:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6865:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6866:                   (ref($rolecodes) eq 'ARRAY') && 
                   6867:                   (ref($groups_roles) eq 'HASH')); 
                   6868:     if (keys(%{$cdom_courseroles}) > 0) {
                   6869:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6870:         if ($cdom ne '' && $cnum ne '') {
                   6871:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6872:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6873:                     my $crsrole = $1;
                   6874:                     my $crssec = $2;
                   6875:                     if ($crsrole =~ /^cr/) {
                   6876:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6877:                             push(@{$rolecodes},'cr');
                   6878:                         }
                   6879:                     } else {
                   6880:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6881:                             push(@{$rolecodes},$crsrole);
                   6882:                         }
                   6883:                     }
                   6884:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6885:                     if ($crssec ne '') {
                   6886:                         $rolekey .= "/$crssec";
                   6887:                     }
                   6888:                     $rolekey .= './';
                   6889:                     $groups_roles->{$rolekey} = $rolecodes;
                   6890:                 }
                   6891:             }
                   6892:         }
                   6893:     }
                   6894:     return;
                   6895: }
                   6896: 
                   6897: sub delete_env_groupprivs {
                   6898:     my ($where,$courseroles,$possroles) = @_;
                   6899:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6900:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6901:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6902:         %{$courseroles->{$udom}} =
                   6903:             &get_my_roles('','','userroles',['active'],
                   6904:                           $possroles,[$udom],1);
                   6905:     }
                   6906:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6907:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6908:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6909:             my $area = '/'.$cdom.'/'.$cnum;
                   6910:             my $privkey = "user.priv.$crsrole.$area";
                   6911:             if ($crssec ne '') {
                   6912:                 $privkey .= '/'.$crssec;
                   6913:             }
                   6914:             $privkey .= ".$area/$group";
                   6915:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6916:         }
                   6917:     }
                   6918:     return;
                   6919: }
                   6920: 
1.994     raeburn  6921: sub check_adhoc_privs {
1.1172.2.86  raeburn  6922:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6923:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6924:     if ($sec) {
                   6925:         $cckey .= '/'.$sec;
                   6926:     }
1.1172.2.9  raeburn  6927:     my $setprivs;
1.994     raeburn  6928:     if ($env{$cckey}) {
                   6929:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6930:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6931:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6932:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6933:             $setprivs = 1;
1.994     raeburn  6934:         }
                   6935:     } else {
1.1172.2.87  raeburn  6936:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6937:         $setprivs = 1;
1.994     raeburn  6938:     }
1.1172.2.9  raeburn  6939:     return $setprivs;
1.994     raeburn  6940: }
                   6941: 
                   6942: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6943: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6944:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6945:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6946:     if ($sec ne '') {
                   6947:         $area .= '/'.$sec;
                   6948:     }
1.994     raeburn  6949:     my $spec = $role.'.'.$area;
                   6950:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6951:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6952:     my %rolehash = ();
1.1172.2.89  raeburn  6953:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6954:         my $rolename = $1;
1.1172.2.84  raeburn  6955:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6956:         my %domdef = &get_domain_defaults($dcdom);
                   6957:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6958:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6959:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6960:             }
                   6961:         }
1.1172.2.84  raeburn  6962:     } else {
                   6963:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6964:     }
1.1172.2.91  raeburn  6965:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6966:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6967:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6968:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6969:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6970:         &appenv( {'request.role'        => $spec,
                   6971:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6972:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6973:                  }
                   6974:                );
                   6975:         my $tadv=0;
                   6976:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6977:         &appenv({'request.role.adv'    => $tadv});
                   6978:     }
1.994     raeburn  6979: }
                   6980: 
1.12      www      6981: # --------------------------------------------------------------- get interface
                   6982: 
                   6983: sub get {
1.131     albertel 6984:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6985:    my $items='';
1.800     albertel 6986:    foreach my $item (@$storearr) {
                   6987:        $items.=&escape($item).'&';
1.191     harris41 6988:    }
1.12      www      6989:    $items=~s/\&$//;
1.620     albertel 6990:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6991:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6992:    my $uhome=&homeserver($uname,$udomain);
                   6993: 
1.133     albertel 6994:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6995:    my @pairs=split(/\&/,$rep);
1.273     albertel 6996:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6997:      return @pairs;
                   6998:    }
1.15      www      6999:    my %returnhash=();
1.42      www      7000:    my $i=0;
1.800     albertel 7001:    foreach my $item (@$storearr) {
                   7002:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7003:       $i++;
1.191     harris41 7004:    }
1.15      www      7005:    return %returnhash;
1.27      www      7006: }
                   7007: 
                   7008: # --------------------------------------------------------------- del interface
                   7009: 
                   7010: sub del {
1.133     albertel 7011:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7012:    my $items='';
1.800     albertel 7013:    foreach my $item (@$storearr) {
                   7014:        $items.=&escape($item).'&';
1.191     harris41 7015:    }
1.984     neumanie 7016: 
1.27      www      7017:    $items=~s/\&$//;
1.620     albertel 7018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7019:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7020:    my $uhome=&homeserver($uname,$udomain);
                   7021:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7022: }
                   7023: 
                   7024: # -------------------------------------------------------------- dump interface
                   7025: 
1.1172.2.22  raeburn  7026: sub unserialize {
                   7027:     my ($rep, $escapedkeys) = @_;
                   7028: 
                   7029:     return {} if $rep =~ /^error/;
                   7030: 
                   7031:     my %returnhash=();
                   7032:     foreach my $item (split(/\&/,$rep)) {
                   7033:         my ($key, $value) = split(/=/, $item, 2);
                   7034:         $key = unescape($key) unless $escapedkeys;
                   7035:         next if $key =~ /^error: 2 /;
                   7036:         $returnhash{$key} = &thaw_unescape($value);
                   7037:     }
                   7038:     return \%returnhash;
                   7039: }
                   7040: 
                   7041: # see Lond::dump_with_regexp
                   7042: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7043: sub dump {
1.1172.2.146.  .1(raebu 7044:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7045:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7046:     if (!$uname) { $uname=$env{'user.name'}; }
                   7047:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7048: 
1.1172.2.55  raeburn  7049:     if ($regexp) {
                   7050:         $regexp=&escape($regexp);
                   7051:     } else {
                   7052:         $regexp='.';
                   7053:     }
1.1172.2.22  raeburn  7054:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7055:         # user is hosted on this machine
1.1172.2.55  raeburn  7056:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7057:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7058:         return %{&unserialize($reply, $escapedkeys)};
                   7059:     }
1.1172.2.146.  .1(raebu 7060:22):     my $rep;
                   7061:22):     if ($encrypt) {
                   7062:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7063:22):     } else {
                   7064:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7065:22):     }
1.755     albertel 7066:     my @pairs=split(/\&/,$rep);
                   7067:     my %returnhash=();
1.1098    foxr     7068:     if (!($rep =~ /^error/ )) {
                   7069: 	foreach my $item (@pairs) {
                   7070: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7071:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7072: 	    next if ($key =~ /^error: 2 /);
                   7073: 	    $returnhash{$key}=&thaw_unescape($value);
                   7074: 	}
1.755     albertel 7075:     }
                   7076:     return %returnhash;
1.407     www      7077: }
                   7078: 
1.1098    foxr     7079: 
1.717     albertel 7080: # --------------------------------------------------------- dumpstore interface
                   7081: 
                   7082: sub dumpstore {
                   7083:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7084:    # same as dump but keys must be escaped. They may contain colon separated
                   7085:    # lists of values that may themself contain colons (e.g. symbs).
                   7086:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7087: }
                   7088: 
1.407     www      7089: # -------------------------------------------------------------- keys interface
                   7090: 
                   7091: sub getkeys {
                   7092:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7094:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7095:    my $uhome=&homeserver($uname,$udomain);
                   7096:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7097:    my @keyarray=();
1.800     albertel 7098:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7099:       next if ($key =~ /^error: 2 /);
1.800     albertel 7100:       push(@keyarray,&unescape($key));
1.407     www      7101:    }
                   7102:    return @keyarray;
1.318     matthew  7103: }
                   7104: 
1.319     matthew  7105: # --------------------------------------------------------------- currentdump
                   7106: sub currentdump {
1.328     matthew  7107:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7108:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7109:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7110:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7111:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7112:    my $rep;
                   7113: 
                   7114:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7115:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7116:                    $courseid)));
                   7117:    } else {
                   7118:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7119:    }
                   7120: 
1.318     matthew  7121:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7122:    #
1.318     matthew  7123:    my %returnhash=();
1.319     matthew  7124:    #
                   7125:    if ($rep eq "unknown_cmd") { 
                   7126:        # an old lond will not know currentdump
                   7127:        # Do a dump and make it look like a currentdump
1.822     albertel 7128:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7129:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7130:        my %hash = @tmp;
                   7131:        @tmp=();
1.424     matthew  7132:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7133:    } else {
                   7134:        my @pairs=split(/\&/,$rep);
1.800     albertel 7135:        foreach my $pair (@pairs) {
                   7136:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7137:            my ($symb,$param) = split(/:/,$key);
                   7138:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7139:                                                         &thaw_unescape($value);
1.319     matthew  7140:        }
1.191     harris41 7141:    }
1.12      www      7142:    return %returnhash;
1.424     matthew  7143: }
                   7144: 
                   7145: sub convert_dump_to_currentdump{
                   7146:     my %hash = %{shift()};
                   7147:     my %returnhash;
                   7148:     # Code ripped from lond, essentially.  The only difference
                   7149:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7150:     # we might run in to problems with parameter names =~ /^v\./
                   7151:     while (my ($key,$value) = each(%hash)) {
                   7152:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7153: 	$symb  = &unescape($symb);
                   7154: 	$param = &unescape($param);
1.424     matthew  7155:         next if ($v eq 'version' || $symb eq 'keys');
                   7156:         next if (exists($returnhash{$symb}) &&
                   7157:                  exists($returnhash{$symb}->{$param}) &&
                   7158:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7159:         $returnhash{$symb}->{$param}=$value;
                   7160:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7161:     }
                   7162:     #
                   7163:     # Remove all of the keys in the hashes which keep track of
                   7164:     # the version of the parameter.
                   7165:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7166:         # use a foreach because we are going to delete from the hash.
                   7167:         foreach my $key (keys(%$param_hash)) {
                   7168:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7169:         }
                   7170:     }
                   7171:     return \%returnhash;
1.12      www      7172: }
                   7173: 
1.627     albertel 7174: # ------------------------------------------------------ critical inc interface
                   7175: 
                   7176: sub cinc {
                   7177:     return &inc(@_,'critical');
                   7178: }
                   7179: 
1.449     matthew  7180: # --------------------------------------------------------------- inc interface
                   7181: 
                   7182: sub inc {
1.627     albertel 7183:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7184:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7185:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7186:     my $uhome=&homeserver($uname,$udomain);
                   7187:     my $items='';
                   7188:     if (! ref($store)) {
                   7189:         # got a single value, so use that instead
                   7190:         $items = &escape($store).'=&';
                   7191:     } elsif (ref($store) eq 'SCALAR') {
                   7192:         $items = &escape($$store).'=&';        
                   7193:     } elsif (ref($store) eq 'ARRAY') {
                   7194:         $items = join('=&',map {&escape($_);} @{$store});
                   7195:     } elsif (ref($store) eq 'HASH') {
                   7196:         while (my($key,$value) = each(%{$store})) {
                   7197:             $items.= &escape($key).'='.&escape($value).'&';
                   7198:         }
                   7199:     }
                   7200:     $items=~s/\&$//;
1.627     albertel 7201:     if ($critical) {
                   7202: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7203:     } else {
                   7204: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7205:     }
1.449     matthew  7206: }
                   7207: 
1.12      www      7208: # --------------------------------------------------------------- put interface
                   7209: 
                   7210: sub put {
1.1172.2.146.  .1(raebu 7211:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7212:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7213:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7214:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7215:    my $items='';
1.800     albertel 7216:    foreach my $item (keys(%$storehash)) {
                   7217:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7218:    }
1.12      www      7219:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7220:22):    if ($encrypt) {
                   7221:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7222:22):    } else {
                   7223:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7224:22):    }
1.47      www      7225: }
                   7226: 
1.631     albertel 7227: # ------------------------------------------------------------ newput interface
                   7228: 
                   7229: sub newput {
                   7230:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7231:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7232:    if (!$uname) { $uname=$env{'user.name'}; }
                   7233:    my $uhome=&homeserver($uname,$udomain);
                   7234:    my $items='';
                   7235:    foreach my $key (keys(%$storehash)) {
                   7236:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7237:    }
                   7238:    $items=~s/\&$//;
                   7239:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7240: }
                   7241: 
                   7242: # ---------------------------------------------------------  putstore interface
                   7243: 
1.524     raeburn  7244: sub putstore {
1.1172.2.59  raeburn  7245:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7246:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7247:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7248:    my $uhome=&homeserver($uname,$udomain);
                   7249:    my $items='';
1.715     albertel 7250:    foreach my $key (keys(%$storehash)) {
                   7251:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7252:    }
1.715     albertel 7253:    $items=~s/\&$//;
1.716     albertel 7254:    my $esc_symb=&escape($symb);
                   7255:    my $esc_v=&escape($version);
1.715     albertel 7256:    my $reply =
1.716     albertel 7257:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7258: 	      $uhome);
1.1172.2.59  raeburn  7259:    if (($tolog) && ($reply eq 'ok')) {
                   7260:        my $namevalue='';
                   7261:        foreach my $key (keys(%{$storehash})) {
                   7262:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7263:        }
1.1172.2.134  raeburn  7264:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7265:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7266:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7267:                      '&version='.$esc_v.
                   7268:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7269:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7270:    }
1.715     albertel 7271:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7272:        # gfall back to way things use to be done
1.715     albertel 7273:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7274: 			    $uname);
1.524     raeburn  7275:    }
1.715     albertel 7276:    return $reply;
                   7277: }
                   7278: 
                   7279: sub old_putstore {
1.716     albertel 7280:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7281:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7282:     if (!$uname) { $uname=$env{'user.name'}; }
                   7283:     my $uhome=&homeserver($uname,$udomain);
                   7284:     my %newstorehash;
1.800     albertel 7285:     foreach my $item (keys(%$storehash)) {
                   7286: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7287: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7288:     }
                   7289:     my $items='';
                   7290:     my %allitems = ();
1.800     albertel 7291:     foreach my $item (keys(%newstorehash)) {
                   7292: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7293: 	    my $key = $1.':keys:'.$2;
                   7294: 	    $allitems{$key} .= $3.':';
                   7295: 	}
1.800     albertel 7296: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7297:     }
1.800     albertel 7298:     foreach my $item (keys(%allitems)) {
                   7299: 	$allitems{$item} =~ s/\:$//;
                   7300: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7301:     }
                   7302:     $items=~s/\&$//;
                   7303:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7304: }
                   7305: 
1.47      www      7306: # ------------------------------------------------------ critical put interface
                   7307: 
                   7308: sub cput {
1.134     albertel 7309:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7310:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7311:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7312:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7313:    my $items='';
1.800     albertel 7314:    foreach my $item (keys(%$storehash)) {
                   7315:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7316:    }
1.47      www      7317:    $items=~s/\&$//;
1.134     albertel 7318:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7319: }
                   7320: 
                   7321: # -------------------------------------------------------------- eget interface
                   7322: 
                   7323: sub eget {
1.133     albertel 7324:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7325:    my $items='';
1.800     albertel 7326:    foreach my $item (@$storearr) {
                   7327:        $items.=&escape($item).'&';
1.191     harris41 7328:    }
1.12      www      7329:    $items=~s/\&$//;
1.620     albertel 7330:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7331:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7332:    my $uhome=&homeserver($uname,$udomain);
                   7333:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7334:    my @pairs=split(/\&/,$rep);
                   7335:    my %returnhash=();
1.42      www      7336:    my $i=0;
1.800     albertel 7337:    foreach my $item (@$storearr) {
                   7338:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7339:       $i++;
1.191     harris41 7340:    }
1.12      www      7341:    return %returnhash;
                   7342: }
                   7343: 
1.667     albertel 7344: # ------------------------------------------------------------ tmpput interface
                   7345: sub tmpput {
1.802     raeburn  7346:     my ($storehash,$server,$context)=@_;
1.667     albertel 7347:     my $items='';
1.800     albertel 7348:     foreach my $item (keys(%$storehash)) {
                   7349: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7350:     }
                   7351:     $items=~s/\&$//;
1.802     raeburn  7352:     if (defined($context)) {
                   7353:         $items .= ':'.&escape($context);
                   7354:     }
1.667     albertel 7355:     return &reply("tmpput:$items",$server);
                   7356: }
                   7357: 
                   7358: # ------------------------------------------------------------ tmpget interface
                   7359: sub tmpget {
1.688     albertel 7360:     my ($token,$server)=@_;
                   7361:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7362:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7363:     my %returnhash;
1.1172.2.85  raeburn  7364:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7365:         return %returnhash;
                   7366:     }
1.667     albertel 7367:     foreach my $item (split(/\&/,$rep)) {
                   7368: 	my ($key,$value)=split(/=/,$item);
                   7369: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7370:     }
                   7371:     return %returnhash;
                   7372: }
                   7373: 
1.1113    raeburn  7374: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7375: sub tmpdel {
                   7376:     my ($token,$server)=@_;
                   7377:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7378:     return &reply("tmpdel:$token",$server);
                   7379: }
                   7380: 
1.1172.2.13  raeburn  7381: # ------------------------------------------------------------ get_timebased_id
                   7382: 
                   7383: sub get_timebased_id {
                   7384:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7385:         $maxtries) = @_;
                   7386:     my ($newid,$error,$dellock);
                   7387:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7388:         return ('','ok','invalid call to get suffix');
                   7389:     }
                   7390: 
                   7391: # set defaults for any optional args for which values were not supplied
                   7392:     if ($who eq '') {
                   7393:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7394:     }
                   7395:     if (!$locktries) {
                   7396:         $locktries = 3;
                   7397:     }
                   7398:     if (!$maxtries) {
                   7399:         $maxtries = 10;
                   7400:     }
                   7401: 
                   7402:     if (($cdom eq '') || ($cnum eq '')) {
                   7403:         if ($env{'request.course.id'}) {
                   7404:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7405:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7406:         }
                   7407:         if (($cdom eq '') || ($cnum eq '')) {
                   7408:             return ('','ok','call to get suffix not in course context');
                   7409:         }
                   7410:     }
                   7411: 
                   7412: # construct locking item
                   7413:     my $lockhash = {
                   7414:                       $prefix."\0".'locked_'.$keyid => $who,
                   7415:                    };
                   7416:     my $tries = 0;
                   7417: 
                   7418: # attempt to get lock on nohist_$namespace file
                   7419:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7420:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7421:         $tries ++;
                   7422:         sleep 1;
                   7423:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7424:     }
                   7425: 
                   7426: # attempt to get unique identifier, based on current timestamp
                   7427:     if ($gotlock eq 'ok') {
                   7428:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7429:         my $id = time;
                   7430:         $newid = $id;
1.1172.2.56  raeburn  7431:         if ($idtype eq 'addcode') {
                   7432:             $newid .= &sixnum_code();
                   7433:         }
1.1172.2.13  raeburn  7434:         my $idtries = 0;
                   7435:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7436:             if ($idtype eq 'concat') {
                   7437:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7438:             } elsif ($idtype eq 'addcode') {
                   7439:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7440:             } else {
                   7441:                 $newid ++;
                   7442:             }
                   7443:             $idtries ++;
                   7444:         }
                   7445:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7446:             my %new_item =  (
                   7447:                               $prefix."\0".$newid => $who,
                   7448:                             );
                   7449:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7450:                                                  $cdom,$cnum);
                   7451:             if ($putresult ne 'ok') {
                   7452:                 undef($newid);
                   7453:                 $error = 'error saving new item: '.$putresult;
                   7454:             }
                   7455:         } else {
1.1172.2.56  raeburn  7456:              undef($newid);
1.1172.2.13  raeburn  7457:              $error = ('error: no unique suffix available for the new item ');
                   7458:         }
                   7459: #  remove lock
                   7460:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7461:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7462:     } else {
                   7463:         $error = "error: could not obtain lockfile\n";
                   7464:         $dellock = 'ok';
1.1172.2.58  raeburn  7465:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7466:             $dellock = 'nolock';
                   7467:         }
1.1172.2.13  raeburn  7468:     }
                   7469:     return ($newid,$dellock,$error);
                   7470: }
                   7471: 
1.1172.2.56  raeburn  7472: sub sixnum_code {
                   7473:     my $code;
                   7474:     for (0..6) {
                   7475:         $code .= int( rand(9) );
                   7476:     }
                   7477:     return $code;
                   7478: }
                   7479: 
1.765     albertel 7480: # -------------------------------------------------- portfolio access checking
                   7481: 
                   7482: sub portfolio_access {
1.1172.2.77  raeburn  7483:     my ($requrl,$clientip) = @_;
1.765     albertel 7484:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7485:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7486:     if ($result) {
                   7487:         my %setters;
                   7488:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7489:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7490:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7491:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7492:                 return 'B';
                   7493:             }
                   7494:         } else {
1.1172.2.142  raeburn  7495:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7496:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7497:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7498:                 return 'B';
                   7499:             }
                   7500:         }
                   7501:     }
1.765     albertel 7502:     if ($result eq 'ok') {
1.766     albertel 7503:        return 'F';
1.765     albertel 7504:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7505:        return 'A';
1.765     albertel 7506:     }
1.766     albertel 7507:     return '';
1.765     albertel 7508: }
                   7509: 
                   7510: sub get_portfolio_access {
1.1172.2.77  raeburn  7511:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7512: 
                   7513:     if (!ref($access_hash)) {
                   7514: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7515: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7516: 						   $file_name);
                   7517: 	$access_hash = $access_controls{$file_name};
                   7518:     }
                   7519: 
1.1172.2.77  raeburn  7520:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7521:     my $now = time;
                   7522:     if (ref($access_hash) eq 'HASH') {
                   7523:         foreach my $key (keys(%{$access_hash})) {
                   7524:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7525:             if ($start > $now) {
                   7526:                 next;
                   7527:             }
                   7528:             if ($end && $end<$now) {
                   7529:                 next;
                   7530:             }
                   7531:             if ($scope eq 'public') {
                   7532:                 $public = $key;
                   7533:                 last;
                   7534:             } elsif ($scope eq 'guest') {
                   7535:                 $guest = $key;
                   7536:             } elsif ($scope eq 'domains') {
                   7537:                 push(@domains,$key);
                   7538:             } elsif ($scope eq 'users') {
                   7539:                 push(@users,$key);
                   7540:             } elsif ($scope eq 'course') {
                   7541:                 push(@courses,$key);
                   7542:             } elsif ($scope eq 'group') {
                   7543:                 push(@groups,$key);
1.1172.2.77  raeburn  7544:             } elsif ($scope eq 'ip') {
                   7545:                 push(@ips,$key);
1.765     albertel 7546:             }
                   7547:         }
                   7548:         if ($public) {
                   7549:             return 'ok';
1.1172.2.77  raeburn  7550:         } elsif (@ips > 0) {
                   7551:             my $allowed;
                   7552:             foreach my $ipkey (@ips) {
                   7553:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7554:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7555:                         $allowed = 1;
                   7556:                         last;
                   7557:                     }
                   7558:                 }
                   7559:             }
                   7560:             if ($allowed) {
                   7561:                 return 'ok';
                   7562:             }
1.765     albertel 7563:         }
                   7564:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7565:             if ($guest) {
                   7566:                 return $guest;
                   7567:             }
                   7568:         } else {
                   7569:             if (@domains > 0) {
                   7570:                 foreach my $domkey (@domains) {
                   7571:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7572:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7573:                             return 'ok';
                   7574:                         }
                   7575:                     }
                   7576:                 }
                   7577:             }
                   7578:             if (@users > 0) {
                   7579:                 foreach my $userkey (@users) {
1.865     raeburn  7580:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7581:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7582:                             if (ref($item) eq 'HASH') {
                   7583:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7584:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7585:                                     return 'ok';
                   7586:                                 }
                   7587:                             }
                   7588:                         }
                   7589:                     } 
1.765     albertel 7590:                 }
                   7591:             }
                   7592:             my %roleshash;
                   7593:             my @courses_and_groups = @courses;
                   7594:             push(@courses_and_groups,@groups); 
                   7595:             if (@courses_and_groups > 0) {
                   7596:                 my (%allgroups,%allroles); 
                   7597:                 my ($start,$end,$role,$sec,$group);
                   7598:                 foreach my $envkey (%env) {
1.1060    raeburn  7599:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7600:                         my $cid = $2.'_'.$3; 
                   7601:                         if ($1 eq 'gr') {
                   7602:                             $group = $4;
                   7603:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7604:                         } else {
                   7605:                             if ($4 eq '') {
                   7606:                                 $sec = 'none';
                   7607:                             } else {
                   7608:                                 $sec = $4;
                   7609:                             }
                   7610:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7611:                         }
1.811     albertel 7612:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7613:                         my $cid = $2.'_'.$3;
                   7614:                         if ($4 eq '') {
                   7615:                             $sec = 'none';
                   7616:                         } else {
                   7617:                             $sec = $4;
                   7618:                         }
                   7619:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7620:                     }
                   7621:                 }
                   7622:                 if (keys(%allroles) == 0) {
                   7623:                     return;
                   7624:                 }
                   7625:                 foreach my $key (@courses_and_groups) {
                   7626:                     my %content = %{$$access_hash{$key}};
                   7627:                     my $cnum = $content{'number'};
                   7628:                     my $cdom = $content{'domain'};
                   7629:                     my $cid = $cdom.'_'.$cnum;
                   7630:                     if (!exists($allroles{$cid})) {
                   7631:                         next;
                   7632:                     }    
                   7633:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7634:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7635:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7636:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7637:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7638:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7639:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7640:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7641:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7642:                                         if (grep/^all$/,@sections) {
                   7643:                                             return 'ok';
                   7644:                                         } else {
                   7645:                                             if (grep/^$sec$/,@sections) {
                   7646:                                                 return 'ok';
                   7647:                                             }
                   7648:                                         }
                   7649:                                     }
                   7650:                                 }
                   7651:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7652:                                     if (grep/^none$/,@groups) {
                   7653:                                         return 'ok';
                   7654:                                     }
                   7655:                                 } else {
                   7656:                                     if (grep/^all$/,@groups) {
                   7657:                                         return 'ok';
                   7658:                                     } 
                   7659:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7660:                                         if (grep/^$group$/,@groups) {
                   7661:                                             return 'ok';
                   7662:                                         }
                   7663:                                     }
                   7664:                                 } 
                   7665:                             }
                   7666:                         }
                   7667:                     }
                   7668:                 }
                   7669:             }
                   7670:             if ($guest) {
                   7671:                 return $guest;
                   7672:             }
                   7673:         }
                   7674:     }
                   7675:     return;
                   7676: }
                   7677: 
                   7678: sub course_group_datechecker {
                   7679:     my ($dates,$now,$status) = @_;
                   7680:     my ($start,$end) = split(/\./,$dates);
                   7681:     if (!$start && !$end) {
                   7682:         return 'ok';
                   7683:     }
                   7684:     if (grep/^active$/,@{$status}) {
                   7685:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7686:             return 'ok';
                   7687:         }
                   7688:     }
                   7689:     if (grep/^previous$/,@{$status}) {
                   7690:         if ($end > $now ) {
                   7691:             return 'ok';
                   7692:         }
                   7693:     }
                   7694:     if (grep/^future$/,@{$status}) {
                   7695:         if ($start > $now) {
                   7696:             return 'ok';
                   7697:         }
                   7698:     }
                   7699:     return; 
                   7700: }
                   7701: 
                   7702: sub parse_portfolio_url {
                   7703:     my ($url) = @_;
                   7704: 
                   7705:     my ($type,$udom,$unum,$group,$file_name);
                   7706:     
1.823     albertel 7707:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7708: 	$type = 1;
                   7709:         $udom = $1;
                   7710:         $unum = $2;
                   7711:         $file_name = $3;
1.823     albertel 7712:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7713: 	$type = 2;
                   7714:         $udom = $1;
                   7715:         $unum = $2;
                   7716:         $group = $3;
                   7717:         $file_name = $3.'/'.$4;
                   7718:     }
                   7719:     if (wantarray) {
                   7720: 	return ($type,$udom,$unum,$file_name,$group);
                   7721:     }
                   7722:     return $type;
                   7723: }
                   7724: 
                   7725: sub is_portfolio_url {
                   7726:     my ($url) = @_;
                   7727:     return scalar(&parse_portfolio_url($url));
                   7728: }
                   7729: 
1.798     raeburn  7730: sub is_portfolio_file {
                   7731:     my ($file) = @_;
1.820     raeburn  7732:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7733:         return 1;
                   7734:     }
                   7735:     return;
                   7736: }
                   7737: 
1.976     raeburn  7738: sub usertools_access {
1.1084    raeburn  7739:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7740:     my ($access,%tools);
                   7741:     if ($context eq '') {
                   7742:         $context = 'tools';
                   7743:     }
                   7744:     if ($context eq 'requestcourses') {
                   7745:         %tools = (
                   7746:                       official   => 1,
                   7747:                       unofficial => 1,
1.1006    raeburn  7748:                       community  => 1,
1.1172.2.37  raeburn  7749:                       textbook   => 1,
1.985     raeburn  7750:                  );
1.1172.2.9  raeburn  7751:     } elsif ($context eq 'requestauthor') {
                   7752:         %tools = (
                   7753:                       requestauthor => 1,
                   7754:                  );
1.985     raeburn  7755:     } else {
                   7756:         %tools = (
                   7757:                       aboutme   => 1,
                   7758:                       blog      => 1,
1.1172.2.6  raeburn  7759:                       webdav    => 1,
1.985     raeburn  7760:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7761:22):                       timezone  => 1,
1.985     raeburn  7762:                  );
                   7763:     }
1.976     raeburn  7764:     return if (!defined($tools{$tool}));
                   7765: 
1.1172.2.35  raeburn  7766:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7767:         $udom = $env{'user.domain'};
                   7768:         $uname = $env{'user.name'};
                   7769:     }
                   7770: 
1.978     raeburn  7771:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7772:         if ($action ne 'reload') {
1.985     raeburn  7773:             if ($context eq 'requestcourses') {
                   7774:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7775:             } elsif ($context eq 'requestauthor') {
                   7776:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7777:             } else {
                   7778:                 return $env{'environment.availabletools.'.$tool};
                   7779:             }
                   7780:         }
1.976     raeburn  7781:     }
                   7782: 
1.1172.2.9  raeburn  7783:     my ($toolstatus,$inststatus,$envkey);
                   7784:     if ($context eq 'requestauthor') {
                   7785:         $envkey = $context;
                   7786:     } else {
                   7787:         $envkey = $context.'.'.$tool;
                   7788:     }
1.976     raeburn  7789: 
1.985     raeburn  7790:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7791:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7792:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7793:         $inststatus = $env{'environment.inststatus'};
                   7794:     } else {
1.1084    raeburn  7795:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7796:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7797:             $inststatus = $userenvref->{'inststatus'};
                   7798:         } else {
1.1172.2.9  raeburn  7799:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7800:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7801:             $inststatus = $userenv{'inststatus'};
                   7802:         }
1.976     raeburn  7803:     }
                   7804: 
                   7805:     if ($toolstatus ne '') {
                   7806:         if ($toolstatus) {
                   7807:             $access = 1;
                   7808:         } else {
                   7809:             $access = 0;
                   7810:         }
                   7811:         return $access;
                   7812:     }
                   7813: 
1.1084    raeburn  7814:     my ($is_adv,%domdef);
                   7815:     if (ref($is_advref) eq 'HASH') {
                   7816:         $is_adv = $is_advref->{'is_adv'};
                   7817:     } else {
                   7818:         $is_adv = &is_advanced_user($udom,$uname);
                   7819:     }
                   7820:     if (ref($domdefref) eq 'HASH') {
                   7821:         %domdef = %{$domdefref};
                   7822:     } else {
                   7823:         %domdef = &get_domain_defaults($udom);
                   7824:     }
1.976     raeburn  7825:     if (ref($domdef{$tool}) eq 'HASH') {
                   7826:         if ($is_adv) {
                   7827:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7828:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7829:                     $access = 1;
                   7830:                 } else {
                   7831:                     $access = 0;
                   7832:                 }
                   7833:                 return $access;
                   7834:             }
                   7835:         }
                   7836:         if ($inststatus ne '') {
                   7837:             my ($hasaccess,$hasnoaccess);
                   7838:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7839:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7840:                     if ($domdef{$tool}{$affiliation}) {
                   7841:                         $hasaccess = 1;
                   7842:                     } else {
                   7843:                         $hasnoaccess = 1;
                   7844:                     }
                   7845:                 }
                   7846:             }
                   7847:             if ($hasaccess || $hasnoaccess) {
                   7848:                 if ($hasaccess) {
                   7849:                     $access = 1;
                   7850:                 } elsif ($hasnoaccess) {
                   7851:                     $access = 0; 
                   7852:                 }
                   7853:                 return $access;
                   7854:             }
                   7855:         } else {
                   7856:             if ($domdef{$tool}{'default'} ne '') {
                   7857:                 if ($domdef{$tool}{'default'}) {
                   7858:                     $access = 1;
                   7859:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7860:                     $access = 0;
                   7861:                 }
                   7862:                 return $access;
                   7863:             }
                   7864:         }
                   7865:     } else {
1.1172.2.6  raeburn  7866:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7867:             $access = 1;
                   7868:         } else {
                   7869:             $access = 0;
                   7870:         }
1.976     raeburn  7871:         return $access;
                   7872:     }
                   7873: }
                   7874: 
1.1050    raeburn  7875: sub is_course_owner {
                   7876:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7877:     if (($udom eq '') || ($uname eq '')) {
                   7878:         $udom = $env{'user.domain'};
                   7879:         $uname = $env{'user.name'};
                   7880:     }
                   7881:     unless (($udom eq '') || ($uname eq '')) {
                   7882:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7883:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7884:                 return 1;
                   7885:             } else {
                   7886:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7887:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7888:                     return 1;
                   7889:                 }
                   7890:             }
                   7891:         }
                   7892:     }
                   7893:     return;
                   7894: }
                   7895: 
1.976     raeburn  7896: sub is_advanced_user {
                   7897:     my ($udom,$uname) = @_;
1.1085    raeburn  7898:     if ($udom ne '' && $uname ne '') {
                   7899:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7900:             if (wantarray) {
                   7901:                 return ($env{'user.adv'},$env{'user.author'});
                   7902:             } else {
                   7903:                 return $env{'user.adv'};
                   7904:             }
1.1085    raeburn  7905:         }
                   7906:     }
1.976     raeburn  7907:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7908:     my %allroles;
1.1128    raeburn  7909:     my ($is_adv,$is_author);
1.976     raeburn  7910:     foreach my $role (keys(%roleshash)) {
                   7911:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7912:         my $area = '/'.$tdomain.'/'.$trest;
                   7913:         if ($sec ne '') {
                   7914:             $area .= '/'.$sec;
                   7915:         }
                   7916:         if (($area ne '') && ($trole ne '')) {
                   7917:             my $spec=$trole.'.'.$area;
                   7918:             if ($trole =~ /^cr\//) {
                   7919:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7920:             } elsif ($trole ne 'gr') {
                   7921:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7922:             }
1.1128    raeburn  7923:             if ($trole eq 'au') {
                   7924:                 $is_author = 1;
                   7925:             }
1.976     raeburn  7926:         }
                   7927:     }
                   7928:     foreach my $role (keys(%allroles)) {
                   7929:         last if ($is_adv);
                   7930:         foreach my $item (split(/:/,$allroles{$role})) {
                   7931:             if ($item ne '') {
                   7932:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7933:                 if ($privilege eq 'adv') {
                   7934:                     $is_adv = 1;
                   7935:                     last;
                   7936:                 }
                   7937:             }
                   7938:         }
                   7939:     }
1.1128    raeburn  7940:     if (wantarray) {
                   7941:         return ($is_adv,$is_author);
                   7942:     }
1.976     raeburn  7943:     return $is_adv;
                   7944: }
1.798     raeburn  7945: 
1.1035    raeburn  7946: sub check_can_request {
1.1036    raeburn  7947:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7948:     my $canreq = 0;
                   7949:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7950:     my @options = ('approval','validate','autolimit');
                   7951:     my $optregex = join('|',@options);
                   7952:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7953:         foreach my $type (@{$types}) {
                   7954:             if (&usertools_access($env{'user.name'},
                   7955:                                   $env{'user.domain'},
                   7956:                                   $type,undef,'requestcourses')) {
                   7957:                 $canreq ++;
1.1036    raeburn  7958:                 if (ref($request_domains) eq 'HASH') {
                   7959:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7960:                 }
1.1035    raeburn  7961:                 if ($dom eq $env{'user.domain'}) {
                   7962:                     $can_request->{$type} = 1;
                   7963:                 }
                   7964:             }
                   7965:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7966:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7967:                 if (@curr > 0) {
1.1036    raeburn  7968:                     foreach my $item (@curr) {
                   7969:                         if (ref($request_domains) eq 'HASH') {
                   7970:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7971:                             if ($otherdom ne '') {
                   7972:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7973:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7974:                                         push(@{$request_domains->{$type}},$otherdom);
                   7975:                                     }
                   7976:                                 } else {
                   7977:                                     push(@{$request_domains->{$type}},$otherdom);
                   7978:                                 }
                   7979:                             }
                   7980:                         }
                   7981:                     }
                   7982:                     unless($dom eq $env{'user.domain'}) {
                   7983:                         $canreq ++;
1.1035    raeburn  7984:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7985:                             $can_request->{$type} = 1;
                   7986:                         }
                   7987:                     }
                   7988:                 }
                   7989:             }
                   7990:         }
                   7991:     }
                   7992:     return $canreq;
                   7993: }
                   7994: 
1.341     www      7995: # ---------------------------------------------- Custom access rule evaluation
                   7996: 
                   7997: sub customaccess {
                   7998:     my ($priv,$uri)=@_;
1.807     albertel 7999:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8000:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8001:     $udom = &LONCAPA::clean_domain($udom);
                   8002:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8003:     my $access=0;
1.800     albertel 8004:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8005: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8006: 	if ($type eq 'user') {
                   8007: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8008: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8009: 		if ($tdom) {
                   8010: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8011: 		}
1.896     albertel 8012: 		if ($tuname) {
                   8013: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8014: 		}
                   8015: 		$access=($effect eq 'allow');
                   8016: 		last;
                   8017: 	    }
                   8018: 	} else {
                   8019: 	    if ($role) {
                   8020: 		if ($role ne $urole) { next; }
                   8021: 	    }
                   8022: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8023: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8024: 		if ($tdom) {
                   8025: 		    if ($tdom ne $udom) { next; }
                   8026: 		}
                   8027: 		if ($tcrs) {
                   8028: 		    if ($tcrs ne $ucrs) { next; }
                   8029: 		}
                   8030: 		if ($tsec) {
                   8031: 		    if ($tsec ne $usec) { next; }
                   8032: 		}
                   8033: 		$access=($effect eq 'allow');
                   8034: 		last;
                   8035: 	    }
                   8036: 	    if ($realm eq '' && $role eq '') {
                   8037: 		$access=($effect eq 'allow');
                   8038: 	    }
1.402     bowersj2 8039: 	}
1.341     www      8040:     }
                   8041:     return $access;
                   8042: }
                   8043: 
1.103     harris41 8044: # ------------------------------------------------- Check for a user privilege
1.12      www      8045: 
                   8046: sub allowed {
1.1172.2.146.  .1(raebu 8047:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8048:     my $ver_orguri=$uri;
1.439     www      8049:     $uri=&deversion($uri);
1.152     www      8050:     my $orguri=$uri;
1.52      www      8051:     $uri=&declutter($uri);
1.809     raeburn  8052: 
1.810     raeburn  8053:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8054:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8055:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8056:             return $1;
                   8057:         } else {
                   8058:             return;
                   8059:         }
                   8060:     }
                   8061: 
1.620     albertel 8062:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8063: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8064:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8065: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8066: 	&& ($priv eq 'bre')) {
1.14      www      8067: 	return 'F';
1.159     www      8068:     }
                   8069: 
1.545     banghart 8070: # Free bre access to user's own portfolio contents
1.714     raeburn  8071:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8072:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8073: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8074:         my %setters;
1.1172.2.142  raeburn  8075:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8076:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8077:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8078:             return 'B';
                   8079:         } else {
                   8080:             return 'F';
                   8081:         }
1.545     banghart 8082:     }
                   8083: 
1.762     raeburn  8084: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8085:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8086:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8087:         if (exists($env{'request.course.id'})) {
                   8088:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8089:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8090:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8091:                 my $courseprivid=$env{'request.course.id'};
                   8092:                 $courseprivid=~s/\_/\//;
                   8093:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8094:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8095:                     return $1; 
1.762     raeburn  8096:                 } else {
                   8097:                     if ($env{'request.course.sec'}) {
                   8098:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8099:                     }
                   8100:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8101:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8102:                         return $2;
                   8103:                     }
1.714     raeburn  8104:                 }
                   8105:             }
                   8106:         }
                   8107:     }
                   8108: 
1.159     www      8109: # Free bre to public access
                   8110: 
                   8111:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8112:22):         my $copyright;
                   8113:22):         unless ($uri =~ /ext\.tool/) {
                   8114:22):             $copyright=&metadata($uri,'copyright');
                   8115:22):         }
1.620     albertel 8116: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8117:            return 'F'; 
                   8118:         }
1.238     www      8119:         if ($copyright eq 'priv') {
                   8120:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8121: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8122: 		return '';
                   8123:             }
                   8124:         }
                   8125:         if ($copyright eq 'domain') {
                   8126:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8127: 	    unless (($env{'user.domain'} eq $1) ||
                   8128:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8129: 		return '';
                   8130:             }
1.262     matthew  8131:         }
1.620     albertel 8132:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8133:             # Library role, so allow browsing of resources in this domain.
                   8134:             return 'F';
1.238     www      8135:         }
1.341     www      8136:         if ($copyright eq 'custom') {
                   8137: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8138:         }
1.14      www      8139:     }
1.264     matthew  8140:     # Domain coordinator is trying to create a course
1.620     albertel 8141:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8142:         # uri is the requested domain in this case.
                   8143:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8144:         # a role of dc for the domain in question.
1.620     albertel 8145:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8146:     }
1.29      www      8147: 
1.52      www      8148:     my $thisallowed='';
                   8149:     my $statecond=0;
                   8150:     my $courseprivid='';
                   8151: 
1.1039    raeburn  8152:     my $ownaccess;
1.1043    raeburn  8153:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8154:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8155:         if ($uri eq '') {
                   8156:             $ownaccess = 1;
                   8157:         } else {
                   8158:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8159:                 my $udom = $env{'user.domain'};
                   8160:                 my $uname = $env{'user.name'};
                   8161:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8162:                     $ownaccess = 1;
1.1040    raeburn  8163:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8164:                     unless ($uri =~ m{\.\./}) {
                   8165:                         $ownaccess = 1;
                   8166:                     }
                   8167:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8168:                     my $now = time;
                   8169:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8170:                         my $adom = $1;
                   8171:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8172:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8173:                                 my ($start,$end) = split(/\./,$env{$key});
                   8174:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8175:                                     $ownaccess = 1;
                   8176:                                     last;
                   8177:                                 }
                   8178:                             }
                   8179:                         }
                   8180:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8181:                         my $adom = $1;
                   8182:                         my $aname = $2;
1.1042    raeburn  8183:                         foreach my $role ('ca','aa') { 
                   8184:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8185:                                 my ($start,$end) =
1.1172.2.142  raeburn  8186:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8187:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8188:                                     $ownaccess = 1;
                   8189:                                     last;
                   8190:                                 }
1.1039    raeburn  8191:                             }
                   8192:                         }
                   8193:                     }
                   8194:                 }
                   8195:             }
                   8196:         }
                   8197:     }
                   8198: 
1.52      www      8199: # Course
                   8200: 
1.620     albertel 8201:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8202:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8203:             $thisallowed.=$1;
                   8204:         }
1.52      www      8205:     }
1.29      www      8206: 
1.52      www      8207: # Domain
                   8208: 
1.620     albertel 8209:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8210:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8211:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8212:             $thisallowed.=$1;
                   8213:         }
1.12      www      8214:     }
1.52      www      8215: 
1.1141    raeburn  8216: # User who is not author or co-author might still be able to edit
                   8217: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8218:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8219:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8220:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8221:             $thisallowed.=$1;
                   8222:         }
                   8223:     }
                   8224: 
1.52      www      8225: # Course: uri itself is a course
1.66      www      8226:     my $courseuri=$uri;
                   8227:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8228:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8229: 
1.620     albertel 8230:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8231:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8232:         if ($priv eq 'mip') {
                   8233:             my $rem = $1;
                   8234:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8235:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8236:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8237:                 if ($cdom ne '') {
                   8238:                     my %passwdconf = &get_passwdconf($cdom);
                   8239:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8240:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8241:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8242:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8243:                                 unless (@inststatuses) {
                   8244:                                     @inststatuses = ('default');
                   8245:                                 }
                   8246:                                 foreach my $status (@inststatuses) {
                   8247:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8248:                                         $thisallowed.=$rem;
                   8249:                                     }
                   8250:                                 }
                   8251:                             }
                   8252:                         }
                   8253:                     }
                   8254:                 }
                   8255:             }
                   8256:         } else {
                   8257:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8258:                 $thisallowed.=$1;
                   8259:             }
1.1039    raeburn  8260:         }
1.12      www      8261:     }
1.29      www      8262: 
1.665     albertel 8263: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8264: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8265:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8266: 	$thisallowed='';
1.671     raeburn  8267:         my ($match)=&is_on_map($uri);
                   8268:         if ($match) {
                   8269:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8270:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8271:                 my $value = $1;
1.1172.2.146.  .1(raebu 8272:22):                 my $deeplinkblock;
                   8273:22):                 unless ($nodeeplinkcheck) {
                   8274:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8275:22):                 }
                   8276:22):                 if ($deeplinkblock) {
                   8277:22):                     $thisallowed='D';
                   8278:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8279:                     $thisallowed.=$value;
1.1162    raeburn  8280:                 } else {
1.1172.2.126  raeburn  8281:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8282:                     if (@blockers > 0) {
                   8283:                         $thisallowed = 'B';
                   8284:                     } else {
                   8285:                         $thisallowed.=$value;
                   8286:                     }
1.1162    raeburn  8287:                 }
1.671     raeburn  8288:             }
                   8289:         } else {
1.705     albertel 8290:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8291:             if ($refuri) {
                   8292:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8293:                     $thisallowed='F';
1.671     raeburn  8294:                 } else {
                   8295:                     $refuri=&declutter($refuri);
                   8296:                     my ($match) = &is_on_map($refuri);
                   8297:                     if ($match) {
1.1172.2.146.  .1(raebu 8298:22):                         my $deeplinkblock;
                   8299:22):                         unless ($nodeeplinkcheck) {
                   8300:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8301:22):                         }
                   8302:22):                         if ($deeplinkblock) {
                   8303:22):                             $thisallowed='D';
                   8304:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8305:                             $thisallowed='F';
1.1172.2.65  raeburn  8306:                         } else {
1.1172.2.127  raeburn  8307:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8308:                             if (@blockers > 0) {
                   8309:                                 $thisallowed = 'B';
                   8310:                             } else {
                   8311:                                 $thisallowed='F';
                   8312:                             }
1.1162    raeburn  8313:                         }
1.671     raeburn  8314:                     }
1.669     raeburn  8315:                 }
1.671     raeburn  8316:             }
                   8317:         }
1.314     www      8318:     }
1.492     albertel 8319: 
1.766     albertel 8320:     if ($priv eq 'bre'
                   8321: 	&& $thisallowed ne 'F' 
                   8322: 	&& $thisallowed ne '2'
                   8323: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8324: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8325:     }
                   8326:     
1.52      www      8327: # Full access at system, domain or course-wide level? Exit.
1.29      www      8328:     if ($thisallowed=~/F/) {
                   8329: 	return 'F';
                   8330:     }
                   8331: 
1.52      www      8332: # If this is generating or modifying users, exit with special codes
1.29      www      8333: 
1.643     www      8334:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8335: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8336: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8337: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8338: 	    unless ($auname) { return $thisallowed; }
                   8339: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8340: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8341: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8342: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8343: 	}
1.52      www      8344: 	return $thisallowed;
                   8345:     }
                   8346: #
1.103     harris41 8347: # Gathered so far: system, domain and course wide privileges
1.52      www      8348: #
                   8349: # Course: See if uri or referer is an individual resource that is part of 
                   8350: # the course
                   8351: 
1.620     albertel 8352:     if ($env{'request.course.id'}) {
1.232     www      8353: 
1.1172.2.115  raeburn  8354: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8355: 
                   8356:         if ($priv eq 'mip') {
                   8357:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8358:                 return $thisallowed;
                   8359:             } else {
                   8360:                 return '';
                   8361:             }
                   8362:         }
                   8363: 
1.620     albertel 8364:        $courseprivid=$env{'request.course.id'};
                   8365:        if ($env{'request.course.sec'}) {
                   8366:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8367:        }
                   8368:        $courseprivid=~s/\_/\//;
                   8369:        my $checkreferer=1;
1.232     www      8370:        my ($match,$cond)=&is_on_map($uri);
                   8371:        if ($match) {
                   8372:            $statecond=$cond;
1.620     albertel 8373:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8374:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8375:                my $value = $1;
                   8376:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8377:22):                    my $deeplinkblock;
                   8378:22):                    unless ($nodeeplinkcheck) {
                   8379:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8380:22):                    }
                   8381:22):                    if ($deeplinkblock) {
                   8382:22):                        $thisallowed = 'D';
                   8383:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8384:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8385:                    } else {
1.1172.2.126  raeburn  8386:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8387:                        if (@blockers > 0) {
                   8388:                            $thisallowed = 'B';
                   8389:                        } else {
                   8390:                            $thisallowed.=$value;
                   8391:                        }
1.1162    raeburn  8392:                    }
                   8393:                } else {
                   8394:                    $thisallowed.=$value;
                   8395:                }
1.52      www      8396:                $checkreferer=0;
                   8397:            }
1.29      www      8398:        }
1.1172.2.126  raeburn  8399: 
1.148     www      8400:        if ($checkreferer) {
1.620     albertel 8401: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8402:             unless ($refuri) {
1.800     albertel 8403:                 foreach my $key (keys(%env)) {
                   8404: 		    if ($key=~/^httpref\..*\*/) {
                   8405: 			my $pattern=$key;
1.156     www      8406:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8407:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8408:                         $pattern=~s/\//\\\//g;
1.152     www      8409:                         if ($orguri=~/$pattern/) {
1.800     albertel 8410: 			    $refuri=$env{$key};
1.148     www      8411:                         }
                   8412:                     }
1.191     harris41 8413:                 }
1.148     www      8414:             }
1.232     www      8415: 
1.148     www      8416:          if ($refuri) { 
1.152     www      8417: 	  $refuri=&declutter($refuri);
1.232     www      8418:           my ($match,$cond)=&is_on_map($refuri);
                   8419:             if ($match) {
                   8420:               my $refstatecond=$cond;
1.620     albertel 8421:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8422:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8423:                   my $value = $1;
                   8424:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8425:22):                       my $deeplinkblock;
                   8426:22):                       unless ($nodeeplinkcheck) {
                   8427:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8428:22):                       }
                   8429:22):                       if ($deeplinkblock) {
                   8430:22):                           $thisallowed = 'D';
                   8431:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8432:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8433:                       } else {
1.1172.2.127  raeburn  8434:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8435:                           if (@blockers > 0) {
                   8436:                               $thisallowed = 'B';
                   8437:                           } else {
                   8438:                               $thisallowed.=$value;
                   8439:                           }
1.1162    raeburn  8440:                       }
                   8441:                   } else {
                   8442:                       $thisallowed.=$value;
                   8443:                   }
1.53      www      8444:                   $uri=$refuri;
                   8445:                   $statecond=$refstatecond;
1.52      www      8446:               }
                   8447:           }
1.148     www      8448:         }
1.29      www      8449:        }
1.52      www      8450:    }
1.29      www      8451: 
1.52      www      8452: #
1.103     harris41 8453: # Gathered now: all privileges that could apply, and condition number
1.52      www      8454: # 
                   8455: #
                   8456: # Full or no access?
                   8457: #
1.29      www      8458: 
1.52      www      8459:     if ($thisallowed=~/F/) {
                   8460: 	return 'F';
                   8461:     }
1.29      www      8462: 
1.52      www      8463:     unless ($thisallowed) {
                   8464:         return '';
                   8465:     }
1.29      www      8466: 
1.52      www      8467: # Restrictions exist, deal with them
                   8468: #
                   8469: #   C:according to course preferences
                   8470: #   R:according to resource settings
                   8471: #   L:unless locked
                   8472: #   X:according to user session state
                   8473: #
                   8474: 
                   8475: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8476: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8477: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8478: # courses, and 2 minutes for current course, in which user has st or ta role
                   8479: # which is neither expired nor a future role (unless current course).
1.52      www      8480: 
1.1172.2.142  raeburn  8481:     my ($needlockcheck,$now,$crsonly);
1.52      www      8482:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8483:         $now = time;
                   8484:         if ($priv eq 'bre') {
                   8485:             if ($uri ne '') {
                   8486:                 if ($orguri =~ m{^/+res/}) {
                   8487:                     if ($uri =~ m{^lib/templates/}) {
                   8488:                         if ($env{'request.course.id'}) {
                   8489:                             $crsonly = 1;
                   8490:                             $needlockcheck = 1;
                   8491:                         }
                   8492:                     } else {
                   8493:                         $needlockcheck = 1;
                   8494:                     }
                   8495:                 } elsif ($env{'request.course.id'}) {
                   8496:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8497:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8498:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8499:                         $crsonly = 1;
                   8500:                     }
                   8501:                     $needlockcheck = 1;
                   8502:                 }
                   8503:             }
                   8504:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8505:             $needlockcheck = 1;
                   8506:         }
                   8507:     }
                   8508:     if ($needlockcheck) {
                   8509:         foreach my $envkey (keys(%env)) {
1.54      www      8510:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8511:                my $courseid=$2;
                   8512:                my $roleid=$1.'.'.$2;
1.92      www      8513:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8514:                unless ($env{'request.role'} eq $roleid) {
                   8515:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8516:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8517:                }
1.54      www      8518:                my $expiretime=600;
1.620     albertel 8519:                if ($env{'request.role'} eq $roleid) {
1.54      www      8520: 		  $expiretime=120;
                   8521:                }
                   8522: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8523:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8524:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8525: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8526:                }
1.620     albertel 8527:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8528:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8529: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8530:                        &log($env{'user.domain'},$env{'user.name'},
                   8531:                             $env{'user.home'},
1.57      www      8532:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8533:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8534:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8535: 		       return '';
                   8536:                    }
                   8537:                }
1.620     albertel 8538:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8539:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8540: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8541:                        &log($env{'user.domain'},$env{'user.name'},
                   8542:                             $env{'user.home'},
1.57      www      8543:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8544:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8545:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8546: 		       return '';
                   8547:                    }
                   8548:                }
                   8549: 	   }
1.29      www      8550:        }
1.52      www      8551:     }
1.1172.2.126  raeburn  8552: 
1.52      www      8553: #
                   8554: # Rest of the restrictions depend on selected course
                   8555: #
                   8556: 
1.620     albertel 8557:     unless ($env{'request.course.id'}) {
1.766     albertel 8558: 	if ($thisallowed eq 'A') {
                   8559: 	    return 'A';
1.814     raeburn  8560:         } elsif ($thisallowed eq 'B') {
                   8561:             return 'B';
1.766     albertel 8562: 	} else {
                   8563: 	    return '1';
                   8564: 	}
1.52      www      8565:     }
1.29      www      8566: 
1.52      www      8567: #
                   8568: # Now user is definitely in a course
                   8569: #
1.53      www      8570: 
                   8571: 
                   8572: # Course preferences
                   8573: 
                   8574:    if ($thisallowed=~/C/) {
1.620     albertel 8575:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8576:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8577:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8578: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8579: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8580: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8581: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8582: 			$env{'request.course.id'});
                   8583: 	   }
1.237     www      8584:            return '';
                   8585:        }
                   8586: 
1.620     albertel 8587:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8588: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8589: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8590: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8591: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8592: 			$env{'request.course.id'});
                   8593: 	   }
1.54      www      8594:            return '';
                   8595:        }
1.53      www      8596:    }
                   8597: 
                   8598: # Resource preferences
                   8599: 
                   8600:    if ($thisallowed=~/R/) {
1.620     albertel 8601:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8602:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8603: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8604: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8605: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8606: 	   }
                   8607: 	   return '';
1.54      www      8608:        }
1.53      www      8609:    }
1.30      www      8610: 
1.1172.2.146.  .1(raebu 8611:22): # Restricted for deeplinked session?
                   8612:22): 
                   8613:22):     if ($env{'request.deeplink.login'}) {
                   8614:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8615:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8616:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8617:22):                 return '';
                   8618:22):             }
                   8619:22):         }
                   8620:22):     }
                   8621:22): 
1.246     www      8622: # Restricted by state or randomout?
1.30      www      8623: 
1.52      www      8624:    if ($thisallowed=~/X/) {
1.620     albertel 8625:       if ($env{'acc.randomout'}) {
1.579     albertel 8626: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8627:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8628:             return ''; 
                   8629:          }
1.247     www      8630:       }
                   8631:       if (&condval($statecond)) {
1.52      www      8632: 	 return '2';
                   8633:       } else {
                   8634:          return '';
                   8635:       }
                   8636:    }
1.30      www      8637: 
1.766     albertel 8638:     if ($thisallowed eq 'A') {
                   8639: 	return 'A';
1.814     raeburn  8640:     } elsif ($thisallowed eq 'B') {
                   8641:         return 'B';
1.1172.2.146.  .1(raebu 8642:22):     } elsif ($thisallowed eq 'D') {
                   8643:22):         return 'D';
1.766     albertel 8644:     }
1.52      www      8645:    return 'F';
1.232     www      8646: }
1.1162    raeburn  8647: 
1.1172.2.13  raeburn  8648: # ------------------------------------------- Check construction space access
                   8649: 
                   8650: sub constructaccess {
                   8651:     my ($url,$setpriv)=@_;
                   8652: 
                   8653: # We do not allow editing of previous versions of files
                   8654:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8655: 
                   8656: # Get username and domain from URL
                   8657:     my ($ownername,$ownerdomain,$ownerhome);
                   8658: 
                   8659:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8660:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8661: 
                   8662: # The URL does not really point to any authorspace, forget it
                   8663:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8664: 
                   8665: # Now we need to see if the user has access to the authorspace of
                   8666: # $ownername at $ownerdomain
                   8667: 
                   8668:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8669: # Real author for this?
                   8670:        $ownerhome = $env{'user.home'};
                   8671:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8672:           return ($ownername,$ownerdomain,$ownerhome);
                   8673:        }
                   8674:     } else {
                   8675: # Co-author for this?
                   8676:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8677:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8678:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8679:             return ($ownername,$ownerdomain,$ownerhome);
                   8680:         }
                   8681:     }
                   8682: 
                   8683: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8684: # we might as well leave
                   8685:    unless ($setpriv) { return ''; }
                   8686: 
                   8687: # Backdoor access?
                   8688:     my $allowed=&allowed('eco',$ownerdomain);
                   8689: # Nope
                   8690:     unless ($allowed) { return ''; }
                   8691: # Looks like we may have access, but could be locked by the owner of the construction space
                   8692:     if ($allowed eq 'U') {
                   8693:         my %blocked=&get('environment',['domcoord.author'],
                   8694:                          $ownerdomain,$ownername);
                   8695: # Is blocked by owner
                   8696:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8697:     }
                   8698:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8699: # Grant temporary access
                   8700:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8701:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8702:         if (!$update) { $update = $then; }
                   8703:         my $refresh=$env{'user.refresh.time'};
                   8704:         if (!$refresh) { $refresh = $update; }
                   8705:         my $now = time;
                   8706:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8707:                            $now,'ca','constructaccess');
                   8708:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8709:         return($ownername,$ownerdomain,$ownerhome);
                   8710:     }
                   8711: # No business here
                   8712:     return '';
                   8713: }
                   8714: 
1.1172.2.66  raeburn  8715: # ----------------------------------------------------------- Content Blocking
                   8716: 
                   8717: {
                   8718: # Caches for faster Course Contents display where content blocking
                   8719: # is in operation (i.e., interval param set) for timed quiz.
                   8720: #
                   8721: # User for whom data are being temporarily cached.
                   8722: my $cacheduser='';
1.1172.2.126  raeburn  8723: # Course for which data are being temporarily cached.
                   8724: my $cachedcid='';
1.1172.2.66  raeburn  8725: # Cached blockers for this user (a hash of blocking items).
                   8726: my %cachedblockers=();
                   8727: # When the data were last cached.
                   8728: my $cachedlast='';
                   8729: 
                   8730: sub load_all_blockers {
1.1172.2.128  raeburn  8731:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8732:     if (($uname ne '') && ($udom ne '')) {
                   8733:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8734:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8735:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8736:             return;
                   8737:         }
                   8738:     }
                   8739:     $cachedlast=time;
                   8740:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8741:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8742:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8743:     return;
1.1172.2.66  raeburn  8744: }
                   8745: 
1.1162    raeburn  8746: sub get_comm_blocks {
                   8747:     my ($cdom,$cnum) = @_;
                   8748:     if ($cdom eq '' || $cnum eq '') {
                   8749:         return unless ($env{'request.course.id'});
                   8750:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8751:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8752:     }
                   8753:     my %commblocks;
                   8754:     my $hashid=$cdom.'_'.$cnum;
                   8755:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8756:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8757:         %commblocks = %{$blocksref};
                   8758:     } else {
                   8759:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8760:         my $cachetime = 600;
                   8761:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8762:     }
                   8763:     return %commblocks;
                   8764: }
                   8765: 
1.1172.2.66  raeburn  8766: sub get_commblock_resources {
                   8767:     my ($blocks) = @_;
                   8768:     my %blockers = ();
                   8769:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8770:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8771:     if ($env{'request.course.sec'}) {
                   8772:         $courseurl .= '/'.$env{'request.course.sec'};
                   8773:     }
                   8774:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8775:     my %commblocks;
                   8776:     if (ref($blocks) eq 'HASH') {
                   8777:         %commblocks = %{$blocks};
                   8778:     } else {
                   8779:         %commblocks = &get_comm_blocks();
                   8780:     }
1.1172.2.66  raeburn  8781:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8782:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8783:     return %blockers unless (ref($navmap));
                   8784:     my $now = time;
1.1162    raeburn  8785:     foreach my $block (keys(%commblocks)) {
                   8786:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8787:             my ($start,$end) = ($1,$2);
                   8788:             if ($start <= $now && $end >= $now) {
                   8789:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8790:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8791:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8792:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8793:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8794:                             }
                   8795:                         }
                   8796:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8797:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8798:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8799:                             }
                   8800:                         }
                   8801:                     }
                   8802:                 }
                   8803:             }
                   8804:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8805:             my $item = $1;
                   8806:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8807:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8808:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8809:                     my $type = 'map';
                   8810:                     if ($item eq 'course') {
                   8811:                         $type = 'course';
                   8812:                         @interval=&EXT("resource.0.interval");
                   8813:                     } else {
                   8814:                         if ($item =~ /___\d+___/) {
                   8815:                             $type = 'resource';
                   8816:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8817:                         } else {
1.1172.2.142  raeburn  8818:                             $mapname = &deversion($item);
                   8819:                             if (ref($navmap)) {
                   8820:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8821:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8822:                             }
                   8823:                         }
1.1172.2.66  raeburn  8824:                     }
1.1172.2.146.  .1(raebu 8825:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8826:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8827:                         my $first_access;
                   8828:                         if ($type eq 'resource') {
                   8829:                             $first_access=&get_first_access($interval[1],$item);
                   8830:                         } elsif ($type eq 'map') {
                   8831:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8832:                         } else {
                   8833:                             $first_access=&get_first_access($interval[1]);
                   8834:                         }
                   8835:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8836:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8837:                             if ($timesup > $now) {
                   8838:                                 my $activeblock;
1.1172.2.142  raeburn  8839:                                 if ($type eq 'resource') {
                   8840:                                     if (ref($navmap)) {
                   8841:                                         my $res = $navmap->getBySymb($item);
                   8842:                                         if ($res->answerable()) {
                   8843:                                             $activeblock = 1;
                   8844:                                         }
                   8845:                                     }
                   8846:                                 } elsif ($type eq 'map') {
                   8847:                                     my $mapsymb = &symbread($mapname,1);
                   8848:                                     if (($mapsymb) && (ref($navmap))) {
                   8849:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8850:                                         if (ref($mapres)) {
                   8851:                                             my $first = $mapres->map_start();
                   8852:                                             my $finish = $mapres->map_finish();
                   8853:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8854:                                             if (ref($it)) {
                   8855:                                                 my $res;
                   8856:                                                 while ($res = $it->next(undef,1)) {
                   8857:                                                     next unless (ref($res));
                   8858:                                                     my $symb = $res->symb();
                   8859:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8860:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8861:                                                     if ($interval[1] eq 'map') {
                   8862:                                                         if ($res->answerable()) {
                   8863:                                                             $activeblock = 1;
                   8864:                                                             last;
                   8865:                                                         }
                   8866:                                                     }
                   8867:                                                 }
                   8868:                                             }
                   8869:                                         }
1.1172.2.66  raeburn  8870:                                     }
                   8871:                                 }
                   8872:                                 if ($activeblock) {
                   8873:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8874:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8875:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8876:                                          }
                   8877:                                     }
                   8878:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8879:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8880:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8881:                                         }
1.1162    raeburn  8882:                                     }
                   8883:                                 }
                   8884:                             }
                   8885:                         }
                   8886:                     }
                   8887:                 }
                   8888:             }
                   8889:         }
                   8890:     }
1.1172.2.66  raeburn  8891:     return %blockers;
1.1162    raeburn  8892: }
                   8893: 
1.1172.2.66  raeburn  8894: sub has_comm_blocking {
1.1172.2.128  raeburn  8895:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8896:     my @blockers;
                   8897:     return unless ($env{'request.course.id'});
                   8898:     return unless ($priv eq 'bre');
                   8899:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8900:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8901:     if ($env{'request.course.sec'}) {
                   8902:         $courseurl .= '/'.$env{'request.course.sec'};
                   8903:     }
                   8904:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8905:     my %blockinfo;
                   8906:     if (ref($blocks) eq 'HASH') {
                   8907:         %blockinfo = &get_commblock_resources($blocks);
                   8908:     } else {
                   8909:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8910:         %blockinfo = %cachedblockers;
                   8911:     }
                   8912:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8913:     my (%possibles,@symbs);
                   8914:     if (!$symb) {
1.1172.2.128  raeburn  8915:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8916:     }
1.1172.2.66  raeburn  8917:     if ($symb) {
                   8918:         @symbs = ($symb);
                   8919:     } elsif (keys(%possibles)) {
                   8920:         @symbs = keys(%possibles);
                   8921:     }
                   8922:     my $noblock;
                   8923:     foreach my $symb (@symbs) {
                   8924:         last if ($noblock);
                   8925:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8926:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8927:             if ($block =~ /^firstaccess____(.+)$/) {
                   8928:                 my $item = $1;
1.1172.2.126  raeburn  8929:                 unless ($blocked) {
                   8930:                     if (($item eq $map) || ($item eq $symb)) {
                   8931:                         $noblock = 1;
                   8932:                         last;
                   8933:                     }
1.1172.2.66  raeburn  8934:                 }
1.1162    raeburn  8935:             }
1.1172.2.128  raeburn  8936:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8937:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8938:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8939:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8940:                             push(@blockers,$block);
                   8941:                         }
                   8942:                     }
                   8943:                 }
1.1172.2.128  raeburn  8944:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8945:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8946:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8947:                             push(@blockers,$block);
                   8948:                         }
1.1172.2.66  raeburn  8949:                     }
                   8950:                 }
1.1162    raeburn  8951:             }
                   8952:         }
                   8953:     }
1.1172.2.126  raeburn  8954:     unless ($noblock) {
                   8955:         return @blockers;
                   8956:     }
                   8957:     return;
1.1172.2.66  raeburn  8958: }
1.1162    raeburn  8959: }
                   8960: 
1.1172.2.146.  .1(raebu 8961:22): sub deeplink_check {
                   8962:22):     my ($priv,$symb,$uri) = @_;
                   8963:22):     return unless ($env{'request.course.id'});
                   8964:22):     return unless ($priv eq 'bre');
                   8965:22):     return if ($env{'request.state'} eq 'construct');
                   8966:22):     return if ($env{'request.role.adv'});
                   8967:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8968:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8969:22):     my (%possibles,@symbs);
                   8970:22):     if (!$symb) {
                   8971:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8972:22):     }
                   8973:22):     if ($symb) {
                   8974:22):         @symbs = ($symb);
                   8975:22):     } elsif (keys(%possibles)) {
                   8976:22):         @symbs = keys(%possibles);
                   8977:22):     }
                   8978:22): 
                   8979:22):     my ($deeplink_symb,$allow);
                   8980:22):     if ($env{'request.deeplink.login'}) {
                   8981:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8982:22):     }
                   8983:22):     foreach my $symb (@symbs) {
                   8984:22):         last if ($allow);
                   8985:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8986:22):         if ($deeplink eq '') {
                   8987:22):             $allow = 1;
                   8988:22):         } else {
                   8989:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8990:22):             if ($state ne 'only') {
                   8991:22):                 $allow = 1;
                   8992:22):             } else {
                   8993:22):                 my $check_deeplink_entry;
                   8994:22):                 if ($protect ne 'none') {
                   8995:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8996:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8997:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8998:22):                             $check_deeplink_entry = 1
                   8999:22):                         }
                   9000:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9001:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9002:22):                             $check_deeplink_entry = 1;
                   9003:22):                         }
                   9004:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9005:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9006:22):                             $check_deeplink_entry = 1;
                   9007:22):                         }
                   9008:22):                     }
                   9009:22):                 }
                   9010:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9011:22):                     if ($scope eq 'res') {
                   9012:22):                         if ($symb eq $deeplink_symb) {
                   9013:22):                             $allow = 1;
                   9014:22):                         }
                   9015:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9016:22):                         my ($map_from_symb,$map_from_login);
                   9017:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9018:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9019:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9020:22):                         } else {
                   9021:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9022:22):                         }
                   9023:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9024:22):                             if ($map_from_symb eq $map_from_login) {
                   9025:22):                                 $allow = 1;
                   9026:22):                             } elsif ($scope eq 'rec') {
                   9027:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9028:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9029:22):                                     $allow = 1;
                   9030:22):                                 }
                   9031:22):                             }
                   9032:22):                         }
                   9033:22):                     }
                   9034:22):                 }
                   9035:22):             }
                   9036:22):         }
                   9037:22):     }
                   9038:22):     return if ($allow);
                   9039:22):     return 1;
                   9040:22): }
                   9041:22): 
1.1172.2.66  raeburn  9042: # -------------------------------- Deversion and split uri into path an filename
                   9043: 
1.1133    foxr     9044: #
1.1172.2.66  raeburn  9045: #   Removes the version from a URI and
1.1133    foxr     9046: #   splits it in to its filename and path to the filename.
                   9047: #   Seems like File::Basename could have done this more clearly.
                   9048: #   Parameters:
                   9049: #      $uri   - input URI
                   9050: #   Returns:
                   9051: #     Two element list consisting of 
                   9052: #     $pathname  - the URI up to and excluding the trailing /
                   9053: #     $filename  - The part of the URI following the last /
                   9054: #  NOTE:
                   9055: #    Another realization of this is simply:
                   9056: #    use File::Basename;
                   9057: #    ...
                   9058: #    $uri = shift;
                   9059: #    $filename = basename($uri);
                   9060: #    $path     = dirname($uri);
                   9061: #    return ($filename, $path);
                   9062: #
                   9063: #     The implementation below is probably faster however.
                   9064: #
1.710     albertel 9065: sub split_uri_for_cond {
                   9066:     my $uri=&deversion(&declutter(shift));
                   9067:     my @uriparts=split(/\//,$uri);
                   9068:     my $filename=pop(@uriparts);
                   9069:     my $pathname=join('/',@uriparts);
                   9070:     return ($pathname,$filename);
                   9071: }
1.232     www      9072: # --------------------------------------------------- Is a resource on the map?
                   9073: 
                   9074: sub is_on_map {
1.710     albertel 9075:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9076:     #Trying to find the conditional for the file
1.620     albertel 9077:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9078: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9079:     if ($match) {
1.289     bowersj2 9080: 	return (1,$1);
                   9081:     } else {
1.434     www      9082: 	return (0,0);
1.289     bowersj2 9083:     }
1.12      www      9084: }
                   9085: 
1.427     www      9086: # --------------------------------------------------------- Get symb from alias
                   9087: 
                   9088: sub get_symb_from_alias {
                   9089:     my $symb=shift;
                   9090:     my ($map,$resid,$url)=&decode_symb($symb);
                   9091: # Already is a symb
                   9092:     if ($url) { return $symb; }
                   9093: # Must be an alias
                   9094:     my $aliassymb='';
                   9095:     my %bighash;
1.620     albertel 9096:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9097:                             &GDBM_READER(),0640)) {
                   9098:         my $rid=$bighash{'mapalias_'.$symb};
                   9099: 	if ($rid) {
                   9100: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9101: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9102: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9103: 	}
                   9104:         untie %bighash;
                   9105:     }
                   9106:     return $aliassymb;
                   9107: }
                   9108: 
1.12      www      9109: # ----------------------------------------------------------------- Define Role
                   9110: 
                   9111: sub definerole {
                   9112:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9113:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9114:     foreach my $role (split(':',$sysrole)) {
                   9115: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9116:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9117:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9118: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9119:                return "refused:s:$crole&$cqual"; 
                   9120:             }
                   9121:         }
1.191     harris41 9122:     }
1.800     albertel 9123:     foreach my $role (split(':',$domrole)) {
                   9124: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9125:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9126:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9127: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9128:                return "refused:d:$crole&$cqual"; 
                   9129:             }
                   9130:         }
1.191     harris41 9131:     }
1.800     albertel 9132:     foreach my $role (split(':',$courole)) {
                   9133: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9134:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9135:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9136: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9137:                return "refused:c:$crole&$cqual"; 
                   9138:             }
                   9139:         }
1.191     harris41 9140:     }
1.1172.2.84  raeburn  9141:     my $uhome;
                   9142:     if (($uname ne '') && ($udom ne '')) {
                   9143:         $uhome = &homeserver($uname,$udom);
                   9144:         return $uhome if ($uhome eq 'no_host');
                   9145:     } else {
                   9146:         $uname = $env{'user.name'};
                   9147:         $udom = $env{'user.domain'};
                   9148:         $uhome = $env{'user.home'};
                   9149:     }
1.620     albertel 9150:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9151:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9152:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9153:     return reply($command,$uhome);
1.12      www      9154:   } else {
                   9155:     return 'refused';
                   9156:   }
1.105     harris41 9157: }
                   9158: 
                   9159: # ---------------- Make a metadata query against the network of library servers
                   9160: 
                   9161: sub metadata_query {
1.1172.2.33  raeburn  9162:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9163:     my %rhash;
1.845     albertel 9164:     my %libserv = &all_library();
1.244     matthew  9165:     my @server_list = (defined($server_array) ? @$server_array
                   9166:                                               : keys(%libserv) );
                   9167:     for my $server (@server_list) {
1.1172.2.33  raeburn  9168:         my $domains = '';
                   9169:         if (ref($domains_hash) eq 'HASH') {
                   9170:             $domains = $domains_hash->{$server};    
                   9171:         }
1.118     harris41 9172: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9173: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9174: 	    $rhash{$server}=$reply;
                   9175: 	}
                   9176: 	else {
                   9177: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9178: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9179: 			     $server);
                   9180: 	    $rhash{$server}=$reply;
                   9181: 	}
1.112     harris41 9182:     }
1.118     harris41 9183:     return \%rhash;
1.240     www      9184: }
                   9185: 
                   9186: # ----------------------------------------- Send log queries and wait for reply
                   9187: 
                   9188: sub log_query {
                   9189:     my ($uname,$udom,$query,%filters)=@_;
                   9190:     my $uhome=&homeserver($uname,$udom);
                   9191:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9192:     my $uhost=&hostname($uhome);
1.800     albertel 9193:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9194:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9195:                        $uhome);
1.479     albertel 9196:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9197:     return get_query_reply($queryid);
                   9198: }
                   9199: 
1.818     raeburn  9200: # -------------------------- Update MySQL table for portfolio file
                   9201: 
                   9202: sub update_portfolio_table {
1.821     raeburn  9203:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9204:     if ($group ne '') {
                   9205:         $file_name =~s /^\Q$group\E//;
                   9206:     }
1.818     raeburn  9207:     my $homeserver = &homeserver($uname,$udom);
                   9208:     my $queryid=
1.821     raeburn  9209:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9210:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9211:     my $reply = &get_query_reply($queryid);
                   9212:     return $reply;
                   9213: }
                   9214: 
1.899     raeburn  9215: # -------------------------- Update MySQL allusers table
                   9216: 
                   9217: sub update_allusers_table {
                   9218:     my ($uname,$udom,$names) = @_;
                   9219:     my $homeserver = &homeserver($uname,$udom);
                   9220:     my $queryid=
                   9221:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9222:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9223:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9224:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9225:                'generation='.&escape($names->{'generation'}).'%%'.
                   9226:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9227:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9228:     return;
1.899     raeburn  9229: }
                   9230: 
1.508     raeburn  9231: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9232: 
                   9233: sub fetch_enrollment_query {
1.511     raeburn  9234:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9235:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9236:     my $maxtries = 1;
1.508     raeburn  9237:     if ($context eq 'automated') {
                   9238:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9239:         $sleep = 2;
                   9240:         $loopmax = 100;
1.547     raeburn  9241:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9242:     } else {
                   9243:         $homeserver = &homeserver($cnum,$dom);
                   9244:     }
1.838     albertel 9245:     my $host=&hostname($homeserver);
1.506     raeburn  9246:     my $cmd = '';
1.1000    raeburn  9247:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9248:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9249:     }
                   9250:     $cmd =~ s/%%$//;
                   9251:     $cmd = &escape($cmd);
                   9252:     my $query = 'fetchenrollment';
1.620     albertel 9253:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9254:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9255:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9256:         return 'error: '.$queryid;
                   9257:     }
1.1172.2.93  raeburn  9258:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9259:     my $tries = 1;
                   9260:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9261:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9262:         $tries ++;
                   9263:     }
1.526     raeburn  9264:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9265:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9266:     } else {
1.901     albertel 9267:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9268:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9269:             foreach my $line (@responses) {
                   9270:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9271:                 $$replyref{$key} = $value;
                   9272:             }
                   9273:         } else {
1.1117    foxr     9274:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9275:             foreach my $line (@responses) {
                   9276:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9277:                 $$replyref{$key} = $value;
                   9278:                 if ($value > 0) {
1.800     albertel 9279:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9280:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9281:                         my $destname = $pathname.'/'.$filename;
                   9282:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9283:                         if ($xml_classlist =~ /^error/) {
                   9284:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9285:                         } else {
1.1172.2.96  raeburn  9286:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9287:                                 print FILE &unescape($xml_classlist);
                   9288:                                 close(FILE);
1.526     raeburn  9289:                             } else {
                   9290:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9291:                             }
                   9292:                         }
                   9293:                     }
                   9294:                 }
                   9295:             }
                   9296:         }
                   9297:         return 'ok';
                   9298:     }
                   9299:     return 'error';
                   9300: }
                   9301: 
1.242     www      9302: sub get_query_reply {
1.1172.2.79  raeburn  9303:     my ($queryid,$sleep,$loopmax) = @_;
                   9304:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9305:         $sleep = 0.2;
                   9306:     }
                   9307:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9308:         $loopmax = 100;
                   9309:     }
1.1117    foxr     9310:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9311:     my $reply='';
1.1172.2.79  raeburn  9312:     for (1..$loopmax) {
                   9313: 	sleep($sleep);
1.240     www      9314:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9315: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9316: 		$reply = join('',<$fh>);
                   9317: 		close($fh);
1.240     www      9318: 	   } else { return 'error: reply_file_error'; }
1.242     www      9319:            return &unescape($reply);
                   9320: 	}
1.240     www      9321:     }
1.242     www      9322:     return 'timeout:'.$queryid;
1.240     www      9323: }
                   9324: 
                   9325: sub courselog_query {
1.241     www      9326: #
                   9327: # possible filters:
                   9328: # url: url or symb
                   9329: # username
                   9330: # domain
                   9331: # action: view, submit, grade
                   9332: # start: timestamp
                   9333: # end: timestamp
                   9334: #
1.240     www      9335:     my (%filters)=@_;
1.620     albertel 9336:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9337:     if ($filters{'url'}) {
                   9338: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9339:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9340:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9341:     }
1.620     albertel 9342:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9343:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9344:     return &log_query($cname,$cdom,'courselog',%filters);
                   9345: }
                   9346: 
                   9347: sub userlog_query {
1.858     raeburn  9348: #
                   9349: # possible filters:
                   9350: # action: log check role
                   9351: # start: timestamp
                   9352: # end: timestamp
                   9353: #
1.240     www      9354:     my ($uname,$udom,%filters)=@_;
                   9355:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9356: }
                   9357: 
1.506     raeburn  9358: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9359: 
                   9360: sub auto_run {
1.508     raeburn  9361:     my ($cnum,$cdom) = @_;
1.876     raeburn  9362:     my $response = 0;
                   9363:     my $settings;
                   9364:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9365:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9366:         $settings = $domconfig{'autoenroll'};
                   9367:         if ($settings->{'run'} eq '1') {
                   9368:             $response = 1;
                   9369:         }
                   9370:     } else {
1.934     raeburn  9371:         my $homeserver;
                   9372:         if (&is_course($cdom,$cnum)) {
                   9373:             $homeserver = &homeserver($cnum,$cdom);
                   9374:         } else {
                   9375:             $homeserver = &domain($cdom,'primary');
                   9376:         }
                   9377:         if ($homeserver ne 'no_host') {
                   9378:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9379:         }
1.876     raeburn  9380:     }
1.506     raeburn  9381:     return $response;
                   9382: }
1.776     albertel 9383: 
1.506     raeburn  9384: sub auto_get_sections {
1.508     raeburn  9385:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9386:     my $homeserver;
                   9387:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9388:         $homeserver = &homeserver($cnum,$cdom);
                   9389:     }
                   9390:     if (!defined($homeserver)) { 
                   9391:         if ($cdom =~ /^$match_domain$/) {
                   9392:             $homeserver = &domain($cdom,'primary');
                   9393:         }
                   9394:     }
                   9395:     my @secs;
                   9396:     if (defined($homeserver)) {
                   9397:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9398:         unless ($response eq 'refused') {
                   9399:             @secs = split(/:/,$response);
                   9400:         }
1.506     raeburn  9401:     }
                   9402:     return @secs;
                   9403: }
1.776     albertel 9404: 
1.506     raeburn  9405: sub auto_new_course {
1.1099    raeburn  9406:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9407:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9408:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9409:     return $response;
                   9410: }
1.776     albertel 9411: 
1.506     raeburn  9412: sub auto_validate_courseID {
1.508     raeburn  9413:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9414:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9415:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9416:     return $response;
                   9417: }
1.776     albertel 9418: 
1.1007    raeburn  9419: sub auto_validate_instcode {
1.1020    raeburn  9420:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9421:     my ($homeserver,$response);
                   9422:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9423:         $homeserver = &homeserver($cnum,$cdom);
                   9424:     }
                   9425:     if (!defined($homeserver)) {
                   9426:         if ($cdom =~ /^$match_domain$/) {
                   9427:             $homeserver = &domain($cdom,'primary');
                   9428:         }
                   9429:     }
1.1065    raeburn  9430:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9431:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9432:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9433:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9434: }
                   9435: 
1.1172.2.141  raeburn  9436: sub auto_validate_inst_crosslist {
                   9437:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9438:     my ($homeserver,$response);
                   9439:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9440:         $homeserver = &homeserver($cnum,$cdom);
                   9441:     }
                   9442:     if (!defined($homeserver)) {
                   9443:         if ($cdom =~ /^$match_domain$/) {
                   9444:             $homeserver = &domain($cdom,'primary');
                   9445:         }
                   9446:     }
                   9447:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9448:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9449:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9450:                          &escape($coowner),$homeserver);
                   9451:     }
                   9452:     return $response;
                   9453: }
                   9454: 
1.506     raeburn  9455: sub auto_create_password {
1.873     raeburn  9456:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9457:     my ($homeserver,$response);
1.506     raeburn  9458:     my $create_passwd = 0;
                   9459:     my $authchk = '';
1.873     raeburn  9460:     if ($udom =~ /^$match_domain$/) {
                   9461:         $homeserver = &domain($udom,'primary');
                   9462:     }
                   9463:     if ($homeserver eq '') {
                   9464:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9465:             $homeserver = &homeserver($cnum,$cdom);
                   9466:         }
                   9467:     }
                   9468:     if ($homeserver eq '') {
                   9469:         $authchk = 'nodomain';
1.506     raeburn  9470:     } else {
1.873     raeburn  9471:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9472:         if ($response eq 'refused') {
                   9473:             $authchk = 'refused';
                   9474:         } else {
1.901     albertel 9475:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9476:         }
1.506     raeburn  9477:     }
                   9478:     return ($authparam,$create_passwd,$authchk);
                   9479: }
                   9480: 
1.706     raeburn  9481: sub auto_photo_permission {
                   9482:     my ($cnum,$cdom,$students) = @_;
                   9483:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9484:     my ($outcome,$perm_reqd,$conditions) = 
                   9485: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9486:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9487: 	return (undef,undef);
                   9488:     }
1.706     raeburn  9489:     return ($outcome,$perm_reqd,$conditions);
                   9490: }
                   9491: 
                   9492: sub auto_checkphotos {
                   9493:     my ($uname,$udom,$pid) = @_;
                   9494:     my $homeserver = &homeserver($uname,$udom);
                   9495:     my ($result,$resulttype);
                   9496:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9497: 				   &escape($uname).':'.&escape($pid),
                   9498: 				   $homeserver));
1.709     albertel 9499:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9500: 	return (undef,undef);
                   9501:     }
1.706     raeburn  9502:     if ($outcome) {
                   9503:         ($result,$resulttype) = split(/:/,$outcome);
                   9504:     } 
                   9505:     return ($result,$resulttype);
                   9506: }
                   9507: 
                   9508: sub auto_photochoice {
                   9509:     my ($cnum,$cdom) = @_;
                   9510:     my $homeserver = &homeserver($cnum,$cdom);
                   9511:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9512: 						       &escape($cdom),
                   9513: 						       $homeserver)));
1.709     albertel 9514:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9515: 	return (undef,undef);
                   9516:     }
1.706     raeburn  9517:     return ($update,$comment);
                   9518: }
                   9519: 
                   9520: sub auto_photoupdate {
                   9521:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9522:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9523:     my $host=&hostname($homeserver);
1.706     raeburn  9524:     my $cmd = '';
                   9525:     my $maxtries = 1;
1.800     albertel 9526:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9527:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9528:     }
                   9529:     $cmd =~ s/%%$//;
                   9530:     $cmd = &escape($cmd);
                   9531:     my $query = 'institutionalphotos';
                   9532:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9533:     unless ($queryid=~/^\Q$host\E\_/) {
                   9534:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9535:         return 'error: '.$queryid;
                   9536:     }
                   9537:     my $reply = &get_query_reply($queryid);
                   9538:     my $tries = 1;
                   9539:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9540:         $reply = &get_query_reply($queryid);
                   9541:         $tries ++;
                   9542:     }
                   9543:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9544:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9545:     } else {
                   9546:         my @responses = split(/:/,$reply);
                   9547:         my $outcome = shift(@responses); 
                   9548:         foreach my $item (@responses) {
                   9549:             my ($key,$value) = split(/=/,$item);
                   9550:             $$photo{$key} = $value;
                   9551:         }
                   9552:         return $outcome;
                   9553:     }
                   9554:     return 'error';
                   9555: }
                   9556: 
1.521     raeburn  9557: sub auto_instcode_format {
1.793     albertel 9558:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9559: 	$cat_order) = @_;
1.521     raeburn  9560:     my $courses = '';
1.772     raeburn  9561:     my @homeservers;
1.521     raeburn  9562:     if ($caller eq 'global') {
1.841     albertel 9563: 	my %servers = &get_servers($codedom,'library');
                   9564: 	foreach my $tryserver (keys(%servers)) {
                   9565: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9566: 		push(@homeservers,$tryserver);
                   9567: 	    }
1.584     raeburn  9568:         }
1.1022    raeburn  9569:     } elsif ($caller eq 'requests') {
                   9570:         if ($codedom =~ /^$match_domain$/) {
                   9571:             my $chome = &domain($codedom,'primary');
                   9572:             unless ($chome eq 'no_host') {
                   9573:                 push(@homeservers,$chome);
                   9574:             }
                   9575:         }
1.521     raeburn  9576:     } else {
1.772     raeburn  9577:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9578:     }
1.793     albertel 9579:     foreach my $code (keys(%{$instcodes})) {
                   9580:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9581:     }
                   9582:     chop($courses);
1.772     raeburn  9583:     my $ok_response = 0;
                   9584:     my $response;
                   9585:     while (@homeservers > 0 && $ok_response == 0) {
                   9586:         my $server = shift(@homeservers); 
                   9587:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9588:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9589:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9590: 		split(/:/,$response);
1.772     raeburn  9591:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9592:             push(@{$codetitles},&str2array($codetitles_str));
                   9593:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9594:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9595:             $ok_response = 1;
                   9596:         }
                   9597:     }
                   9598:     if ($ok_response) {
1.521     raeburn  9599:         return 'ok';
1.772     raeburn  9600:     } else {
                   9601:         return $response;
1.521     raeburn  9602:     }
                   9603: }
                   9604: 
1.792     raeburn  9605: sub auto_instcode_defaults {
                   9606:     my ($domain,$returnhash,$code_order) = @_;
                   9607:     my @homeservers;
1.841     albertel 9608: 
                   9609:     my %servers = &get_servers($domain,'library');
                   9610:     foreach my $tryserver (keys(%servers)) {
                   9611: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9612: 	    push(@homeservers,$tryserver);
                   9613: 	}
1.792     raeburn  9614:     }
1.841     albertel 9615: 
1.792     raeburn  9616:     my $response;
1.841     albertel 9617:     foreach my $server (@homeservers) {
1.792     raeburn  9618:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9619:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9620: 	
                   9621: 	foreach my $pair (split(/\&/,$response)) {
                   9622: 	    my ($name,$value)=split(/\=/,$pair);
                   9623: 	    if ($name eq 'code_order') {
                   9624: 		@{$code_order} = split(/\&/,&unescape($value));
                   9625: 	    } else {
                   9626: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9627: 	    }
                   9628: 	}
                   9629: 	return 'ok';
1.792     raeburn  9630:     }
1.841     albertel 9631: 
                   9632:     return $response;
1.1003    raeburn  9633: }
                   9634: 
                   9635: sub auto_possible_instcodes {
1.1007    raeburn  9636:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9637:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9638:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9639:         return;
                   9640:     }
1.1003    raeburn  9641:     my (@homeservers,$uhome);
                   9642:     if (defined(&domain($domain,'primary'))) {
                   9643:         $uhome=&domain($domain,'primary');
                   9644:         push(@homeservers,&domain($domain,'primary'));
                   9645:     } else {
                   9646:         my %servers = &get_servers($domain,'library');
                   9647:         foreach my $tryserver (keys(%servers)) {
                   9648:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9649:                 push(@homeservers,$tryserver);
                   9650:             }
                   9651:         }
                   9652:     }
                   9653:     my $response;
                   9654:     foreach my $server (@homeservers) {
                   9655:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9656:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9657:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9658:             split(':',$response);
                   9659:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9660:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9661:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9662:             my ($name,$value)=split('=',$item);
                   9663:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9664:         }
                   9665:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9666:             my ($name,$value)=split('=',$item);
                   9667:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9668:         }
                   9669:         return 'ok';
                   9670:     }
                   9671:     return $response;
                   9672: }
1.792     raeburn  9673: 
1.1010    raeburn  9674: sub auto_courserequest_checks {
                   9675:     my ($dom) = @_;
1.1020    raeburn  9676:     my ($homeserver,%validations);
                   9677:     if ($dom =~ /^$match_domain$/) {
                   9678:         $homeserver = &domain($dom,'primary');
                   9679:     }
                   9680:     unless ($homeserver eq 'no_host') {
                   9681:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9682:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9683:             my @items = split(/&/,$response);
                   9684:             foreach my $item (@items) {
                   9685:                 my ($key,$value) = split('=',$item);
                   9686:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9687:             }
                   9688:         }
                   9689:     }
1.1010    raeburn  9690:     return %validations; 
                   9691: }
                   9692: 
1.1020    raeburn  9693: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9694:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9695:     my ($homeserver,$response);
                   9696:     if ($dom =~ /^$match_domain$/) {
                   9697:         $homeserver = &domain($dom,'primary');
                   9698:     }
1.1172.2.43  raeburn  9699:     unless ($homeserver eq 'no_host') {
                   9700:         my $customdata;
                   9701:         if (ref($custominfo) eq 'HASH') {
                   9702:             $customdata = &freeze_escape($custominfo);
                   9703:         }
1.1020    raeburn  9704:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9705:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9706:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9707:                                     $customdata,$homeserver));
1.1020    raeburn  9708:     }
                   9709:     return $response;
                   9710: }
                   9711: 
1.777     albertel 9712: sub auto_validate_class_sec {
1.918     raeburn  9713:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9714:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9715:     my $ownerlist;
                   9716:     if (ref($owners) eq 'ARRAY') {
                   9717:         $ownerlist = join(',',@{$owners});
                   9718:     } else {
                   9719:         $ownerlist = $owners;
                   9720:     }
1.773     raeburn  9721:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9722:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9723:     return $response;
                   9724: }
                   9725: 
1.1172.2.141  raeburn  9726: sub auto_instsec_reformat {
                   9727:     my ($cdom,$action,$instsecref) = @_;
                   9728:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9729:     my @homeservers;
                   9730:     if (defined(&domain($cdom,'primary'))) {
                   9731:         push(@homeservers,&domain($cdom,'primary'));
                   9732:     } else {
                   9733:         my %servers = &get_servers($cdom,'library');
                   9734:         foreach my $tryserver (keys(%servers)) {
                   9735:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9736:                 push(@homeservers,$tryserver);
                   9737:             }
                   9738:         }
                   9739:     }
                   9740:     my $response;
                   9741:     my %reformatted = %{$instsecref};
                   9742:     foreach my $server (@homeservers) {
                   9743:         if (ref($instsecref) eq 'HASH') {
                   9744:             my $info = &freeze_escape($instsecref);
                   9745:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9746:                                 $action.':'.$info,$server);
                   9747:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9748:             my @items = split(/&/,$response);
                   9749:             foreach my $item (@items) {
                   9750:                 my ($key,$value) = split(/=/,$item);
                   9751:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9752:             }
                   9753:         }
                   9754:     }
                   9755:     return %reformatted;
                   9756: }
                   9757: 
1.1172.2.94  raeburn  9758: sub auto_validate_instclasses {
                   9759:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9760:     my ($homeserver,%validations);
                   9761:     $homeserver = &homeserver($cnum,$cdom);
                   9762:     unless ($homeserver eq 'no_host') {
                   9763:         my $ownerlist;
                   9764:         if (ref($owners) eq 'ARRAY') {
                   9765:             $ownerlist = join(',',@{$owners});
                   9766:         } else {
                   9767:             $ownerlist = $owners;
                   9768:         }
                   9769:         if (ref($classesref) eq 'HASH') {
                   9770:             my $classes = &freeze_escape($classesref);
                   9771:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9772:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9773:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9774:                 my @items = split(/&/,$response);
                   9775:                 foreach my $item (@items) {
                   9776:                     my ($key,$value) = split('=',$item);
                   9777:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9778:                 }
                   9779:             }
                   9780:         }
                   9781:     }
                   9782:     return %validations;
                   9783: }
                   9784: 
1.1172.2.38  raeburn  9785: sub auto_crsreq_update {
                   9786:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9787:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9788:     my ($homeserver,%crsreqresponse);
                   9789:     if ($cdom =~ /^$match_domain$/) {
                   9790:         $homeserver = &domain($cdom,'primary');
                   9791:     }
                   9792:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9793:         my $info;
                   9794:         if (ref($inbound) eq 'HASH') {
                   9795:             $info = &freeze_escape($inbound);
                   9796:         }
                   9797:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9798:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9799:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9800:                             &escape($title).':'.&escape($code).':'.
                   9801:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9802:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9803:             my @items = split(/&/,$response);
                   9804:             foreach my $item (@items) {
                   9805:                 my ($key,$value) = split('=',$item);
                   9806:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9807:             }
                   9808:         }
                   9809:     }
                   9810:     return \%crsreqresponse;
                   9811: }
                   9812: 
1.1172.2.78  raeburn  9813: sub auto_export_grades {
                   9814:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9815:     my ($homeserver,%exportresponse);
                   9816:     if ($cdom =~ /^$match_domain$/) {
                   9817:         $homeserver = &domain($cdom,'primary');
                   9818:     }
                   9819:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9820:         my $info;
                   9821:         if (ref($inforef) eq 'HASH') {
                   9822:             $info = &freeze_escape($inforef);
                   9823:         }
                   9824:         if (ref($gradesref) eq 'HASH') {
                   9825:             my $grades = &freeze_escape($gradesref);
                   9826:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9827:                                 $info.':'.$grades,$homeserver);
                   9828:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9829:                 my @items = split(/&/,$response);
                   9830:                 foreach my $item (@items) {
                   9831:                     my ($key,$value) = split('=',$item);
                   9832:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9833:                 }
                   9834:             }
                   9835:         }
                   9836:     }
                   9837:     return \%exportresponse;
                   9838: }
                   9839: 
1.1172.2.68  raeburn  9840: sub check_instcode_cloning {
                   9841:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9842:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9843:         return;
                   9844:     }
                   9845:     my $canclone;
                   9846:     if (@{$code_order} > 0) {
                   9847:         my $instcoderegexp ='^';
                   9848:         my @clonecodes = split(/\&/,$cloner);
                   9849:         foreach my $item (@{$code_order}) {
                   9850:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9851:                 foreach my $pair (@clonecodes) {
                   9852:                     my ($key,$val) = split(/\=/,$pair,2);
                   9853:                     $val = &unescape($val);
                   9854:                     if ($key eq $item) {
                   9855:                         $instcoderegexp .= '('.$val.')';
                   9856:                         last;
                   9857:                     }
                   9858:                 }
                   9859:             } else {
                   9860:                 $instcoderegexp .= $codedefaults->{$item};
                   9861:             }
                   9862:         }
                   9863:         $instcoderegexp .= '$';
                   9864:         my (@from,@to);
                   9865:         eval {
                   9866:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9867:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9868:         };
                   9869:         if ((@from > 0) && (@to > 0)) {
                   9870:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9871:             if (!@diffs) {
                   9872:                 $canclone = 1;
                   9873:             }
                   9874:         }
                   9875:     }
                   9876:     return $canclone;
                   9877: }
                   9878: 
                   9879: sub default_instcode_cloning {
                   9880:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9881:     my (%codedefaults,@code_order,$canclone);
                   9882:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9883:         %codedefaults = %{$codedefaultsref};
                   9884:         @code_order = @{$codeorderref};
                   9885:     } elsif ($clonedom) {
                   9886:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9887:     }
                   9888:     if (($domdefclone) && (@code_order)) {
                   9889:         my @clonecodes = split(/\+/,$domdefclone);
                   9890:         my $instcoderegexp ='^';
                   9891:         foreach my $item (@code_order) {
                   9892:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9893:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9894:             } else {
                   9895:                 $instcoderegexp .= $codedefaults{$item};
                   9896:             }
                   9897:         }
                   9898:         $instcoderegexp .= '$';
                   9899:         my (@from,@to);
                   9900:         eval {
                   9901:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9902:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9903:         };
                   9904:         if ((@from > 0) && (@to > 0)) {
                   9905:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9906:             if (!@diffs) {
                   9907:                 $canclone = 1;
                   9908:             }
                   9909:         }
                   9910:     }
                   9911:     return $canclone;
                   9912: }
                   9913: 
1.679     raeburn  9914: # ------------------------------------------------------- Course Group routines
                   9915: 
                   9916: sub get_coursegroups {
1.809     raeburn  9917:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9918:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9919: }
                   9920: 
1.679     raeburn  9921: sub modify_coursegroup {
                   9922:     my ($cdom,$cnum,$groupsettings) = @_;
                   9923:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9924: }
                   9925: 
1.809     raeburn  9926: sub toggle_coursegroup_status {
                   9927:     my ($cdom,$cnum,$group,$action) = @_;
                   9928:     my ($from_namespace,$to_namespace);
                   9929:     if ($action eq 'delete') {
                   9930:         $from_namespace = 'coursegroups';
                   9931:         $to_namespace = 'deleted_groups';
                   9932:     } else {
                   9933:         $from_namespace = 'deleted_groups';
                   9934:         $to_namespace = 'coursegroups';
                   9935:     }
                   9936:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9937:     if (my $tmp = &error(%curr_group)) {
                   9938:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9939:         return ('read error',$tmp);
                   9940:     } else {
                   9941:         my %savedsettings = %curr_group; 
1.809     raeburn  9942:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9943:         my $deloutcome;
                   9944:         if ($result eq 'ok') {
1.809     raeburn  9945:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9946:         } else {
                   9947:             return ('write error',$result);
                   9948:         }
                   9949:         if ($deloutcome eq 'ok') {
                   9950:             return 'ok';
                   9951:         } else {
                   9952:             return ('delete error',$deloutcome);
                   9953:         }
                   9954:     }
                   9955: }
                   9956: 
1.679     raeburn  9957: sub modify_group_roles {
1.957     raeburn  9958:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9959:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9960:     my $role = 'gr/'.&escape($userprivs);
                   9961:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9962:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9963:     if ($result eq 'ok') {
                   9964:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9965:     }
1.679     raeburn  9966:     return $result;
                   9967: }
                   9968: 
                   9969: sub modify_coursegroup_membership {
                   9970:     my ($cdom,$cnum,$membership) = @_;
                   9971:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9972:     return $result;
                   9973: }
                   9974: 
1.682     raeburn  9975: sub get_active_groups {
                   9976:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9977:     my $now = time;
                   9978:     my %groups = ();
                   9979:     foreach my $key (keys(%env)) {
1.811     albertel 9980:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9981:             my ($start,$end) = split(/\./,$env{$key});
                   9982:             if (($end!=0) && ($end<$now)) { next; }
                   9983:             if (($start!=0) && ($start>$now)) { next; }
                   9984:             if ($1 eq $cdom && $2 eq $cnum) {
                   9985:                 $groups{$3} = $env{$key} ;
                   9986:             }
                   9987:         }
                   9988:     }
                   9989:     return %groups;
                   9990: }
                   9991: 
1.683     raeburn  9992: sub get_group_membership {
                   9993:     my ($cdom,$cnum,$group) = @_;
                   9994:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9995: }
                   9996: 
                   9997: sub get_users_groups {
                   9998:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9999:     my @usersgroups;
1.683     raeburn  10000:     my $cachetime=1800;
                   10001: 
                   10002:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10003:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10004:     if (defined($cached)) {
1.734     albertel 10005:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10006:     } else {  
                   10007:         $grouplist = '';
1.816     raeburn  10008:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10009:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10010:         my $access_end = $env{'course.'.$courseid.
                   10011:                               '.default_enrollment_end_date'};
                   10012:         my $now = time;
                   10013:         foreach my $key (keys(%roleshash)) {
                   10014:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10015:                 my $group = $1;
                   10016:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10017:                     my $start = $2;
                   10018:                     my $end = $1;
                   10019:                     if ($start == -1) { next; } # deleted from group
                   10020:                     if (($start!=0) && ($start>$now)) { next; }
                   10021:                     if (($end!=0) && ($end<$now)) {
                   10022:                         if ($access_end && $access_end < $now) {
                   10023:                             if ($access_end - $end < 86400) {
                   10024:                                 push(@usersgroups,$group);
1.733     raeburn  10025:                             }
                   10026:                         }
1.817     raeburn  10027:                         next;
1.733     raeburn  10028:                     }
1.817     raeburn  10029:                     push(@usersgroups,$group);
1.683     raeburn  10030:                 }
                   10031:             }
                   10032:         }
1.817     raeburn  10033:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10034:         $grouplist = join(':',@usersgroups);
                   10035:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10036:     }
1.733     raeburn  10037:     return @usersgroups;
1.683     raeburn  10038: }
                   10039: 
                   10040: sub devalidate_getgroups_cache {
                   10041:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10042:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10043: 
1.683     raeburn  10044:     my $hashid="$udom:$uname:$courseid";
                   10045:     &devalidate_cache_new('getgroups',$hashid);
                   10046: }
                   10047: 
1.12      www      10048: # ------------------------------------------------------------------ Plain Text
                   10049: 
                   10050: sub plaintext {
1.988     raeburn  10051:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10052:     if ($short =~ m{^cr/}) {
1.758     albertel 10053: 	return (split('/',$short))[-1];
                   10054:     }
1.742     raeburn  10055:     if (!defined($cid)) {
                   10056:         $cid = $env{'request.course.id'};
                   10057:     }
                   10058:     my %rolenames = (
1.1008    raeburn  10059:                       Course    => 'std',
                   10060:                       Community => 'alt1',
1.742     raeburn  10061:                     );
1.1037    raeburn  10062:     if ($cid ne '') {
                   10063:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10064:             unless ($forcedefault) {
                   10065:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10066:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10067:                 return &Apache::lonlocal::mt($roletext);
                   10068:             }
                   10069:         }
                   10070:     }
                   10071:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10072:         (defined($rolenames{$type})) && 
                   10073:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10074:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10075:     } elsif ($cid ne '') {
                   10076:         my $crstype = $env{'course.'.$cid.'.type'};
                   10077:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10078:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10079:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10080:         }
1.742     raeburn  10081:     }
1.1037    raeburn  10082:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10083: }
                   10084: 
                   10085: # ----------------------------------------------------------------- Assign Role
                   10086: 
                   10087: sub assignrole {
1.957     raeburn  10088:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10089:         $context)=@_;
1.21      www      10090:     my $mrole;
                   10091:     if ($role =~ /^cr\//) {
1.393     www      10092:         my $cwosec=$url;
1.811     albertel 10093:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10094: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10095:            my $refused = 1;
                   10096:            if ($context eq 'requestcourses') {
                   10097:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10098:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10099:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10100:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10101:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10102:                            if ($crsenv{'internal.courseowner'} eq
                   10103:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10104:                                $refused = '';
                   10105:                            }
                   10106:                        }
                   10107:                    }
                   10108:                }
                   10109:            }
                   10110:            if ($refused) {
                   10111:                &logthis('Refused custom assignrole: '.
                   10112:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10113:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10114:                return 'refused';
                   10115:            }
1.104     www      10116:         }
1.21      www      10117:         $mrole='cr';
1.678     raeburn  10118:     } elsif ($role =~ /^gr\//) {
                   10119:         my $cwogrp=$url;
1.811     albertel 10120:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10121:         unless (&allowed('mdg',$cwogrp)) {
                   10122:             &logthis('Refused group assignrole: '.
                   10123:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10124:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10125:             return 'refused';
                   10126:         }
                   10127:         $mrole='gr';
1.21      www      10128:     } else {
1.82      www      10129:         my $cwosec=$url;
1.811     albertel 10130:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10131:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10132:             my $refused;
                   10133:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10134:                 if (!(&allowed('c'.$role,$url))) {
                   10135:                     $refused = 1;
                   10136:                 }
                   10137:             } else {
                   10138:                 $refused = 1;
                   10139:             }
1.947     raeburn  10140:             if ($refused) {
1.1045    raeburn  10141:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10142:                 if (!$selfenroll && $context eq 'course') {
                   10143:                     my %crsenv;
                   10144:                     if ($role eq 'cc' || $role eq 'co') {
                   10145:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10146:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10147:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10148:                                 if ($crsenv{'internal.courseowner'} eq 
                   10149:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10150:                                     $refused = '';
                   10151:                                 }
                   10152:                             }
                   10153:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10154:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10155:                                 if ($crsenv{'internal.courseowner'} eq 
                   10156:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10157:                                     $refused = '';
                   10158:                                 }
                   10159:                             }
                   10160:                         }
                   10161:                     }
                   10162:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10163:                     $refused = '';
1.1017    raeburn  10164:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10165:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10166:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10167:                         my $wrongcc;
                   10168:                         if ($cnum =~ /^$match_community$/) {
                   10169:                             $wrongcc = 1 if ($role eq 'cc');
                   10170:                         } else {
                   10171:                             $wrongcc = 1 if ($role eq 'co');
                   10172:                         }
                   10173:                         unless ($wrongcc) {
                   10174:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10175:                             if ($crsenv{'internal.courseowner'} eq 
                   10176:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10177:                                 $refused = '';
                   10178:                             }
1.1017    raeburn  10179:                         }
                   10180:                     }
1.1172.2.9  raeburn  10181:                 } elsif ($context eq 'requestauthor') {
                   10182:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10183:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10184:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10185:                             $refused = '';
                   10186:                         } else {
                   10187:                             my %domdefaults = &get_domain_defaults($udom);
                   10188:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10189:                                 my $checkbystatus;
                   10190:                                 if ($env{'user.adv'}) {
                   10191:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10192:                                     if ($disposition eq 'automatic') {
                   10193:                                         $refused = '';
                   10194:                                     } elsif ($disposition eq '') {
                   10195:                                         $checkbystatus = 1;
                   10196:                                     }
                   10197:                                 } else {
                   10198:                                     $checkbystatus = 1;
                   10199:                                 }
                   10200:                                 if ($checkbystatus) {
                   10201:                                     if ($env{'environment.inststatus'}) {
                   10202:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10203:                                         foreach my $type (@inststatuses) {
                   10204:                                             if (($type ne '') &&
                   10205:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10206:                                                 $refused = '';
                   10207:                                             }
                   10208:                                         }
                   10209:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10210:                                         $refused = '';
                   10211:                                     }
                   10212:                                 }
                   10213:                             }
                   10214:                         }
                   10215:                     }
1.1017    raeburn  10216:                 }
                   10217:                 if ($refused) {
1.947     raeburn  10218:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10219:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10220: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10221:                     return 'refused';
                   10222:                 }
1.932     raeburn  10223:             }
1.1131    raeburn  10224:         } elsif ($role eq 'au') {
                   10225:             if ($url ne '/'.$udom.'/') {
                   10226:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10227:                          ' to assign author role for '.$uname.':'.$udom.
                   10228:                          ' in domain: '.$url.' refused (wrong domain).');
                   10229:                 return 'refused';
                   10230:             }
1.104     www      10231:         }
1.21      www      10232:         $mrole=$role;
                   10233:     }
1.620     albertel 10234:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10235:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10236:     if ($end) { $command.='_'.$end; }
1.21      www      10237:     if ($start) {
                   10238: 	if ($end) { 
1.81      www      10239:            $command.='_'.$start; 
1.21      www      10240:         } else {
1.81      www      10241:            $command.='_0_'.$start;
1.21      www      10242:         }
                   10243:     }
1.739     raeburn  10244:     my $origstart = $start;
                   10245:     my $origend = $end;
1.957     raeburn  10246:     my $delflag;
1.357     www      10247: # actually delete
                   10248:     if ($deleteflag) {
1.373     www      10249: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10250: # modify command to delete the role
1.620     albertel 10251:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10252:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10253: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10254: # set start and finish to negative values for userrolelog
                   10255:            $start=-1;
                   10256:            $end=-1;
1.957     raeburn  10257:            $delflag = 1;
1.357     www      10258:         }
                   10259:     }
                   10260: # send command
1.349     www      10261:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10262: # log new user role if status is ok
1.349     www      10263:     if ($answer eq 'ok') {
1.663     raeburn  10264: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10265:         if (($role eq 'cc') || ($role eq 'in') ||
                   10266:             ($role eq 'ep') || ($role eq 'ad') ||
                   10267:             ($role eq 'ta') || ($role eq 'st') ||
                   10268:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10269:             ($role eq 'co')) {
1.1172.2.13  raeburn  10270: # for course roles, perform group memberships changes triggered by role change.
                   10271:             unless ($role =~ /^gr/) {
                   10272:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10273:                                                  $origstart,$selfenroll,$context);
                   10274:             }
1.1172.2.9  raeburn  10275:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10276:                            $selfenroll,$context);
                   10277:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10278:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10279:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10280:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10281:                            $context);
                   10282:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10283:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10284:                              $context);
                   10285:         }
1.1053    raeburn  10286:         if ($role eq 'cc') {
                   10287:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10288:         }
1.349     www      10289:     }
                   10290:     return $answer;
1.169     harris41 10291: }
                   10292: 
1.1053    raeburn  10293: sub autoupdate_coowners {
                   10294:     my ($url,$end,$start,$uname,$udom) = @_;
                   10295:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10296:     if (($cdom ne '') && ($cnum ne '')) {
                   10297:         my $now = time;
                   10298:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10299:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10300:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10301:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10302:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10303:             if ($instcode ne '') {
1.1056    raeburn  10304:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10305:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10306:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10307:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10308:                         unless ($result eq 'valid') {
                   10309:                             if ($xlists ne '') {
                   10310:                                 foreach my $xlist (split(',',$xlists)) {
                   10311:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10312:                                     $result =
                   10313:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10314:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10315:                                     last if ($result eq 'valid');
                   10316:                                 }
                   10317:                             }
                   10318:                         }
1.1056    raeburn  10319:                         if ($result eq 'valid') {
                   10320:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10321:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10322:                                     push(@newcoowners,$coowner);
                   10323:                                 }
                   10324:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10325:                                     push(@newcoowners,$uname.':'.$udom);
                   10326:                                 }
                   10327:                                 @newcoowners = sort(@newcoowners);
                   10328:                             } else {
                   10329:                                 push(@newcoowners,$uname.':'.$udom);
                   10330:                             }
1.1172.2.141  raeburn  10331:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10332:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10333:                                 unless ($coowner eq $uname.':'.$udom) {
                   10334:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10335:                                 }
                   10336:                             }
1.1172.2.141  raeburn  10337:                             unless (@newcoowners > 0) {
                   10338:                                 $delcoowners = 1;
                   10339:                                 $coowners = '';
                   10340:                             }
1.1053    raeburn  10341:                         }
                   10342:                         if (@newcoowners || $delcoowners) {
                   10343:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10344:                                             $delcoowners,@newcoowners);
                   10345:                         }
                   10346:                     }
                   10347:                 }
                   10348:             }
                   10349:         }
                   10350:     }
                   10351: }
                   10352: 
                   10353: sub store_coowners {
                   10354:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10355:     my $cid = $cdom.'_'.$cnum;
                   10356:     my ($coowners,$delresult,$putresult);
                   10357:     if (@newcoowners) {
                   10358:         $coowners = join(',',@newcoowners);
                   10359:         my %coownershash = (
                   10360:                             'internal.co-owners' => $coowners,
                   10361:                            );
                   10362:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10363:         if ($putresult eq 'ok') {
                   10364:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10365:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10366:             }
                   10367:         }
                   10368:     }
                   10369:     if ($delcoowners) {
                   10370:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10371:         if ($delresult eq 'ok') {
                   10372:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10373:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10374:             }
                   10375:         }
                   10376:     }
                   10377:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10378:         my %crsinfo =
                   10379:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10380:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10381:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10382:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10383:         }
                   10384:     }
                   10385: }
                   10386: 
1.169     harris41 10387: # -------------------------------------------------- Modify user authentication
1.197     www      10388: # Overrides without validation
                   10389: 
1.169     harris41 10390: sub modifyuserauth {
                   10391:     my ($udom,$uname,$umode,$upass)=@_;
                   10392:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10393:     my $allowed;
                   10394:     if (&allowed('mau',$udom)) {
                   10395:         $allowed = 1;
                   10396:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10397:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10398:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10399:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10400:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10401:         if (($cdom ne '') && ($cnum ne '')) {
                   10402:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10403:             if ($is_owner) {
                   10404:                 $allowed = 1;
                   10405:             }
                   10406:         }
                   10407:     }
                   10408:     unless ($allowed) { return 'refused'; }
1.197     www      10409:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10410:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10411:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10412:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10413: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10414:     my $ip = &get_requestor_ip();
1.620     albertel 10415:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10416:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10417:          '(Remote '.$ip.'): '.$reply);
1.197     www      10418:     &log($udom,,$uname,$uhome,
1.620     albertel 10419:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10420:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10421:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10422:     unless ($reply eq 'ok') {
1.197     www      10423:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10424: 	return 'error: '.$reply;
                   10425:     }   
1.170     harris41 10426:     return 'ok';
1.80      www      10427: }
                   10428: 
1.81      www      10429: # --------------------------------------------------------------- Modify a user
1.80      www      10430: 
1.81      www      10431: sub modifyuser {
1.206     matthew  10432:     my ($udom,    $uname, $uid,
                   10433:         $umode,   $upass, $first,
                   10434:         $middle,  $last,  $gene,
1.1058    raeburn  10435:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10436:     $udom= &LONCAPA::clean_domain($udom);
                   10437:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10438:     my $showcandelete = 'none';
                   10439:     if (ref($candelete) eq 'ARRAY') {
                   10440:         if (@{$candelete} > 0) {
                   10441:             $showcandelete = join(', ',@{$candelete});
                   10442:         }
                   10443:     }
1.81      www      10444:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10445:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10446: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10447:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10448:                                      ' desiredhome not specified'). 
1.620     albertel 10449:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10450:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10451:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10452:     my $newuser;
                   10453:     if ($uhome eq 'no_host') {
                   10454:         $newuser = 1;
                   10455:     }
1.80      www      10456: # ----------------------------------------------------------------- Create User
1.406     albertel 10457:     if (($uhome eq 'no_host') && 
                   10458: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10459:         my $unhome='';
1.844     albertel 10460:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10461:             $unhome = $desiredhome;
1.620     albertel 10462: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10463: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10464:         } else { # load balancing routine for determining $unhome
1.81      www      10465:             my $loadm=10000000;
1.841     albertel 10466: 	    my %servers = &get_servers($udom,'library');
                   10467: 	    foreach my $tryserver (keys(%servers)) {
                   10468: 		my $answer=reply('load',$tryserver);
                   10469: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10470: 		    $loadm=$answer;
                   10471: 		    $unhome=$tryserver;
                   10472: 		}
1.80      www      10473: 	    }
                   10474:         }
                   10475:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10476: 	    return 'error: unable to find a home server for '.$uname.
                   10477:                    ' in domain '.$udom;
1.80      www      10478:         }
                   10479:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10480:                          &escape($upass),$unhome);
                   10481: 	unless ($reply eq 'ok') {
                   10482:             return 'error: '.$reply;
                   10483:         }   
1.230     stredwic 10484:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10485:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10486: 	    return 'error: unable verify users home machine.';
1.80      www      10487:         }
1.209     matthew  10488:     }   # End of creation of new user
1.80      www      10489: # ---------------------------------------------------------------------- Add ID
                   10490:     if ($uid) {
                   10491:        $uid=~tr/A-Z/a-z/;
                   10492:        my %uidhash=&idrget($udom,$uname);
1.196     www      10493:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10494:          && (!$forceid)) {
1.80      www      10495: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10496: 	      return 'error: user id "'.$uid.'" does not match '.
                   10497:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10498:           }
                   10499:        } else {
                   10500: 	  &idput($udom,($uname => $uid));
                   10501:        }
                   10502:     }
                   10503: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10504:     my @tmp=&get('environment',
1.899     raeburn  10505: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10506:                     'permanentemail','inststatus'],
1.134     albertel 10507: 		   $udom,$uname);
1.1075    raeburn  10508:     my (%names,%oldnames);
1.313     matthew  10509:     if ($tmp[0] =~ m/^error:.*/) { 
                   10510:         %names=(); 
                   10511:     } else {
                   10512:         %names = @tmp;
1.1075    raeburn  10513:         %oldnames = %names;
1.313     matthew  10514:     }
1.388     www      10515: #
1.1058    raeburn  10516: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10517: # of users did not contain them), do not overwrite existing values
                   10518: # unless field is in $candelete array ref.  
                   10519: #
                   10520: 
                   10521:     my @fields = ('firstname','middlename','lastname','generation',
                   10522:                   'permanentemail','id');
                   10523:     my %newvalues;
                   10524:     if (ref($candelete) eq 'ARRAY') {
                   10525:         foreach my $field (@fields) {
                   10526:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10527:                 if ($field eq 'firstname') {
                   10528:                     $names{$field} = $first;
                   10529:                 } elsif ($field eq 'middlename') {
                   10530:                     $names{$field} = $middle;
                   10531:                 } elsif ($field eq 'lastname') {
                   10532:                     $names{$field} = $last;
                   10533:                 } elsif ($field eq 'generation') { 
                   10534:                     $names{$field} = $gene;
                   10535:                 } elsif ($field eq 'permanentemail') {
                   10536:                     $names{$field} = $email;
                   10537:                 } elsif ($field eq 'id') {
                   10538:                     $names{$field}  = $uid;
                   10539:                 }
                   10540:             }
                   10541:         }
                   10542:     }
1.388     www      10543:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10544:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10545:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10546:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10547:     if ($email) {
                   10548:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10549:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10550:     }
1.899     raeburn  10551:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10552:     if (defined($inststatus)) {
                   10553:         $names{'inststatus'} = '';
                   10554:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10555:         if (ref($usertypes) eq 'HASH') {
                   10556:             my @okstatuses; 
                   10557:             foreach my $item (split(/:/,$inststatus)) {
                   10558:                 if (defined($usertypes->{$item})) {
                   10559:                     push(@okstatuses,$item);  
                   10560:                 }
                   10561:             }
                   10562:             if (@okstatuses) {
                   10563:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10564:             }
                   10565:         }
                   10566:     }
1.1075    raeburn  10567:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10568:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10569:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10570:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10571:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10572:     } else {
                   10573:         $logmsg .= ' during self creation';
                   10574:     }
1.1075    raeburn  10575:     my $changed;
                   10576:     if ($newuser) {
                   10577:         $changed = 1;
                   10578:     } else {
                   10579:         foreach my $field (@fields) {
                   10580:             if ($names{$field} ne $oldnames{$field}) {
                   10581:                 $changed = 1;
                   10582:                 last;
                   10583:             }
                   10584:         }
                   10585:     }
                   10586:     unless ($changed) {
                   10587:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10588:         &logthis($logmsg);
                   10589:         return 'ok';
                   10590:     }
                   10591:     my $reply = &put('environment', \%names, $udom,$uname);
                   10592:     if ($reply ne 'ok') { 
                   10593:         return 'error: '.$reply;
                   10594:     }
1.1087    raeburn  10595:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10596:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10597:     }
1.1075    raeburn  10598:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10599:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10600:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10601:     &logthis($logmsg);
1.134     albertel 10602:     return 'ok';
1.80      www      10603: }
                   10604: 
1.81      www      10605: # -------------------------------------------------------------- Modify student
1.80      www      10606: 
1.81      www      10607: sub modifystudent {
                   10608:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10609:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10610:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10611:     if (!$cid) {
1.620     albertel 10612: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10613: 	    return 'not_in_class';
                   10614: 	}
1.80      www      10615:     }
                   10616: # --------------------------------------------------------------- Make the user
1.81      www      10617:     my $reply=&modifyuser
1.209     matthew  10618: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10619:          $desiredhome,$email,$inststatus);
1.80      www      10620:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10621:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10622:     # student's environment
1.297     matthew  10623:     $uid = undef if (!$forceid);
1.455     albertel 10624:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10625: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10626:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10627:     return $reply;
                   10628: }
                   10629: 
                   10630: sub modify_student_enrollment {
1.1172.2.23  raeburn  10631:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10632:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10633:     my ($cdom,$cnum,$chome);
                   10634:     if (!$cid) {
1.620     albertel 10635: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10636: 	    return 'not_in_class';
                   10637: 	}
1.620     albertel 10638: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10639: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10640:     } else {
                   10641: 	($cdom,$cnum)=split(/_/,$cid);
                   10642:     }
1.620     albertel 10643:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10644:     if (!$chome) {
1.457     raeburn  10645: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10646:     }
1.455     albertel 10647:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10648:     # Make sure the user exists
1.81      www      10649:     my $uhome=&homeserver($uname,$udom);
                   10650:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10651: 	return 'error: no such user';
                   10652:     }
1.297     matthew  10653:     # Get student data if we were not given enough information
                   10654:     if (!defined($first)  || $first  eq '' || 
                   10655:         !defined($last)   || $last   eq '' || 
                   10656:         !defined($uid)    || $uid    eq '' || 
                   10657:         !defined($middle) || $middle eq '' || 
                   10658:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10659:         # They did not supply us with enough data to enroll the student, so
                   10660:         # we need to pick up more information.
1.297     matthew  10661:         my %tmp = &get('environment',
1.294     matthew  10662:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10663:                        ,$udom,$uname);
                   10664: 
1.800     albertel 10665:         #foreach my $key (keys(%tmp)) {
                   10666:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10667:         #}
1.294     matthew  10668:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10669:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10670:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10671:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10672:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10673:     }
1.556     albertel 10674:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10675:     my $user = "$uname:$udom";
                   10676:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10677:     my $reply=cput('classlist',
1.1148    raeburn  10678: 		   {$user => 
1.1172.2.76  raeburn  10679: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10680: 		   $cdom,$cnum);
1.1148    raeburn  10681:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10682:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10683:     } else { 
1.81      www      10684: 	return 'error: '.$reply;
                   10685:     }
1.297     matthew  10686:     # Add student role to user
1.83      www      10687:     my $uurl='/'.$cid;
1.81      www      10688:     $uurl=~s/\_/\//g;
                   10689:     if ($usec) {
                   10690: 	$uurl.='/'.$usec;
                   10691:     }
1.1148    raeburn  10692:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10693:                              $selfenroll,$context);
                   10694:     if ($result ne 'ok') {
                   10695:         if ($old_entry{$user} ne '') {
                   10696:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10697:         } else {
                   10698:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10699:         }
                   10700:     }
                   10701:     return $result; 
1.21      www      10702: }
                   10703: 
1.556     albertel 10704: sub format_name {
                   10705:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10706:     my $name;
                   10707:     if ($first ne 'lastname') {
                   10708: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10709:     } else {
                   10710: 	if ($lastname=~/\S/) {
                   10711: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10712: 	    $name=~s/\s+,/,/;
                   10713: 	} else {
                   10714: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10715: 	}
                   10716:     }
                   10717:     $name=~s/^\s+//;
                   10718:     $name=~s/\s+$//;
                   10719:     $name=~s/\s+/ /g;
                   10720:     return $name;
                   10721: }
                   10722: 
1.84      www      10723: # ------------------------------------------------- Write to course preferences
                   10724: 
                   10725: sub writecoursepref {
                   10726:     my ($courseid,%prefs)=@_;
                   10727:     $courseid=~s/^\///;
                   10728:     $courseid=~s/\_/\//g;
                   10729:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10730:     my $chome=homeserver($cnum,$cdomain);
                   10731:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10732: 	return 'error: no such course';
                   10733:     }
                   10734:     my $cstring='';
1.800     albertel 10735:     foreach my $pref (keys(%prefs)) {
                   10736: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10737:     }
1.84      www      10738:     $cstring=~s/\&$//;
                   10739:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10740: }
                   10741: 
                   10742: # ---------------------------------------------------------- Make/modify course
                   10743: 
                   10744: sub createcourse {
1.741     raeburn  10745:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10746:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10747:     $url=&declutter($url);
                   10748:     my $cid='';
1.1028    raeburn  10749:     if ($context eq 'requestcourses') {
                   10750:         my $can_create = 0;
                   10751:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10752:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10753:22):             my $reload;
                   10754:22):             if (($callercontext eq 'auto') &&
                   10755:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10756:22):                 $reload = 'reload';
                   10757:22):             }
                   10758:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10759:                                   $context)) {
                   10760:                 $can_create = 1;
                   10761:             }
                   10762:         } else {
                   10763:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10764:                                            $category);
                   10765:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10766:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10767:                 if (@curr > 0) {
                   10768:                     my @options = qw(approval validate autolimit);
                   10769:                     my $optregex = join('|',@options);
                   10770:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10771:                         $can_create = 1;
                   10772:                     }
                   10773:                 }
                   10774:             }
                   10775:         }
                   10776:         if ($can_create) {
                   10777:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10778:                 unless (&allowed('ccc',$udom)) {
                   10779:                     return 'refused'; 
                   10780:                 }
1.1017    raeburn  10781:             }
                   10782:         } else {
                   10783:             return 'refused';
                   10784:         }
1.1028    raeburn  10785:     } elsif (!&allowed('ccc',$udom)) {
                   10786:         return 'refused';
1.84      www      10787:     }
1.1011    raeburn  10788: # --------------------------------------------------------------- Get Unique ID
                   10789:     my $uname;
                   10790:     if ($cnum =~ /^$match_courseid$/) {
                   10791:         my $chome=&homeserver($cnum,$udom,'true');
                   10792:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10793:             $uname = $cnum;
                   10794:         } else {
1.1038    raeburn  10795:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10796:         }
                   10797:     } else {
1.1038    raeburn  10798:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10799:     }
                   10800:     return $uname if ($uname =~ /^error/);
                   10801: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10802:     if (!defined($course_server)) {
                   10803:         if (defined(&domain($udom,'primary'))) {
                   10804:             $course_server = &domain($udom,'primary');
                   10805:         } else {
                   10806:             $course_server = $env{'user.home'}; 
                   10807:         }
                   10808:     }
                   10809:     my %host_servers =
                   10810:         &Apache::lonnet::get_servers($udom,'library');
                   10811:     unless ($host_servers{$course_server}) {
                   10812:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10813:     }
1.84      www      10814: # ------------------------------------------------------------- Make the course
                   10815:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10816:                       $course_server);
1.84      www      10817:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10818:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10819:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10820: 	return 'error: no such course';
                   10821:     }
1.271     www      10822: # ----------------------------------------------------------------- Course made
1.516     raeburn  10823: # log existence
1.1029    raeburn  10824:     my $now = time;
1.918     raeburn  10825:     my $newcourse = {
                   10826:                     $udom.'_'.$uname => {
1.921     raeburn  10827:                                      description => $description,
                   10828:                                      inst_code   => $inst_code,
                   10829:                                      owner       => $course_owner,
                   10830:                                      type        => $crstype,
1.1029    raeburn  10831:                                      creator     => $env{'user.name'}.':'.
                   10832:                                                     $env{'user.domain'},
                   10833:                                      created     => $now,
                   10834:                                      context     => $context,
1.918     raeburn  10835:                                                 },
                   10836:                     };
1.921     raeburn  10837:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10838: # set toplevel url
1.271     www      10839:     my $topurl=$url;
                   10840:     unless ($nonstandard) {
                   10841: # ------------------------------------------ For standard courses, make top url
                   10842:         my $mapurl=&clutter($url);
1.278     www      10843:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10844:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10845: <map>
                   10846: <resource id="1" type="start"></resource>
                   10847: <resource id="2" src="$mapurl"></resource>
                   10848: <resource id="3" type="finish"></resource>
                   10849: <link index="1" from="1" to="2"></link>
                   10850: <link index="2" from="2" to="3"></link>
                   10851: </map>
                   10852: ENDINITMAP
                   10853:         $topurl=&declutter(
1.638     albertel 10854:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10855:                           );
                   10856:     }
                   10857: # ----------------------------------------------------------- Write preferences
1.84      www      10858:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10859:                      ('description'              => $description,
                   10860:                       'url'                      => $topurl,
                   10861:                       'internal.creator'         => $env{'user.name'}.':'.
                   10862:                                                     $env{'user.domain'},
                   10863:                       'internal.created'         => $now,
                   10864:                       'internal.creationcontext' => $context)
                   10865:                     );
1.84      www      10866:     return '/'.$udom.'/'.$uname;
                   10867: }
                   10868: 
1.1011    raeburn  10869: # ------------------------------------------------------------------- Create ID
                   10870: sub generate_coursenum {
1.1038    raeburn  10871:     my ($udom,$crstype) = @_;
1.1011    raeburn  10872:     my $domdesc = &domain($udom);
                   10873:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10874:     my $first;
                   10875:     if ($crstype eq 'Community') {
                   10876:         $first = '0';
                   10877:     } else {
                   10878:         $first = int(1+rand(9)); 
                   10879:     } 
                   10880:     my $uname=$first.
1.1011    raeburn  10881:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10882:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10883:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10884: # ----------------------------------------------- Make sure that does not exist
                   10885:     my $uhome=&homeserver($uname,$udom,'true');
                   10886:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10887:         if ($crstype eq 'Community') {
                   10888:             $first = '0';
                   10889:         } else {
                   10890:             $first = int(1+rand(9));
                   10891:         }
                   10892:         $uname=$first.
1.1011    raeburn  10893:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10894:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10895:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10896:         $uhome=&homeserver($uname,$udom,'true');
                   10897:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10898:             return 'error: unable to generate unique course-ID';
                   10899:         }
                   10900:     }
                   10901:     return $uname;
                   10902: }
                   10903: 
1.813     albertel 10904: sub is_course {
1.1167    droeschl 10905:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10906:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10907:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10908:     my $uhome=&homeserver($cnum,$cdom);
                   10909:     my $iscourse;
                   10910:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10911:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10912:     } else {
                   10913:         my $hashid = $cdom.':'.$cnum;
                   10914:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10915:         unless (defined($cached)) {
                   10916:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10917:                                         $cnum,undef,undef,'.');
                   10918:             $iscourse = 0;
                   10919:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10920:                 $iscourse = 1;
                   10921:             }
                   10922:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10923:         }
                   10924:     }
                   10925:     return unless($iscourse);
1.1167    droeschl 10926:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10927: }
                   10928: 
1.1015    raeburn  10929: sub store_userdata {
                   10930:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10931:     my $result;
1.1016    raeburn  10932:     if ($datakey ne '') {
1.1013    raeburn  10933:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10934:             if ($udom eq '' || $uname eq '') {
                   10935:                 $udom = $env{'user.domain'};
                   10936:                 $uname = $env{'user.name'};
                   10937:             }
                   10938:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10939:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10940:                 $result = 'error: no_host';
                   10941:             } else {
1.1172.2.138  raeburn  10942:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10943:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10944: 
                   10945:                 my $namevalue='';
                   10946:                 foreach my $key (keys(%{$storehash})) {
                   10947:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10948:                 }
                   10949:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10950:                 unless ($namespace eq 'courserequests') {
                   10951:                     $datakey = &escape($datakey);
                   10952:                 }
1.1105    raeburn  10953:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10954:                                   $namevalue,$uhome);
1.1013    raeburn  10955:             }
                   10956:         } else {
                   10957:             $result = 'error: data to store was not a hash reference'; 
                   10958:         }
                   10959:     } else {
                   10960:         $result= 'error: invalid requestkey'; 
                   10961:     }
                   10962:     return $result;
                   10963: }
                   10964: 
1.21      www      10965: # ---------------------------------------------------------- Assign Custom Role
                   10966: 
                   10967: sub assigncustomrole {
1.957     raeburn  10968:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10969:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10970:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10971: }
                   10972: 
                   10973: # ----------------------------------------------------------------- Revoke Role
                   10974: 
                   10975: sub revokerole {
1.957     raeburn  10976:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10977:     my $now=time;
1.965     raeburn  10978:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10979: }
                   10980: 
                   10981: # ---------------------------------------------------------- Revoke Custom Role
                   10982: 
                   10983: sub revokecustomrole {
1.957     raeburn  10984:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10985:     my $now=time;
1.357     www      10986:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10987:            $deleteflag,$selfenroll,$context);
1.17      www      10988: }
                   10989: 
1.533     banghart 10990: # ------------------------------------------------------------ Disk usage
1.535     albertel 10991: sub diskusage {
1.955     raeburn  10992:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10993:     $directorypath =~ s/\/$//;
                   10994:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10995:                        .&escape($getpropath).':'.&escape($uname).':'
                   10996:                        .&escape($udom),homeserver($uname,$udom));
                   10997:     if ($listing eq 'unknown_cmd') {
                   10998:         if ($getpropath) {
                   10999:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11000:         }
                   11001:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11002:     }
1.514     albertel 11003:     return $listing;
1.512     banghart 11004: }
                   11005: 
1.566     banghart 11006: sub is_locked {
1.1096    raeburn  11007:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11008:     my @check;
                   11009:     my $is_locked;
1.1093    raeburn  11010:     push (@check,$file_name);
1.613     albertel 11011:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11012: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11013:     my ($tmp)=keys(%locked);
                   11014:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11015:     
1.566     banghart 11016:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11017:         $is_locked = 'false';
                   11018:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11019:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11020:                $is_locked = 'true';
1.1096    raeburn  11021:                if (ref($which) eq 'ARRAY') {
                   11022:                    push(@{$which},$entry);
                   11023:                } else {
                   11024:                    last;
                   11025:                }
1.745     raeburn  11026:            }
                   11027:        }
1.566     banghart 11028:     } else {
                   11029:         $is_locked = 'false';
                   11030:     }
1.1093    raeburn  11031:     return $is_locked;
1.566     banghart 11032: }
                   11033: 
1.759     albertel 11034: sub declutter_portfile {
                   11035:     my ($file) = @_;
1.833     albertel 11036:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11037:     return $file;
                   11038: }
                   11039: 
1.559     banghart 11040: # ------------------------------------------------------------- Mark as Read Only
                   11041: 
                   11042: sub mark_as_readonly {
                   11043:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11044:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11045:     my ($tmp)=keys(%current_permissions);
                   11046:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11047:     foreach my $file (@{$files}) {
1.759     albertel 11048: 	$file = &declutter_portfile($file);
1.561     banghart 11049:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11050:     }
1.613     albertel 11051:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11052:     return;
                   11053: }
                   11054: 
1.572     banghart 11055: # ------------------------------------------------------------Save Selected Files
                   11056: 
                   11057: sub save_selected_files {
                   11058:     my ($user, $path, @files) = @_;
                   11059:     my $filename = $user."savedfiles";
1.573     banghart 11060:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11061:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11062:     foreach my $file (@files) {
1.620     albertel 11063:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11064:     }
                   11065:     foreach my $file (@other_files) {
1.574     banghart 11066:         print (OUT $file."\n");
1.572     banghart 11067:     }
1.574     banghart 11068:     close (OUT);
1.572     banghart 11069:     return 'ok';
                   11070: }
                   11071: 
1.574     banghart 11072: sub clear_selected_files {
                   11073:     my ($user) = @_;
                   11074:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11075:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11076:     print (OUT undef);
                   11077:     close (OUT);
                   11078:     return ("ok");    
                   11079: }
                   11080: 
1.572     banghart 11081: sub files_in_path {
                   11082:     my ($user, $path) = @_;
                   11083:     my $filename = $user."savedfiles";
                   11084:     my %return_files;
1.1172.2.96  raeburn  11085:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11086:     while (my $line_in = <IN>) {
1.574     banghart 11087:         chomp ($line_in);
                   11088:         my @paths_and_file = split (m!/!, $line_in);
                   11089:         my $file_part = pop (@paths_and_file);
                   11090:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11091:         $path_part.='/';
                   11092:         my $path_and_file = $path_part.$file_part;
                   11093:         if ($path_part eq $path) {
                   11094:             $return_files{$file_part}= 'selected';
                   11095:         }
                   11096:     }
1.574     banghart 11097:     close (IN);
                   11098:     return (\%return_files);
1.572     banghart 11099: }
                   11100: 
                   11101: # called in portfolio select mode, to show files selected NOT in current directory
                   11102: sub files_not_in_path {
                   11103:     my ($user, $path) = @_;
                   11104:     my $filename = $user."savedfiles";
                   11105:     my @return_files;
                   11106:     my $path_part;
1.1172.2.96  raeburn  11107:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11108:     while (my $line = <IN>) {
1.572     banghart 11109:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11110:         my @paths_and_file = split(m|/|, $line);
                   11111:         my $file_part = pop(@paths_and_file);
                   11112:         chomp($file_part);
                   11113:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11114:         $path_part .= '/';
                   11115:         my $path_and_file = $path_part.$file_part;
                   11116:         if ($path_part ne $path) {
1.800     albertel 11117:             push(@return_files, ($path_and_file));
1.572     banghart 11118:         }
                   11119:     }
1.800     albertel 11120:     close(OUT);
1.574     banghart 11121:     return (@return_files);
1.572     banghart 11122: }
                   11123: 
1.745     raeburn  11124: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11125: 
1.745     raeburn  11126: sub get_portfile_permissions {
                   11127:     my ($domain,$user) = @_;
1.613     albertel 11128:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11129:     my ($tmp)=keys(%current_permissions);
                   11130:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11131:     return \%current_permissions;
                   11132: }
                   11133: 
                   11134: #---------------------------------------------Get portfolio file access controls
                   11135: 
1.749     raeburn  11136: sub get_access_controls {
1.745     raeburn  11137:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11138:     my %access;
                   11139:     my $real_file = $file;
                   11140:     $file =~ s/\.meta$//;
1.745     raeburn  11141:     if (defined($file)) {
1.749     raeburn  11142:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11143:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11144:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11145:             }
                   11146:         }
1.745     raeburn  11147:     } else {
1.749     raeburn  11148:         foreach my $key (keys(%{$current_permissions})) {
                   11149:             if ($key =~ /\0accesscontrol$/) {
                   11150:                 if (defined($group)) {
                   11151:                     if ($key !~ m-^\Q$group\E/-) {
                   11152:                         next;
                   11153:                     }
                   11154:                 }
                   11155:                 my ($fullpath) = split(/\0/,$key);
                   11156:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11157:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11158:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11159:                     }
                   11160:                 }
                   11161:             }
                   11162:         }
                   11163:     }
                   11164:     return %access;
                   11165: }
                   11166: 
                   11167: sub modify_access_controls {
                   11168:     my ($file_name,$changes,$domain,$user)=@_;
                   11169:     my ($outcome,$deloutcome);
                   11170:     my %store_permissions;
                   11171:     my %new_values;
                   11172:     my %new_control;
                   11173:     my %translation;
                   11174:     my @deletions = ();
                   11175:     my $now = time;
                   11176:     if (exists($$changes{'activate'})) {
                   11177:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11178:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11179:             my $numnew = scalar(@newitems);
                   11180:             for (my $i=0; $i<$numnew; $i++) {
                   11181:                 my $newkey = $newitems[$i];
                   11182:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11183:                 if ($newkey =~ /^\d+:/) { 
                   11184:                     $newkey =~ s/^(\d+)/$newid/;
                   11185:                     $translation{$1} = $newid;
                   11186:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11187:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11188:                     $translation{$1} = $newid;
                   11189:                 }
1.749     raeburn  11190:                 $new_values{$file_name."\0".$newkey} = 
                   11191:                                           $$changes{'activate'}{$newitems[$i]};
                   11192:                 $new_control{$newkey} = $now;
                   11193:             }
                   11194:         }
                   11195:     }
                   11196:     my %todelete;
                   11197:     my %changed_items;
                   11198:     foreach my $action ('delete','update') {
                   11199:         if (exists($$changes{$action})) {
                   11200:             if (ref($$changes{$action}) eq 'HASH') {
                   11201:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11202:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11203:                     if ($action eq 'delete') { 
                   11204:                         $todelete{$itemnum} = 1;
                   11205:                     } else {
                   11206:                         $changed_items{$itemnum} = $key;
                   11207:                     }
                   11208:                 }
1.745     raeburn  11209:             }
                   11210:         }
1.749     raeburn  11211:     }
                   11212:     # get lock on access controls for file.
                   11213:     my $lockhash = {
                   11214:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11215:                                                        ':'.$env{'user.domain'},
                   11216:                    }; 
                   11217:     my $tries = 0;
                   11218:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11219:    
1.1172.2.79  raeburn  11220:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11221:         $tries ++;
1.1172.2.79  raeburn  11222:         sleep(0.1);
1.749     raeburn  11223:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11224:     }
                   11225:     if ($gotlock eq 'ok') {
                   11226:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11227:         my ($tmp)=keys(%curr_permissions);
                   11228:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11229:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11230:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11231:             if (ref($curr_controls) eq 'HASH') {
                   11232:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11233:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11234:                     if (defined($todelete{$itemnum})) {
                   11235:                         push(@deletions,$file_name."\0".$control_item);
                   11236:                     } else {
                   11237:                         if (defined($changed_items{$itemnum})) {
                   11238:                             $new_control{$changed_items{$itemnum}} = $now;
                   11239:                             push(@deletions,$file_name."\0".$control_item);
                   11240:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11241:                         } else {
                   11242:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11243:                         }
                   11244:                     }
1.745     raeburn  11245:                 }
                   11246:             }
                   11247:         }
1.970     raeburn  11248:         my ($group);
                   11249:         if (&is_course($domain,$user)) {
                   11250:             ($group,my $file) = split(/\//,$file_name,2);
                   11251:         }
1.749     raeburn  11252:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11253:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11254:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11255:         #  remove lock
                   11256:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11257:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11258:         my $sqlresult =
1.970     raeburn  11259:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11260:                                     $group);
1.749     raeburn  11261:     } else {
                   11262:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11263:     }
1.749     raeburn  11264:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11265: }
                   11266: 
1.827     raeburn  11267: sub make_public_indefinitely {
                   11268:     my ($requrl) = @_;
                   11269:     my $now = time;
                   11270:     my $action = 'activate';
                   11271:     my $aclnum = 0;
                   11272:     if (&is_portfolio_url($requrl)) {
                   11273:         my (undef,$udom,$unum,$file_name,$group) =
                   11274:             &parse_portfolio_url($requrl);
                   11275:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11276:         my %access_controls = &get_access_controls($current_perms,
                   11277:                                                    $group,$file_name);
                   11278:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11279:             my ($num,$scope,$end,$start) = 
                   11280:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11281:             if ($scope eq 'public') {
                   11282:                 if ($start <= $now && $end == 0) {
                   11283:                     $action = 'none';
                   11284:                 } else {
                   11285:                     $action = 'update';
                   11286:                     $aclnum = $num;
                   11287:                 }
                   11288:                 last;
                   11289:             }
                   11290:         }
                   11291:         if ($action eq 'none') {
                   11292:              return 'ok';
                   11293:         } else {
                   11294:             my %changes;
                   11295:             my $newend = 0;
                   11296:             my $newstart = $now;
                   11297:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11298:             $changes{$action}{$newkey} = {
                   11299:                 type => 'public',
                   11300:                 time => {
                   11301:                     start => $newstart,
                   11302:                     end   => $newend,
                   11303:                 },
                   11304:             };
                   11305:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11306:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11307:             return $outcome;
                   11308:         }
                   11309:     } else {
                   11310:         return 'invalid';
                   11311:     }
                   11312: }
                   11313: 
1.745     raeburn  11314: #------------------------------------------------------Get Marked as Read Only
                   11315: 
                   11316: sub get_marked_as_readonly {
                   11317:     my ($domain,$user,$what,$group) = @_;
                   11318:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11319:     my @readonly_files;
1.629     banghart 11320:     my $cmp1=$what;
                   11321:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11322:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11323:         if (defined($group)) {
                   11324:             if ($file_name !~ m-^\Q$group\E/-) {
                   11325:                 next;
                   11326:             }
                   11327:         }
1.561     banghart 11328:         if (ref($value) eq "ARRAY"){
                   11329:             foreach my $stored_what (@{$value}) {
1.629     banghart 11330:                 my $cmp2=$stored_what;
1.759     albertel 11331:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11332:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11333:                 }
1.629     banghart 11334:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11335:                     push(@readonly_files, $file_name);
1.745     raeburn  11336:                     last;
1.563     banghart 11337:                 } elsif (!defined($what)) {
                   11338:                     push(@readonly_files, $file_name);
1.745     raeburn  11339:                     last;
1.561     banghart 11340:                 }
                   11341:             }
1.745     raeburn  11342:         }
1.561     banghart 11343:     }
                   11344:     return @readonly_files;
                   11345: }
1.577     banghart 11346: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11347: 
1.577     banghart 11348: sub get_marked_as_readonly_hash {
1.745     raeburn  11349:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11350:     my %readonly_files;
1.745     raeburn  11351:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11352:         if (defined($group)) {
                   11353:             if ($file_name !~ m-^\Q$group\E/-) {
                   11354:                 next;
                   11355:             }
                   11356:         }
1.577     banghart 11357:         if (ref($value) eq "ARRAY"){
                   11358:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11359:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11360:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11361:                         if ($lock_descriptor eq 'graded') {
                   11362:                             $readonly_files{$file_name} = 'graded';
                   11363:                         } elsif ($lock_descriptor eq 'handback') {
                   11364:                             $readonly_files{$file_name} = 'handback';
                   11365:                         } else {
                   11366:                             if (!exists($readonly_files{$file_name})) {
                   11367:                                 $readonly_files{$file_name} = 'locked';
                   11368:                             }
                   11369:                         }
1.745     raeburn  11370:                     }
1.750     banghart 11371:                 } 
1.577     banghart 11372:             }
                   11373:         } 
                   11374:     }
                   11375:     return %readonly_files;
                   11376: }
1.559     banghart 11377: # ------------------------------------------------------------ Unmark as Read Only
                   11378: 
                   11379: sub unmark_as_readonly {
1.629     banghart 11380:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11381:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11382:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11383:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11384:     my $symb_crs = $what;
                   11385:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11386:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11387:     my ($tmp)=keys(%current_permissions);
                   11388:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11389:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11390:     foreach my $file (@readonly_files) {
1.759     albertel 11391: 	my $clean_file = &declutter_portfile($file);
                   11392: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11393: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11394:         my @new_locks;
                   11395:         my @del_keys;
                   11396:         if (ref($current_locks) eq "ARRAY"){
                   11397:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11398:                 my $compare=$locker;
1.749     raeburn  11399:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11400:                     $compare=join('',@{$locker});
1.746     raeburn  11401:                     if ($compare ne $symb_crs) {
                   11402:                         push(@new_locks, $locker);
                   11403:                     }
1.563     banghart 11404:                 }
                   11405:             }
1.650     albertel 11406:             if (scalar(@new_locks) > 0) {
1.563     banghart 11407:                 $current_permissions{$file} = \@new_locks;
                   11408:             } else {
                   11409:                 push(@del_keys, $file);
1.613     albertel 11410:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11411:                 delete($current_permissions{$file});
1.563     banghart 11412:             }
                   11413:         }
1.561     banghart 11414:     }
1.613     albertel 11415:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11416:     return;
                   11417: }
1.512     banghart 11418: 
1.17      www      11419: # ------------------------------------------------------------ Directory lister
                   11420: 
                   11421: sub dirlist {
1.955     raeburn  11422:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11423:     $uri=~s/^\///;
                   11424:     $uri=~s/\/$//;
1.253     stredwic 11425:     my ($udom, $uname);
1.955     raeburn  11426:     if ($getuserdir) {
1.253     stredwic 11427:         $udom = $userdomain;
                   11428:         $uname = $username;
1.955     raeburn  11429:     } else {
                   11430:         (undef,$udom,$uname)=split(/\//,$uri);
                   11431:         if(defined($userdomain)) {
                   11432:             $udom = $userdomain;
                   11433:         }
                   11434:         if(defined($username)) {
                   11435:             $uname = $username;
                   11436:         }
1.253     stredwic 11437:     }
1.955     raeburn  11438:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11439: 
1.955     raeburn  11440:     $dirRoot = $perlvar{'lonDocRoot'};
                   11441:     if (defined($getpropath)) {
                   11442:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11443:         $dirRoot =~ s/\/$//;
1.955     raeburn  11444:     } elsif (defined($getuserdir)) {
                   11445:         my $subdir=$uname.'__';
                   11446:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11447:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11448:                    ."/$udom/$subdir/$uname";
                   11449:     } elsif (defined($alternateRoot)) {
                   11450:         $dirRoot = $alternateRoot;
1.751     banghart 11451:     }
1.253     stredwic 11452: 
                   11453:     if($udom) {
                   11454:         if($uname) {
1.1135    raeburn  11455:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11456:             if ($uhome eq 'no_host') {
                   11457:                 return ([],'no_host');
                   11458:             }
1.955     raeburn  11459:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11460:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11461:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11462:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11463:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11464:             } else {
                   11465:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11466:             }
1.605     matthew  11467:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11468:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11469:                 @listing_results = split(/:/,$listing);
                   11470:             } else {
                   11471:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11472:             }
1.1135    raeburn  11473:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11474:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11475:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11476:                 return ([],$listing);
                   11477:             } else {
                   11478:                 return (\@listing_results);
1.1135    raeburn  11479:             }
1.955     raeburn  11480:         } elsif(!$alternateRoot) {
1.1136    raeburn  11481:             my (%allusers,%listerror);
1.841     albertel 11482: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11483:  	    foreach my $tryserver (keys(%servers)) {
                   11484:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11485:                                   &escape($udom),$tryserver);
                   11486:                 if ($listing eq 'unknown_cmd') {
                   11487: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11488: 				      $udom, $tryserver);
                   11489:                 } else {
                   11490:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11491:                 }
1.841     albertel 11492: 		if ($listing eq 'unknown_cmd') {
                   11493: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11494: 				      $udom, $tryserver);
                   11495: 		    @listing_results = split(/:/,$listing);
                   11496: 		} else {
                   11497: 		    @listing_results =
                   11498: 			map { &unescape($_); } split(/:/,$listing);
                   11499: 		}
1.1136    raeburn  11500:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11501:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11502:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11503:                     $listerror{$tryserver} = $listing;
                   11504:                 } else {
1.841     albertel 11505: 		    foreach my $line (@listing_results) {
                   11506: 			my ($entry) = split(/&/,$line,2);
                   11507: 			$allusers{$entry} = 1;
                   11508: 		    }
                   11509: 		}
1.253     stredwic 11510:             }
1.1136    raeburn  11511:             my @alluserslist=();
1.800     albertel 11512:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11513:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11514:             }
1.1172.2.80  raeburn  11515:             if (!%listerror) {
                   11516:                 # no errors
                   11517:                 return (\@alluserslist);
                   11518:             } elsif (scalar(keys(%servers)) == 1) {
                   11519:                 # one library server, one error
                   11520:                 my ($key) = keys(%listerror);
                   11521:                 return (\@alluserslist, $listerror{$key});
                   11522:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11523:                 # con_lost indicates that we might miss data from at least one
                   11524:                 # library server
                   11525:                 return (\@alluserslist, 'con_lost');
                   11526:             } else {
                   11527:                 # multiple library servers and no con_lost -> data should be
                   11528:                 # complete.
                   11529:                 return (\@alluserslist);
                   11530:             }
                   11531: 
1.253     stredwic 11532:         } else {
1.1136    raeburn  11533:             return ([],'missing username');
1.253     stredwic 11534:         }
1.955     raeburn  11535:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11536:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11537:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11538:         return (\@all_domains);
1.955     raeburn  11539:     } else {
1.1136    raeburn  11540:         return ([],'missing domain');
1.275     stredwic 11541:     }
                   11542: }
                   11543: 
                   11544: # --------------------------------------------- GetFileTimestamp
                   11545: # This function utilizes dirlist and returns the date stamp for
                   11546: # when it was last modified.  It will also return an error of -1
                   11547: # if an error occurs
                   11548: 
                   11549: sub GetFileTimestamp {
1.955     raeburn  11550:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11551:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11552:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11553:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11554:                                     undef,$getuserdir);
                   11555:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11556:         return -1;
                   11557:     }
                   11558:     if (ref($fileref) eq 'ARRAY') {
                   11559:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11560:         # @stats contains first the filename, then the stat output
                   11561:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11562:     } else {
                   11563:         return -1;
1.253     stredwic 11564:     }
1.26      www      11565: }
                   11566: 
1.712     albertel 11567: sub stat_file {
                   11568:     my ($uri) = @_;
1.787     albertel 11569:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11570: 
1.955     raeburn  11571:     my ($udom,$uname,$file);
1.712     albertel 11572:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11573: 	($udom,$uname,$file) =
1.811     albertel 11574: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11575: 	$file = 'userfiles/'.$file;
                   11576:     }
                   11577:     if ($uri =~ m-^/res/-) {
                   11578: 	($udom,$uname) = 
1.807     albertel 11579: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11580: 	$file = $uri;
                   11581:     }
                   11582: 
                   11583:     if (!$udom || !$uname || !$file) {
                   11584: 	# unable to handle the uri
                   11585: 	return ();
                   11586:     }
1.956     raeburn  11587:     my $getpropath;
                   11588:     if ($file =~ /^userfiles\//) {
                   11589:         $getpropath = 1;
                   11590:     }
1.1136    raeburn  11591:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11592:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11593:         return ();
                   11594:     } else {
                   11595:         if (ref($listref) eq 'ARRAY') {
                   11596:             my @stats = split('&',$listref->[0]);
                   11597: 	    shift(@stats); #filename is first
                   11598: 	    return @stats;
                   11599:         }
1.712     albertel 11600:     }
                   11601:     return ();
                   11602: }
                   11603: 
1.26      www      11604: # -------------------------------------------------------- Value of a Condition
                   11605: 
1.713     albertel 11606: # gets the value of a specific preevaluated condition
                   11607: #    stored in the string  $env{user.state.<cid>}
                   11608: # or looks up a condition reference in the bighash and if if hasn't
                   11609: # already been evaluated recurses into docondval to get the value of
                   11610: # the condition, then memoizing it to 
                   11611: #   $env{user.state.<cid>.<condition>}
1.40      www      11612: sub directcondval {
                   11613:     my $number=shift;
1.620     albertel 11614:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11615: 	&Apache::lonuserstate::evalstate();
                   11616:     }
1.713     albertel 11617:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11618: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11619:     } elsif ($number =~ /^_/) {
                   11620: 	my $sub_condition;
                   11621: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11622: 		&GDBM_READER(),0640)) {
                   11623: 	    $sub_condition=$bighash{'conditions'.$number};
                   11624: 	    untie(%bighash);
                   11625: 	}
                   11626: 	my $value = &docondval($sub_condition);
1.949     raeburn  11627: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11628: 	return $value;
                   11629:     }
1.620     albertel 11630:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11631:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11632:     } else {
                   11633:        return 2;
                   11634:     }
                   11635: }
                   11636: 
1.713     albertel 11637: # get the collection of conditions for this resource
1.26      www      11638: sub condval {
                   11639:     my $condidx=shift;
1.54      www      11640:     my $allpathcond='';
1.713     albertel 11641:     foreach my $cond (split(/\|/,$condidx)) {
                   11642: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11643: 	    $allpathcond.=
                   11644: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11645: 	}
1.191     harris41 11646:     }
1.54      www      11647:     $allpathcond=~s/\|$//;
1.713     albertel 11648:     return &docondval($allpathcond);
                   11649: }
                   11650: 
                   11651: #evaluates an expression of conditions
                   11652: sub docondval {
                   11653:     my ($allpathcond) = @_;
                   11654:     my $result=0;
                   11655:     if ($env{'request.course.id'}
                   11656: 	&& defined($allpathcond)) {
                   11657: 	my $operand='|';
                   11658: 	my @stack;
                   11659: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11660: 	    if ($chunk eq '(') {
                   11661: 		push @stack,($operand,$result);
                   11662: 	    } elsif ($chunk eq ')') {
                   11663: 		my $before=pop @stack;
                   11664: 		if (pop @stack eq '&') {
                   11665: 		    $result=$result>$before?$before:$result;
                   11666: 		} else {
                   11667: 		    $result=$result>$before?$result:$before;
                   11668: 		}
                   11669: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11670: 		$operand=$chunk;
                   11671: 	    } else {
                   11672: 		my $new=directcondval($chunk);
                   11673: 		if ($operand eq '&') {
                   11674: 		    $result=$result>$new?$new:$result;
                   11675: 		} else {
                   11676: 		    $result=$result>$new?$result:$new;
                   11677: 		}
                   11678: 	    }
                   11679: 	}
1.26      www      11680:     }
                   11681:     return $result;
1.421     albertel 11682: }
                   11683: 
                   11684: # ---------------------------------------------------- Devalidate courseresdata
                   11685: 
                   11686: sub devalidatecourseresdata {
                   11687:     my ($coursenum,$coursedomain)=@_;
                   11688:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11689:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11690: }
                   11691: 
1.763     www      11692: 
1.200     www      11693: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11694: #
                   11695: #  Parameters:
                   11696: #      $coursenum    - Number of the course.
                   11697: #      $coursedomain - Domain at which the course was created.
                   11698: #  Returns:
                   11699: #     A hash of the course parameters along (I think) with timestamps
                   11700: #     and version info.
1.877     foxr     11701: 
1.624     albertel 11702: sub get_courseresdata {
                   11703:     my ($coursenum,$coursedomain)=@_;
1.200     www      11704:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11705:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11706:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11707:     my %dumpreply;
1.417     albertel 11708:     unless (defined($cached)) {
1.624     albertel 11709: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11710: 	$result=\%dumpreply;
1.251     albertel 11711: 	my ($tmp) = keys(%dumpreply);
                   11712: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11713: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11714: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11715: 	    return $tmp;
1.416     albertel 11716: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11717: 	    $result=undef;
1.599     albertel 11718: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11719: 	}
                   11720:     }
1.624     albertel 11721:     return $result;
                   11722: }
                   11723: 
1.633     albertel 11724: sub devalidateuserresdata {
                   11725:     my ($uname,$udom)=@_;
                   11726:     my $hashid="$udom:$uname";
                   11727:     &devalidate_cache_new('userres',$hashid);
                   11728: }
                   11729: 
1.624     albertel 11730: sub get_userresdata {
                   11731:     my ($uname,$udom)=@_;
                   11732:     #most student don\'t have any data set, check if there is some data
                   11733:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11734: 
                   11735:     my $hashid="$udom:$uname";
                   11736:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11737:     if (!defined($cached)) {
                   11738: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11739: 	$result=\%resourcedata;
                   11740: 	&do_cache_new('userres',$hashid,$result,600);
                   11741:     }
                   11742:     my ($tmp)=keys(%$result);
                   11743:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11744: 	return $result;
                   11745:     }
                   11746:     #error 2 occurs when the .db doesn't exist
                   11747:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11748:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11749: 	    &logthis("<font color=\"blue\">WARNING:".
                   11750: 		     " Trying to get resource data for ".
                   11751: 		     $uname." at ".$udom.": ".
                   11752: 		     $tmp."</font>");
                   11753:         }
1.624     albertel 11754:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11755: 	#&EXT_cache_set($udom,$uname);
                   11756: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11757: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11758:     }
                   11759:     return $tmp;
                   11760: }
1.879     foxr     11761: #----------------------------------------------- resdata - return resource data
                   11762: #  Purpose:
                   11763: #    Return resource data for either users or for a course.
                   11764: #  Parameters:
                   11765: #     $name      - Course/user name.
                   11766: #     $domain    - Name of the domain the user/course is registered on.
                   11767: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11768: #     @which     - Array of names of resources desired.
                   11769: #  Returns:
                   11770: #     The value of the first reasource in @which that is found in the
                   11771: #     resource hash.
                   11772: #  Exceptional Conditions:
                   11773: #     If the $type passed in is not valid (not the string 'course' or 
                   11774: #     'user', an undefined  reference is returned.
                   11775: #     If none of the resources are found, an undef is returned
1.624     albertel 11776: sub resdata {
                   11777:     my ($name,$domain,$type,@which)=@_;
                   11778:     my $result;
                   11779:     if ($type eq 'course') {
                   11780: 	$result=&get_courseresdata($name,$domain);
                   11781:     } elsif ($type eq 'user') {
                   11782: 	$result=&get_userresdata($name,$domain);
                   11783:     }
                   11784:     if (!ref($result)) { return $result; }    
1.251     albertel 11785:     foreach my $item (@which) {
1.927     albertel 11786: 	if (defined($result->{$item->[0]})) {
                   11787: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11788: 	}
1.250     albertel 11789:     }
1.291     albertel 11790:     return undef;
1.200     www      11791: }
                   11792: 
1.1172.2.146.  .1(raebu 11793:22): sub get_domain_lti {
                   11794:22):     my ($cdom,$context) = @_;
          .4(raebu 11795:22):     my ($name,$cachename,%lti);
          .1(raebu 11796:22):     if ($context eq 'consumer') {
                   11797:22):         $name = 'ltitools';
                   11798:22):     } elsif ($context eq 'provider') {
                   11799:22):         $name = 'lti';
          .4(raebu 11800:22):     } elsif ($context eq 'linkprot') {
                   11801:22):         $name = 'ltisec';
          .1(raebu 11802:22):     } else {
                   11803:22):         return %lti;
                   11804:22):     }
          .4(raebu 11805:22): 
                   11806:22):     if ($context eq 'linkprot') {
                   11807:22):         $cachename = $context;
                   11808:22):     } else {
                   11809:22):         $cachename = $name;
                   11810:22):     }
                   11811:22): 
                   11812:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11813:22):     if (defined($cached)) {
                   11814:22):         if (ref($result) eq 'HASH') {
                   11815:22):             %lti = %{$result};
                   11816:22):         }
                   11817:22):     } else {
                   11818:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11819:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11820:22):             if ($context eq 'linkprot') {
                   11821:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11822:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11823:22):                 }
                   11824:22):             } else {
                   11825:22):                 %lti = %{$domconfig{$name}};
                   11826:22):             }
                   11827:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11828:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11829:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11830:22):                     foreach my $id (keys(%lti)) {
                   11831:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11832:22):                             foreach my $item ('key','secret') {
                   11833:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11834:22):                             }
          .1(raebu 11835:22):                         }
                   11836:22):                     }
                   11837:22):                 }
                   11838:22):             }
                   11839:22):         }
                   11840:22):         my $cachetime = 24*60*60;
          .4(raebu 11841:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11842:22):     }
                   11843:22):     return %lti;
                   11844:22): }
                   11845:22): 
                   11846:22): sub get_course_lti {
                   11847:22):     my ($cnum,$cdom) = @_;
                   11848:22):     my $hashid=$cdom.'_'.$cnum;
                   11849:22):     my %courselti;
                   11850:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11851:22):     if (defined($cached)) {
                   11852:22):         if (ref($result) eq 'HASH') {
                   11853:22):             %courselti = %{$result};
                   11854:22):         }
                   11855:22):     } else {
                   11856:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11857:22):         my $cachetime = 24*60*60;
                   11858:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11859:22):     }
                   11860:22):     return %courselti;
                   11861:22): }
                   11862:22): 
          .3(raebu 11863:22): sub courselti_itemid {
                   11864:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11865:22):     my ($chome,$itemid);
                   11866:22):     $chome = &homeserver($cnum,$cdom);
                   11867:22):     return if ($chome eq 'no_host');
                   11868:22):     if (ref($params) eq 'HASH') {
                   11869:22):         my $items = &freeze_escape($params);
                   11870:22):         my $rep;
                   11871:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11872:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11873:22):         } else {
                   11874:22):             my $escurl = &escape($url);
                   11875:22):             my $escmethod = &escape($method);
                   11876:22):             my $items = &freeze_escape($params);
                   11877:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11878:22):         }
                   11879:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11880:22):                 ($rep eq 'unknown_cmd')) {
                   11881:22):             $itemid = $rep;
                   11882:22):         }
                   11883:22):     }
                   11884:22):     return $itemid;
                   11885:22): }
                   11886:22): 
                   11887:22): sub domainlti_itemid {
                   11888:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11889:22):     my ($primary_id,$itemid);
                   11890:22):     $primary_id = &domain($cdom,'primary');
                   11891:22):     return if ($primary_id eq '');
                   11892:22):     if (ref($params) eq 'HASH') {
                   11893:22):         my $items = &freeze_escape($params);
                   11894:22):         my $rep;
                   11895:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11896:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11897:22):         } else {
                   11898:22):             my $cnum = '';
                   11899:22):             my $escurl = &escape($url);
                   11900:22):             my $escmethod = &escape($method);
                   11901:22):             my $items = &freeze_escape($params);
                   11902:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11903:22):         }
                   11904:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11905:22):                 ($rep eq 'unknown_cmd')) {
                   11906:22):             $itemid = $rep;
                   11907:22):         }
                   11908:22):     }
                   11909:22):     return $itemid;
                   11910:22): }
                   11911:22): 
          .9(raebu 11912:23): sub count_supptools {
                   11913:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  11914:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 11915:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  11916:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 11917:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  11918:     }
                   11919:     unless (defined($cached)) {
                   11920:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 11921:23):         $numexttools = 0;
1.1172.2.31  raeburn  11922:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 11923:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   11924:23):             if (ref($supplemental) eq 'HASH') {
                   11925:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11926:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11927:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   11928:23):                             $numexttools ++;
                   11929:23):                         }
                   11930:23):                     }
                   11931:23):                 }
                   11932:23):             }
1.1172.2.31  raeburn  11933:         }
1.1172.2.146.  .9(raebu 11934:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  11935:     }
1.1172.2.146.  .9(raebu 11936:23):     return $numexttools;
                   11937:23): }
                   11938:23): 
                   11939:23): sub has_unhidden_suppfiles {
                   11940:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   11941:23):     my $hashid=$cnum.':'.$cdom;
                   11942:23):     my ($showsupp,$cached);
                   11943:23):     unless ($ignorecache) {
                   11944:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   11945:23):     }
                   11946:23):     unless (defined($cached)) {
                   11947:23):         my $chome=&homeserver($cnum,$cdom);
                   11948:23):         unless ($chome eq 'no_host') {
                   11949:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   11950:23):             if (ref($supplemental) eq 'HASH') {
                   11951:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11952:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11953:23):                         next if ($key =~ /\.sequence$/);
                   11954:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   11955:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   11956:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   11957:23):                                     $showsupp = 1;
                   11958:23):                                     last;
                   11959:23):                                 }
                   11960:23):                             }
                   11961:23):                         }
                   11962:23):                         last if ($showsupp);
                   11963:23):                     }
                   11964:23):                 }
                   11965:23):             }
                   11966:23):         }
                   11967:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   11968:23):     }
                   11969:23):     return $showsupp;
1.1172.2.31  raeburn  11970: }
                   11971: 
1.379     matthew  11972: #
                   11973: # EXT resource caching routines
                   11974: #
                   11975: 
1.1172.2.146.  .1(raebu 11976:22): {
                   11977:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11978:22): #
                   11979:22): # The course for which we cache
                   11980:22): my $cachedmapkey='';
                   11981:22): # The cached recursive maps for this course
                   11982:22): my %cachedmaps=();
                   11983:22): # When this was last done
                   11984:22): my $cachedmaptime='';
                   11985:22): 
1.379     matthew  11986: sub clear_EXT_cache_status {
1.383     albertel 11987:     &delenv('cache.EXT.');
1.379     matthew  11988: }
                   11989: 
                   11990: sub EXT_cache_status {
                   11991:     my ($target_domain,$target_user) = @_;
1.383     albertel 11992:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11993:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11994:         # We know already the user has no data
                   11995:         return 1;
                   11996:     } else {
                   11997:         return 0;
                   11998:     }
                   11999: }
                   12000: 
                   12001: sub EXT_cache_set {
                   12002:     my ($target_domain,$target_user) = @_;
1.383     albertel 12003:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12004:     #&appenv({$cachename => time});
1.379     matthew  12005: }
                   12006: 
1.28      www      12007: # --------------------------------------------------------- Value of a Variable
1.58      www      12008: sub EXT {
1.715     albertel 12009: 
1.1172.2.28  raeburn  12010:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12011:     unless ($varname) { return ''; }
1.218     albertel 12012:     #get real user name/domain, courseid and symb
                   12013:     my $courseid;
1.359     albertel 12014:     my $publicuser;
1.427     www      12015:     if ($symbparm) {
                   12016: 	$symbparm=&get_symb_from_alias($symbparm);
                   12017:     }
1.218     albertel 12018:     if (!($uname && $udom)) {
1.790     albertel 12019:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12020:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12021:     } else {
1.620     albertel 12022: 	$courseid=$env{'request.course.id'};
1.218     albertel 12023:     }
1.48      www      12024:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12025:     my $rest;
1.320     albertel 12026:     if (defined($therest[0])) {
1.48      www      12027:        $rest=join('.',@therest);
                   12028:     } else {
                   12029:        $rest='';
                   12030:     }
1.320     albertel 12031: 
1.57      www      12032:     my $qualifierrest=$qualifier;
                   12033:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12034:     my $spacequalifierrest=$space;
                   12035:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12036:     if ($realm eq 'user') {
1.48      www      12037: # --------------------------------------------------------------- user.resource
                   12038: 	if ($space eq 'resource') {
1.651     albertel 12039: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12040: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12041: 		 &&
1.1172.2.142  raeburn  12042: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12043: 		# if we are in the middle of processing the resource the
                   12044: 		# get the value we are planning on committing
                   12045:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12046:                     return $Apache::lonhomework::results{$qualifierrest};
                   12047:                 } else {
                   12048:                     return $Apache::lonhomework::history{$qualifierrest};
                   12049:                 }
1.335     albertel 12050: 	    } else {
1.359     albertel 12051: 		my %restored;
1.620     albertel 12052: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12053: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12054: 		} else {
                   12055: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12056: 		}
1.335     albertel 12057: 		return $restored{$qualifierrest};
                   12058: 	    }
1.48      www      12059: # ----------------------------------------------------------------- user.access
                   12060:         } elsif ($space eq 'access') {
1.218     albertel 12061: 	    # FIXME - not supporting calls for a specific user
1.48      www      12062:             return &allowed($qualifier,$rest);
                   12063: # ------------------------------------------ user.preferences, user.environment
                   12064:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12065: 	    if (($uname eq $env{'user.name'}) &&
                   12066: 		($udom eq $env{'user.domain'})) {
                   12067: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12068: 	    } else {
1.359     albertel 12069: 		my %returnhash;
                   12070: 		if (!$publicuser) {
                   12071: 		    %returnhash=&userenvironment($udom,$uname,
                   12072: 						 $qualifierrest);
                   12073: 		}
1.218     albertel 12074: 		return $returnhash{$qualifierrest};
                   12075: 	    }
1.48      www      12076: # ----------------------------------------------------------------- user.course
                   12077:         } elsif ($space eq 'course') {
1.218     albertel 12078: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12079:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12080: # ------------------------------------------------------------------- user.role
                   12081:         } elsif ($space eq 'role') {
1.218     albertel 12082: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12083:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12084:             if ($qualifier eq 'value') {
                   12085: 		return $role;
                   12086:             } elsif ($qualifier eq 'extent') {
                   12087:                 return $where;
                   12088:             }
                   12089: # ----------------------------------------------------------------- user.domain
                   12090:         } elsif ($space eq 'domain') {
1.218     albertel 12091:             return $udom;
1.48      www      12092: # ------------------------------------------------------------------- user.name
                   12093:         } elsif ($space eq 'name') {
1.218     albertel 12094:             return $uname;
1.48      www      12095: # ---------------------------------------------------- Any other user namespace
1.29      www      12096:         } else {
1.359     albertel 12097: 	    my %reply;
                   12098: 	    if (!$publicuser) {
                   12099: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12100: 	    }
                   12101: 	    return $reply{$qualifierrest};
1.48      www      12102:         }
1.236     www      12103:     } elsif ($realm eq 'query') {
                   12104: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12105:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12106: 						[$spacequalifierrest]);
1.620     albertel 12107: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12108:    } elsif ($realm eq 'request') {
1.48      www      12109: # ------------------------------------------------------------- request.browser
                   12110:         if ($space eq 'browser') {
1.1145    bisitz   12111:             return $env{'browser.'.$qualifier};
1.57      www      12112: # ------------------------------------------------------------ request.filename
                   12113:         } else {
1.620     albertel 12114:             return $env{'request.'.$spacequalifierrest};
1.29      www      12115:         }
1.28      www      12116:     } elsif ($realm eq 'course') {
1.48      www      12117: # ---------------------------------------------------------- course.description
1.620     albertel 12118:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12119:     } elsif ($realm eq 'resource') {
1.165     www      12120: 
1.620     albertel 12121: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12122: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12123: 	}
1.693     albertel 12124: 
1.1172.2.30  raeburn  12125:         if ($qualifier eq '') {
                   12126: 	    if ($space eq 'title') {
                   12127: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12128: 	        return &gettitle($symbparm);
                   12129: 	    }
1.693     albertel 12130: 	
1.1172.2.30  raeburn  12131: 	    if ($space eq 'map') {
                   12132: 	        my ($map) = &decode_symb($symbparm);
                   12133: 	        return &symbread($map);
                   12134: 	    }
                   12135:             if ($space eq 'maptitle') {
                   12136:                 my ($map) = &decode_symb($symbparm);
                   12137:                 return &gettitle($map);
                   12138:             }
                   12139: 	    if ($space eq 'filename') {
                   12140: 	        if ($symbparm) {
                   12141: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12142: 	        }
                   12143: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12144: 	    }
1.1172.2.30  raeburn  12145: 
                   12146:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12147:                 if ($space eq 'visibleparts') {
                   12148:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12149:                     my $item;
                   12150:                     if (ref($navmap)) {
                   12151:                         my $res = $navmap->getBySymb($symbparm);
                   12152:                         my $parts = $res->parts();
                   12153:                         if (ref($parts) eq 'ARRAY') {
                   12154:                             $item = join(',',@{$parts});
                   12155:                         }
                   12156:                         undef($navmap);
                   12157:                     }
                   12158:                     return $item;
                   12159:                 }
                   12160:             }
                   12161:         }
1.693     albertel 12162: 
                   12163: 	my ($section, $group, @groups);
1.593     albertel 12164: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12165:         if (($courseid eq '') && ($cid)) {
                   12166:             $courseid = $cid;
                   12167:         }
                   12168: 	if (($symbparm && $courseid) && 
                   12169: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12170: 
1.218     albertel 12171: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12172: 
1.60      www      12173: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12174: 	    my $symbp=$symbparm;
1.735     albertel 12175: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12176: 
                   12177: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12178: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12179: 
1.620     albertel 12180: 	    if (($env{'user.name'} eq $uname) &&
                   12181: 		($env{'user.domain'} eq $udom)) {
                   12182: 		$section=$env{'request.course.sec'};
1.733     raeburn  12183:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12184:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12185: 	    } else {
1.539     albertel 12186: 		if (! defined($usection)) {
1.551     albertel 12187: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12188: 		} else {
                   12189: 		    $section = $usection;
                   12190: 		}
1.733     raeburn  12191:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12192: 	    }
                   12193: 
                   12194: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12195: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12196: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12197: 
1.593     albertel 12198: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12199: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12200: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12201: 
1.60      www      12202: # ----------------------------------------------------------- first, check user
1.624     albertel 12203: 
                   12204: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12205: 				       ([$courselevelr,'resource'],
                   12206: 					[$courselevelm,'map'     ],
                   12207: 					[$courselevel, 'course'  ]));
1.931     albertel 12208: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12209: 
1.594     albertel 12210: # ------------------------------------------------ second, check some of course
1.684     raeburn  12211:             my $coursereply;
1.691     raeburn  12212:             if (@groups > 0) {
                   12213:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12214:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12215:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12216:             }
1.96      www      12217: 
1.684     raeburn  12218: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12219: 				  $env{'course.'.$courseid.'.domain'},
                   12220: 				  'course',
                   12221: 				  ([$seclevelr,   'resource'],
                   12222: 				   [$seclevelm,   'map'     ],
                   12223: 				   [$seclevel,    'course'  ],
                   12224: 				   [$courselevelr,'resource']));
                   12225: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12226: 
1.60      www      12227: # ------------------------------------------------------ third, check map parms
1.218     albertel 12228: 	    my %parmhash=();
                   12229: 	    my $thisparm='';
                   12230: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12231: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12232: 		    &GDBM_READER(),0640)) {
1.218     albertel 12233: 		$thisparm=$parmhash{$symbparm};
                   12234: 		untie(%parmhash);
                   12235: 	    }
1.927     albertel 12236: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12237: 	}
1.594     albertel 12238: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12239: 
1.218     albertel 12240: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12241: 	my $filename;
                   12242: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12243: 	if ($symbparm) {
1.409     www      12244: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12245: 	} else {
1.620     albertel 12246: 	    $filename=$env{'request.filename'};
1.282     albertel 12247: 	}
                   12248: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12249: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12250: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12251: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12252: 
1.927     albertel 12253: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12254: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12255: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12256: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12257: 				     $env{'course.'.$courseid.'.domain'},
                   12258: 				     'course',
1.927     albertel 12259: 				     ([$courselevelm,'map'   ],
                   12260: 				      [$courselevel, 'course']));
                   12261: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12262: 	}
1.145     www      12263: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12264: 	unless ($space eq '0') {
1.336     albertel 12265: 	    my @parts=split(/_/,$space);
                   12266: 	    my $id=pop(@parts);
                   12267: 	    my $part=join('_',@parts);
                   12268: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12269: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12270: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12271: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12272: 	}
1.395     albertel 12273: 	if ($recurse) { return undef; }
                   12274: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12275: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12276: # ---------------------------------------------------- Any other user namespace
                   12277:     } elsif ($realm eq 'environment') {
                   12278: # ----------------------------------------------------------------- environment
1.620     albertel 12279: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12280: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12281: 	} else {
1.770     albertel 12282: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12283: 		return '';
                   12284: 	    }
1.219     albertel 12285: 	    my %returnhash=&userenvironment($udom,$uname,
                   12286: 					    $spacequalifierrest);
                   12287: 	    return $returnhash{$spacequalifierrest};
                   12288: 	}
1.28      www      12289:     } elsif ($realm eq 'system') {
1.48      www      12290: # ----------------------------------------------------------------- system.time
                   12291: 	if ($space eq 'time') {
                   12292: 	    return time;
                   12293:         }
1.696     albertel 12294:     } elsif ($realm eq 'server') {
                   12295: # ----------------------------------------------------------------- system.time
                   12296: 	if ($space eq 'name') {
                   12297: 	    return $ENV{'SERVER_NAME'};
                   12298:         }
1.1172.2.146.  .1(raebu 12299:22):     } elsif ($realm eq 'client') {
                   12300:22):         if ($space eq 'remote_addr') {
                   12301:22):             return &get_requestor_ip();
                   12302:22):         }
1.28      www      12303:     }
1.48      www      12304:     return '';
1.61      www      12305: }
                   12306: 
1.927     albertel 12307: sub get_reply {
                   12308:     my ($reply_value) = @_;
1.940     raeburn  12309:     if (ref($reply_value) eq 'ARRAY') {
                   12310:         if (wantarray) {
                   12311: 	    return @$reply_value;
                   12312:         }
                   12313:         return $reply_value->[0];
                   12314:     } else {
                   12315:         return $reply_value;
1.927     albertel 12316:     }
                   12317: }
                   12318: 
1.691     raeburn  12319: sub check_group_parms {
                   12320:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12321:     my @groupitems = ();
                   12322:     my $resultitem;
1.927     albertel 12323:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12324:     foreach my $group (@{$groups}) {
                   12325:         foreach my $level (@levels) {
1.927     albertel 12326:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12327:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12328:         }
                   12329:     }
                   12330:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12331:                             $env{'course.'.$courseid.'.domain'},
                   12332:                                      'course',@groupitems);
                   12333:     return $coursereply;
                   12334: }
                   12335: 
1.1172.2.146.  .1(raebu 12336:22): sub get_map_hierarchy {
                   12337:22):     my ($mapname,$courseid) = @_;
                   12338:22):     my @recurseup = ();
                   12339:22):     if ($mapname) {
                   12340:22):         if (($cachedmapkey eq $courseid) &&
                   12341:22):             (abs($cachedmaptime-time)<5)) {
                   12342:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12343:22):                 return @{$cachedmaps{$mapname}};
                   12344:22):             }
                   12345:22):         }
                   12346:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12347:22):         if (ref($navmap)) {
                   12348:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12349:22):             undef($navmap);
                   12350:22):             $cachedmaps{$mapname} = \@recurseup;
                   12351:22):             $cachedmaptime=time;
                   12352:22):             $cachedmapkey=$courseid;
                   12353:22):         }
                   12354:22):     }
                   12355:22):     return @recurseup;
                   12356:22): }
                   12357:22): 
          .2(raebu 12358:22): }
          .1(raebu 12359:22): 
1.691     raeburn  12360: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12361:     my ($courseid,@groups) = @_;
                   12362:     @groups = sort(@groups);
1.691     raeburn  12363:     return @groups;
                   12364: }
                   12365: 
1.395     albertel 12366: sub packages_tab_default {
                   12367:     my ($uri,$varname)=@_;
                   12368:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12369: 
                   12370:     my (@extension,@specifics,$do_default);
                   12371:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12372: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12373: 	if ($pack_type eq 'default') {
                   12374: 	    $do_default=1;
                   12375: 	} elsif ($pack_type eq 'extension') {
                   12376: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12377: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12378: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12379: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12380: 	}
                   12381:     }
                   12382:     # first look for a package that matches the requested part id
                   12383:     foreach my $package (@specifics) {
                   12384: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12385: 	next if ($pack_part ne $part);
                   12386: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12387: 	    return $packagetab{"$pack_type&$name&default"};
                   12388: 	}
                   12389:     }
                   12390:     # look for any possible matching non extension_ package
                   12391:     foreach my $package (@specifics) {
                   12392: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12393: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12394: 	    return $packagetab{"$pack_type&$name&default"};
                   12395: 	}
1.585     albertel 12396: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12397: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12398: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12399: 	}
                   12400:     }
1.738     albertel 12401:     # look for any posible extension_ match
                   12402:     foreach my $package (@extension) {
                   12403: 	my ($package,$pack_type)=@{$package};
                   12404: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12405: 	    return $packagetab{"$pack_type&$name&default"};
                   12406: 	}
                   12407: 	if (defined($packagetab{$package."&$name&default"})) {
                   12408: 	    return $packagetab{$package."&$name&default"};
                   12409: 	}
                   12410:     }
                   12411:     # look for a global default setting
                   12412:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12413: 	return $packagetab{"default&$name&default"};
                   12414:     }
1.395     albertel 12415:     return undef;
                   12416: }
                   12417: 
1.334     albertel 12418: sub add_prefix_and_part {
                   12419:     my ($prefix,$part)=@_;
                   12420:     my $keyroot;
                   12421:     if (defined($prefix) && $prefix !~ /^__/) {
                   12422: 	# prefix that has a part already
                   12423: 	$keyroot=$prefix;
                   12424:     } elsif (defined($prefix)) {
                   12425: 	# prefix that is missing a part
                   12426: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12427:     } else {
                   12428: 	# no prefix at all
                   12429: 	if (defined($part)) { $keyroot='_'.$part; }
                   12430:     }
                   12431:     return $keyroot;
                   12432: }
                   12433: 
1.71      www      12434: # ---------------------------------------------------------------- Get metadata
                   12435: 
1.599     albertel 12436: my %metaentry;
1.1070    www      12437: my %importedpartids;
1.1172.2.99  raeburn  12438: my %importedrespids;
1.71      www      12439: sub metadata {
1.176     www      12440:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12441:     $uri=&declutter($uri);
1.288     albertel 12442:     # if it is a non metadata possible uri return quickly
1.529     albertel 12443:     if (($uri eq '') || 
                   12444: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12445:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12446:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12447: 	return undef;
                   12448:     }
1.1172.2.49  raeburn  12449:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12450: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12451: 	return undef;
1.288     albertel 12452:     }
1.73      www      12453:     my $filename=$uri;
                   12454:     $uri=~s/\.meta$//;
1.172     www      12455: #
                   12456: # Is the metadata already cached?
1.177     www      12457: # Look at timestamp of caching
1.172     www      12458: # Everything is cached by the main uri, libraries are never directly cached
                   12459: #
1.428     albertel 12460:     if (!defined($liburi)) {
1.599     albertel 12461: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12462: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12463:     }
                   12464:     {
1.1069    www      12465: # Imported parts would go here
1.1172.2.99  raeburn  12466:         my @origfiletagids=();
1.1069    www      12467:         my $importedparts=0;
1.1172.2.99  raeburn  12468: 
                   12469: # Imported responseids would go here
                   12470:         my $importedresponses=0;
1.172     www      12471: #
                   12472: # Is this a recursive call for a library?
                   12473: #
1.599     albertel 12474: #	if (! exists($metacache{$uri})) {
                   12475: #	    $metacache{$uri}={};
                   12476: #	}
1.924     albertel 12477: 	my $cachetime = 60*60;
1.171     www      12478:         if ($liburi) {
                   12479: 	    $liburi=&declutter($liburi);
                   12480:             $filename=$liburi;
1.401     bowersj2 12481:         } else {
1.599     albertel 12482: 	    &devalidate_cache_new('meta',$uri);
                   12483: 	    undef(%metaentry);
1.401     bowersj2 12484: 	}
1.140     www      12485:         my %metathesekeys=();
1.73      www      12486:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12487: 	my $metastring;
1.1140    www      12488: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12489: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12490: 	    $metastring = 
1.929     albertel 12491: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12492: 					  ('grade_target' => 'meta'));
                   12493: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12494: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12495:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12496: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12497: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12498: 	    $metastring=&getfile($file);
1.489     albertel 12499: 	}
1.208     albertel 12500:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12501:         my $token;
1.140     www      12502:         undef %metathesekeys;
1.71      www      12503:         while ($token=$parser->get_token) {
1.339     albertel 12504: 	    if ($token->[0] eq 'S') {
                   12505: 		if (defined($token->[2]->{'package'})) {
1.172     www      12506: #
                   12507: # This is a package - get package info
                   12508: #
1.339     albertel 12509: 		    my $package=$token->[2]->{'package'};
                   12510: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12511: 		    if (defined($token->[2]->{'id'})) { 
                   12512: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12513: 		    }
1.599     albertel 12514: 		    if ($metaentry{':packages'}) {
                   12515: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12516: 		    } else {
1.599     albertel 12517: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12518: 		    }
1.736     albertel 12519: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12520: 			my $part=$keyroot;
                   12521: 			$part=~s/^\_//;
1.736     albertel 12522: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12523: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12524: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12525: 			    # ignore package.tab specified default values
                   12526:                             # here &package_tab_default() will fetch those
                   12527: 			    if ($subp eq 'default') { next; }
1.736     albertel 12528: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12529: 			    my $unikey;
                   12530: 			    if ($pack =~ /_0$/) {
                   12531: 				$unikey='parameter_0_'.$name;
                   12532: 				$part=0;
                   12533: 			    } else {
                   12534: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12535: 			    }
1.339     albertel 12536: 			    if ($subp eq 'display') {
                   12537: 				$value.=' [Part: '.$part.']';
                   12538: 			    }
1.599     albertel 12539: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12540: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12541: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12542: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12543: 			    }
1.599     albertel 12544: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12545: 				$metaentry{':'.$unikey}=
                   12546: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12547: 			    }
1.339     albertel 12548: 			}
                   12549: 		    }
                   12550: 		} else {
1.172     www      12551: #
                   12552: # This is not a package - some other kind of start tag
1.339     albertel 12553: #
                   12554: 		    my $entry=$token->[1];
1.1068    www      12555: 		    my $unikey='';
1.175     www      12556: 
1.339     albertel 12557: 		    if ($entry eq 'import') {
1.175     www      12558: #
                   12559: # Importing a library here
1.339     albertel 12560: #
1.1067    www      12561:                         my $location=$parser->get_text('/import');
                   12562:                         my $dir=$filename;
                   12563:                         $dir=~s|[^/]*$||;
                   12564:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12565: 
                   12566:                         my $importid=$token->[2]->{'id'};
1.1068    www      12567:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12568: #
                   12569: # Check metadata for imported file to
                   12570: # see if it contained response items
                   12571: #
                   12572:                         my %currmetaentry = %metaentry;
                   12573:                         my $libresponseorder = &metadata($location,'responseorder');
                   12574:                         my $origfile;
                   12575:                         if ($libresponseorder ne '') {
                   12576:                             if ($#origfiletagids<0) {
                   12577:                                 undef(%importedrespids);
                   12578:                                 undef(%importedpartids);
                   12579:                             }
                   12580:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12581:                             if (@{$importedrespids{$importid}} > 0) {
                   12582:                                 $importedresponses = 1;
                   12583: # We need to get the original file and the imported file to get the response order correct
                   12584: # Load and inspect original file
                   12585:                                 if ($#origfiletagids<0) {
                   12586:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12587:                                     $origfile=&getfile($origfilelocation);
                   12588:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12589:                                 }
                   12590:                             }
                   12591:                         }
                   12592: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12593: # hash populated for imported library file
                   12594:                         %metaentry = %currmetaentry;
                   12595:                         undef(%currmetaentry);
1.1068    www      12596:                         if ($importmode eq 'problem') {
1.1069    www      12597: # Import as problem/response
1.1068    www      12598:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12599:                         } elsif ($importmode eq 'part') {
                   12600: # Import as part(s)
1.1069    www      12601:                            $importedparts=1;
                   12602: # We need to get the original file and the imported file to get the part order correct
                   12603: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12604: # Load and inspect original file if we didn't do that already
                   12605:                            if ($#origfiletagids<0) {
                   12606:                                undef(%importedrespids);
                   12607:                                undef(%importedpartids);
                   12608:                                if ($origfile eq '') {
                   12609:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12610:                                    $origfile=&getfile($origfilelocation);
                   12611:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12612:                                }
1.1070    www      12613:                            }
                   12614: 
1.1069    www      12615: # Load and inspect imported file
                   12616:                            my $impfile=&getfile($location);
                   12617:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12618:                            if ($#impfilepartids>=0) {
                   12619: # This problem had parts
1.1070    www      12620:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12621:                            } else {
                   12622: # Importing by turning a single problem into a problem part
                   12623: # It gets the import-tags ID as part-ID
                   12624:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12625:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12626:                            }
1.1068    www      12627:                         } else {
                   12628: # Normal import
                   12629:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12630:                            if (defined($token->[2]->{'id'})) {
                   12631:                               $unikey.='_'.$token->[2]->{'id'};
                   12632:                            }
1.1067    www      12633:                         }
                   12634: 
1.339     albertel 12635: 			if ($depthcount<20) {
1.736     albertel 12636: 			    my $metadata = 
                   12637: 				&metadata($uri,'keys', $location,$unikey,
                   12638: 					  $depthcount+1);
                   12639: 			    foreach my $meta (split(',',$metadata)) {
                   12640: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12641: 				$metathesekeys{$meta}=1;
1.339     albertel 12642: 			    }
1.1068    www      12643: 			
                   12644:                         }
1.1067    www      12645: 		    } else {
                   12646: #
                   12647: # Not importing, some other kind of non-package, non-library start tag
                   12648: # 
                   12649:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12650:                         if (defined($token->[2]->{'id'})) {
                   12651:                             $unikey.='_'.$token->[2]->{'id'};
                   12652:                         }
1.339     albertel 12653: 			if (defined($token->[2]->{'name'})) { 
                   12654: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12655: 			}
                   12656: 			$metathesekeys{$unikey}=1;
1.736     albertel 12657: 			foreach my $param (@{$token->[3]}) {
                   12658: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12659: 				$token->[2]->{$param};
1.339     albertel 12660: 			}
                   12661: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12662: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12663: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12664: 		 # only ws inside the tag, and not in default, so use default
                   12665: 		 # as value
1.599     albertel 12666: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12667: 			} elsif ( $internaltext =~ /\S/ ) {
                   12668: 		  # something interesting inside the tag
                   12669: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12670: 			} else {
1.908     albertel 12671: 		  # no interesting values, don't set a default
1.339     albertel 12672: 			}
1.172     www      12673: # end of not-a-package not-a-library import
1.339     albertel 12674: 		    }
1.172     www      12675: # end of not-a-package start tag
1.339     albertel 12676: 		}
1.172     www      12677: # the next is the end of "start tag"
1.339     albertel 12678: 	    }
                   12679: 	}
1.483     albertel 12680: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12681: 	$extension = lc($extension);
                   12682: 	if ($extension eq 'htm') { $extension='html'; }
                   12683: 
1.737     albertel 12684: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12685: 	    #no specific packages #how's our extension
                   12686: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12687: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12688: 					 \%metathesekeys);
                   12689: 	}
1.883     albertel 12690: 
                   12691: 	if (!exists($metaentry{':packages'})
                   12692: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12693: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12694: 		#no specific packages well let's get default then
                   12695: 		if ($key!~/^default&/) { next; }
1.488     albertel 12696: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12697: 					     \%metathesekeys);
                   12698: 	    }
                   12699: 	}
1.338     www      12700: # are there custom rights to evaluate
1.599     albertel 12701: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12702: 
1.338     www      12703:     #
                   12704:     # Importing a rights file here
1.339     albertel 12705:     #
                   12706: 	    unless ($depthcount) {
1.599     albertel 12707: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12708: 		my $dir=$filename;
                   12709: 		$dir=~s|[^/]*$||;
                   12710: 		$location=&filelocation($dir,$location);
1.736     albertel 12711: 		my $rights_metadata =
                   12712: 		    &metadata($uri,'keys',$location,'_rights',
                   12713: 			      $depthcount+1);
                   12714: 		foreach my $rights (split(',',$rights_metadata)) {
                   12715: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12716: 		    $metathesekeys{$rights}=1;
1.339     albertel 12717: 		}
                   12718: 	    }
                   12719: 	}
1.737     albertel 12720: 	# uniqifiy package listing
                   12721: 	my %seen;
                   12722: 	my @uniq_packages =
                   12723: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12724: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12725: 
1.1172.2.99  raeburn  12726:         if (($importedresponses) || ($importedparts)) {
                   12727:             if ($importedparts) {
1.1070    www      12728: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12729:                 $metaentry{':partorder'}='';
                   12730:                 $metathesekeys{'partorder'}=1;
                   12731:             }
                   12732:             if ($importedresponses) {
                   12733: # We had imported responses and need to rebuild responseorder
                   12734:                 $metaentry{':responseorder'}='';
                   12735:                 $metathesekeys{'responseorder'}=1;
                   12736:             }
                   12737:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12738:                 my $origid = $origfiletagids[$index+1];
                   12739:                 if ($origfiletagids[$index] eq 'part') {
                   12740: # Original part, part of the problem
                   12741:                     if ($importedparts) {
                   12742:                         $metaentry{':partorder'}.=','.$origid;
                   12743:                     }
                   12744:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12745:                     if ($importedparts) {
                   12746: # We have imported parts at this position
                   12747:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12748:                     }
                   12749:                     if ($importedresponses) {
                   12750: # We have imported responses at this position
                   12751:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12752:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12753:                         }
                   12754:                     }
                   12755:                 } else {
                   12756: # Original response item, part of the problem
                   12757:                     if ($importedresponses) {
                   12758:                         $metaentry{':responseorder'}.=','.$origid;
                   12759:                     }
                   12760:                 }
                   12761:             }
                   12762:             if ($importedparts) {
                   12763:                 $metaentry{':partorder'}=~s/^\,//;
                   12764:             }
                   12765:             if ($importedresponses) {
                   12766:                 $metaentry{':responseorder'}=~s/^\,//;
                   12767:             }
1.1070    www      12768:         }
                   12769: 
1.737     albertel 12770: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12771: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12772: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12773: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12774: # this is the end of "was not already recently cached
1.71      www      12775:     }
1.599     albertel 12776:     return $metaentry{':'.$what};
1.261     albertel 12777: }
                   12778: 
1.488     albertel 12779: sub metadata_create_package_def {
1.483     albertel 12780:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12781:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12782:     if ($subp eq 'default') { next; }
                   12783:     
1.599     albertel 12784:     if (defined($metaentry{':packages'})) {
                   12785: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12786:     } else {
1.599     albertel 12787: 	$metaentry{':packages'}=$package;
1.483     albertel 12788:     }
                   12789:     my $value=$packagetab{$key};
                   12790:     my $unikey;
                   12791:     $unikey='parameter_0_'.$name;
1.599     albertel 12792:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12793:     $$metathesekeys{$unikey}=1;
1.599     albertel 12794:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12795: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12796:     }
1.599     albertel 12797:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12798: 	$metaentry{':'.$unikey}=
                   12799: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12800:     }
                   12801: }
                   12802: 
1.261     albertel 12803: sub metadata_generate_part0 {
                   12804:     my ($metadata,$metacache,$uri) = @_;
                   12805:     my %allnames;
1.737     albertel 12806:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12807: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12808: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12809: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12810: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12811: 	    $allnames{$name}=$part;
                   12812: 	  }
                   12813: 	}
                   12814:     }
                   12815:     foreach my $name (keys(%allnames)) {
                   12816:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12817:       my $key=":parameter_0_$name";
1.261     albertel 12818:       $$metacache{"$key.part"}='0';
                   12819:       $$metacache{"$key.name"}=$name;
1.428     albertel 12820:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12821: 					   $allnames{$name}.'_'.$name.
                   12822: 					   '.type'};
1.428     albertel 12823:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12824: 			     '.display'};
1.644     www      12825:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12826:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12827:       $$metacache{"$key.display"}=$olddis;
                   12828:     }
1.71      www      12829: }
                   12830: 
1.764     albertel 12831: # ------------------------------------------------------ Devalidate title cache
                   12832: 
                   12833: sub devalidate_title_cache {
                   12834:     my ($url)=@_;
                   12835:     if (!$env{'request.course.id'}) { return; }
                   12836:     my $symb=&symbread($url);
                   12837:     if (!$symb) { return; }
                   12838:     my $key=$env{'request.course.id'}."\0".$symb;
                   12839:     &devalidate_cache_new('title',$key);
                   12840: }
                   12841: 
1.1014    droeschl 12842: # ------------------------------------------------- Get the title of a course
                   12843: 
                   12844: sub current_course_title {
                   12845:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12846: }
1.301     www      12847: # ------------------------------------------------- Get the title of a resource
                   12848: 
                   12849: sub gettitle {
                   12850:     my $urlsymb=shift;
                   12851:     my $symb=&symbread($urlsymb);
1.534     albertel 12852:     if ($symb) {
1.620     albertel 12853: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12854: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12855: 	if (defined($cached)) { 
                   12856: 	    return $result;
                   12857: 	}
1.534     albertel 12858: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12859: 	my $title='';
1.907     albertel 12860: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12861: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12862: 	} else {
                   12863: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12864: 		    &GDBM_READER(),0640)) {
                   12865: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12866: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12867: 		untie(%bighash);
                   12868: 	    }
1.534     albertel 12869: 	}
                   12870: 	$title=~s/\&colon\;/\:/gs;
                   12871: 	if ($title) {
1.1159    www      12872: # Remember both $symb and $title for dynamic metadata
                   12873:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12874:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12875: # Cache this title and then return it
1.599     albertel 12876: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12877: 	}
                   12878: 	$urlsymb=$url;
                   12879:     }
                   12880:     my $title=&metadata($urlsymb,'title');
                   12881:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12882:     return $title;
1.301     www      12883: }
1.613     albertel 12884: 
1.614     albertel 12885: sub get_slot {
                   12886:     my ($which,$cnum,$cdom)=@_;
                   12887:     if (!$cnum || !$cdom) {
1.790     albertel 12888: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12889: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12890: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12891:     }
1.703     albertel 12892:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12893:     my %slotinfo;
                   12894:     if (exists($remembered{$key})) {
                   12895: 	$slotinfo{$which} = $remembered{$key};
                   12896:     } else {
                   12897: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12898: 	&Apache::lonhomework::showhash(%slotinfo);
                   12899: 	my ($tmp)=keys(%slotinfo);
                   12900: 	if ($tmp=~/^error:/) { return (); }
                   12901: 	$remembered{$key} = $slotinfo{$which};
                   12902:     }
1.616     albertel 12903:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12904: 	return %{$slotinfo{$which}};
                   12905:     }
                   12906:     return $slotinfo{$which};
1.614     albertel 12907: }
1.1150    raeburn  12908: 
                   12909: sub get_reservable_slots {
                   12910:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12911:     my $now = time;
                   12912:     my $reservable_info;
                   12913:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12914:     if (exists($remembered{$key})) {
                   12915:         $reservable_info = $remembered{$key};
                   12916:     } else {
                   12917:         my %resv;
                   12918:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12919:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12920:         $reservable_info = \%resv;
                   12921:         $remembered{$key} = $reservable_info;
                   12922:     }
                   12923:     return $reservable_info;
                   12924: }
                   12925: 
                   12926: sub get_course_slots {
                   12927:     my ($cnum,$cdom) = @_;
                   12928:     my $hashid=$cnum.':'.$cdom;
                   12929:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12930:     if (defined($cached)) {
                   12931:         if (ref($result) eq 'HASH') {
                   12932:             return %{$result};
                   12933:         }
                   12934:     } else {
                   12935:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12936:         my ($tmp) = keys(%slots);
                   12937:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12938:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12939:             return %slots;
                   12940:         }
                   12941:     }
                   12942:     return;
                   12943: }
                   12944: 
                   12945: sub devalidate_slots_cache {
                   12946:     my ($cnum,$cdom)=@_;
                   12947:     my $hashid=$cnum.':'.$cdom;
                   12948:     &devalidate_cache_new('allslots',$hashid);
                   12949: }
                   12950: 
1.1172.2.8  raeburn  12951: sub get_coursechange {
                   12952:     my ($cdom,$cnum) = @_;
                   12953:     if ($cdom eq '' || $cnum eq '') {
                   12954:         return unless ($env{'request.course.id'});
                   12955:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12956:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12957:     }
                   12958:     my $hashid=$cdom.'_'.$cnum;
                   12959:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12960:     if ((defined($cached)) && ($change ne '')) {
                   12961:         return $change;
                   12962:     } else {
                   12963:         my %crshash;
                   12964:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12965:         if ($crshash{'internal.contentchange'} eq '') {
                   12966:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12967:             if ($change eq '') {
                   12968:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12969:                 $change = $crshash{'internal.created'};
                   12970:             }
                   12971:         } else {
                   12972:             $change = $crshash{'internal.contentchange'};
                   12973:         }
                   12974:         my $cachetime = 600;
                   12975:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12976:     }
                   12977:     return $change;
                   12978: }
                   12979: 
                   12980: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 12981:23):     my ($cdom,$cnum)=@_;
                   12982:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  12983:     &devalidate_cache_new('crschange',$hashid);
                   12984: }
                   12985: 
1.1172.2.146.  .9(raebu 12986:23): sub get_suppchange {
                   12987:23):     my ($cdom,$cnum) = @_;
                   12988:23):     if ($cdom eq '' || $cnum eq '') {
                   12989:23):         return unless ($env{'request.course.id'});
                   12990:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12991:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12992:23):     }
                   12993:23):     my $hashid=$cdom.'_'.$cnum;
                   12994:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   12995:23):     if ((defined($cached)) && ($change ne '')) {
                   12996:23):         return $change;
                   12997:23):     } else {
                   12998:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   12999:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13000:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13001:23):             if ($change eq '') {
                   13002:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13003:23):                 $change = $crshash{'internal.created'};
                   13004:23):             }
                   13005:23):         } else {
                   13006:23):             $change = $crshash{'internal.supplementalchange'};
                   13007:23):         }
                   13008:23):         my $cachetime = 600;
                   13009:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13010:23):     }
                   13011:23):     return $change;
                   13012:23): }
                   13013:23): 
                   13014:23): sub devalidate_suppchange_cache {
                   13015:23):     my ($cdom,$cnum)=@_;
                   13016:23):     my $hashid=$cdom.'_'.$cnum;
                   13017:23):     &devalidate_cache_new('suppchange',$hashid);
                   13018:23): }
                   13019:23): 
                   13020:23): sub update_supp_caches {
                   13021:23):     my ($cdom,$cnum) = @_;
                   13022:23):     my %servers = &internet_dom_servers($cdom);
                   13023:23):     my @ids=&current_machine_ids();
                   13024:23):     foreach my $server (keys(%servers)) {
                   13025:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13026:23):         my $hashid=$cnum.':'.$cdom;
                   13027:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13028:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13029:23):     }
                   13030:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13031:23):     &count_supptools($cnum,$cdom,1);
                   13032:23):     my $now = time;
                   13033:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13034:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13035:23):     }
                   13036:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13037:23):          $cdom,$cnum);
                   13038:23):     &Apache::lonnet::appenv(
                   13039:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13040:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13041:23): }
                   13042:23): 
1.31      www      13043: # ------------------------------------------------- Update symbolic store links
                   13044: 
                   13045: sub symblist {
                   13046:     my ($mapname,%newhash)=@_;
1.438     www      13047:     $mapname=&deversion(&declutter($mapname));
1.31      www      13048:     my %hash;
1.620     albertel 13049:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13050:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13051:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13052: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13053: 		next if ($url eq 'last_known'
                   13054: 			 && $env{'form.no_update_last_known'});
                   13055: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13056: 						    $newhash{$url}->[1],
                   13057: 						    $newhash{$url}->[0]);
1.191     harris41 13058:             }
1.31      www      13059:             if (untie(%hash)) {
                   13060: 		return 'ok';
                   13061:             }
                   13062:         }
                   13063:     }
                   13064:     return 'error';
1.212     www      13065: }
                   13066: 
                   13067: # --------------------------------------------------------------- Verify a symb
                   13068: 
                   13069: sub symbverify {
1.1172.2.11  raeburn  13070:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13071:     my $thisfn=$thisurl;
1.439     www      13072:     $thisfn=&declutter($thisfn);
1.215     www      13073: # direct jump to resource in page or to a sequence - will construct own symbs
                   13074:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13075: # check URL part
1.409     www      13076:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13077: 
1.431     www      13078:     unless ($url eq $thisfn) { return 0; }
1.213     www      13079: 
1.216     www      13080:     $symb=&symbclean($symb);
1.510     www      13081:     $thisurl=&deversion($thisurl);
1.439     www      13082:     $thisfn=&deversion($thisfn);
1.213     www      13083: 
                   13084:     my %bighash;
                   13085:     my $okay=0;
1.431     www      13086: 
1.620     albertel 13087:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13088:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13089:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13090:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13091:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13092:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13093:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13094:             }
                   13095:         }
                   13096:         my $ids;
1.1172.2.122  raeburn  13097:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13098:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13099:         } else {
                   13100:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13101:         }
1.1102    raeburn  13102:         unless ($ids) {
1.1172.2.13  raeburn  13103:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13104:             $ids=$bighash{$idkey};
1.216     www      13105:         }
                   13106:         if ($ids) {
                   13107: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13108:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13109:                 $symb =~ s/\?.+$//;
                   13110:             }
1.800     albertel 13111: 	    foreach my $id (split(/\,/,$ids)) {
                   13112: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13113:                if (
                   13114:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13115:    eq $symb) {
1.1172.2.11  raeburn  13116:                    if (ref($encstate)) {
                   13117:                        $$encstate = $bighash{'encrypted_'.$id};
                   13118:                    }
1.1172.2.13  raeburn  13119:                    if (($env{'request.role.adv'}) ||
                   13120:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13121:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13122:                        $okay=1;
                   13123:                        last;
                   13124:                    }
                   13125:                }
                   13126:            }
1.216     www      13127:         }
1.213     www      13128: 	untie(%bighash);
                   13129:     }
                   13130:     return $okay;
1.31      www      13131: }
                   13132: 
1.210     www      13133: # --------------------------------------------------------------- Clean-up symb
                   13134: 
                   13135: sub symbclean {
                   13136:     my $symb=shift;
1.568     albertel 13137:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13138: # remove version from map
                   13139:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13140: 
1.210     www      13141: # remove version from URL
                   13142:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13143: 
1.507     www      13144: # remove wrapper
                   13145: 
1.510     www      13146:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13147:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13148:     return $symb;
1.409     www      13149: }
                   13150: 
                   13151: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13152: 
                   13153: sub encode_symb {
                   13154:     my ($map,$resid,$url)=@_;
                   13155:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13156: }
1.409     www      13157: 
                   13158: sub decode_symb {
1.568     albertel 13159:     my $symb=shift;
                   13160:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13161:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13162:     return (&fixversion($map),$resid,&fixversion($url));
                   13163: }
                   13164: 
                   13165: sub fixversion {
                   13166:     my $fn=shift;
1.609     banghart 13167:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13168:     my %bighash;
                   13169:     my $uri=&clutter($fn);
1.620     albertel 13170:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13171: # is this cached?
1.599     albertel 13172:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13173:     if (defined($cached)) { return $result; }
                   13174: # unfortunately not cached, or expired
1.620     albertel 13175:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13176: 	    &GDBM_READER(),0640)) {
                   13177:  	if ($bighash{'version_'.$uri}) {
                   13178:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13179:  	    unless (($version eq 'mostrecent') || 
                   13180: 		    ($version==&getversion($uri))) {
1.440     www      13181:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13182:  	    }
                   13183:  	}
                   13184:  	untie %bighash;
1.413     www      13185:     }
1.599     albertel 13186:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13187: }
                   13188: 
                   13189: sub deversion {
                   13190:     my $url=shift;
                   13191:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13192:     return $url;
1.210     www      13193: }
                   13194: 
1.31      www      13195: # ------------------------------------------------------ Return symb list entry
                   13196: 
                   13197: sub symbread {
1.1172.2.126  raeburn  13198:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13199:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13200:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13201:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13202:         unless (ref($possibles) eq 'HASH') {
                   13203:             if ($ignorecachednull) {
                   13204:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13205:             } else {
                   13206:                 return $env{$cache_str};
                   13207:             }
1.1172.2.66  raeburn  13208:         }
                   13209:     }
1.242     www      13210: # no filename provided? try from environment
1.1172.2.54  raeburn  13211:     unless ($thisfn) {
1.620     albertel 13212:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13213:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13214:         }
                   13215:         $thisfn=$env{'request.filename'};
1.44      www      13216:     }
1.569     albertel 13217:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13218: # is that filename actually a symb? Verify, clean, and return
                   13219:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13220: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13221: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13222: 	}
1.242     www      13223:     }
1.44      www      13224:     $thisfn=declutter($thisfn);
1.31      www      13225:     my %hash;
1.37      www      13226:     my %bighash;
                   13227:     my $syval='';
1.620     albertel 13228:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13229:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13230:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13231:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13232:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13233:                 untie(%hash);
                   13234:             }
1.1172.2.128  raeburn  13235:             if ($syval && $checkforblock) {
                   13236:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13237:                 if (@blockers) {
                   13238:                     $syval='';
                   13239:                 }
                   13240:             }
1.37      www      13241:         }
                   13242: # ---------------------------------------------------------- There was an entry
                   13243:         if ($syval) {
1.601     albertel 13244: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13245: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13246: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13247: 		    #return $env{$cache_str}='';
1.601     albertel 13248: 		#}    
                   13249: 		#$syval.=$1;
                   13250: 	    #}
1.37      www      13251:         } else {
                   13252: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13253:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13254:                             &GDBM_READER(),0640)) {
1.37      www      13255: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13256:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13257:               unless ($ids) { 
                   13258:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13259:               }
                   13260:               unless ($ids) {
                   13261: # alias?
                   13262: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13263:               }
1.37      www      13264:               if ($ids) {
                   13265: # ------------------------------------------------------------------- Has ID(s)
                   13266:                  my @possibilities=split(/\,/,$ids);
1.39      www      13267:                  if ($#possibilities==0) {
                   13268: # ----------------------------------------------- There is only one possibility
1.37      www      13269: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13270: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13271: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13272:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13273:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13274:                              $possibles->{$syval} = 1;
                   13275:                          }
1.1172.2.66  raeburn  13276:                      }
                   13277:                      if ($checkforblock) {
1.1172.2.126  raeburn  13278:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13279:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13280:                              if (@blockers) {
                   13281:                                  $syval = '';
                   13282:                                  untie(%bighash);
                   13283:                                  return $env{$cache_str}='';
                   13284:                              }
1.1172.2.66  raeburn  13285:                          }
                   13286:                      }
                   13287:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13288: # ------------------------------------------ There is more than one possibility
                   13289:                      my $realpossible=0;
1.800     albertel 13290:                      foreach my $id (@possibilities) {
                   13291: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13292:                          my $canaccess;
                   13293:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13294:                              $canaccess = 1;
                   13295:                          } else {
                   13296:                              $canaccess = &allowed('bre',$file);
                   13297:                          }
                   13298:                          if ($canaccess) {
                   13299:          		     my ($mapid,$resid)=split(/\./,$id);
                   13300:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13301:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13302:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13303:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13304:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13305:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13306:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13307:                                      if (@blockers > 0) {
                   13308:                                          $syval = '';
                   13309:                                      } else {
1.1172.2.66  raeburn  13310:                                          $syval = $poss_syval;
                   13311:                                          $realpossible++;
                   13312:                                      }
                   13313:                                  } else {
                   13314:                                      $syval = $poss_syval;
                   13315:                                      $realpossible++;
                   13316:                                  }
1.1172.2.126  raeburn  13317:                                  if ($syval) {
                   13318:                                      if (ref($possibles) eq 'HASH') {
                   13319:                                          $possibles->{$syval} = 1;
                   13320:                                      }
                   13321:                                  }
1.1172.2.66  raeburn  13322:                              }
1.39      www      13323: 			 }
1.191     harris41 13324:                      }
1.39      www      13325: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13326:                  } else {
                   13327:                      $syval='';
1.37      www      13328:                  }
                   13329: 	      }
1.1172.2.66  raeburn  13330:               untie(%bighash);
1.481     raeburn  13331:            }
1.31      www      13332:         }
1.62      www      13333:         if ($syval) {
1.1172.2.128  raeburn  13334: 	    return $env{$cache_str}=$syval;
1.62      www      13335:         }
1.31      www      13336:     }
1.949     raeburn  13337:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13338:     return $env{$cache_str}='';
1.31      www      13339: }
                   13340: 
                   13341: # ---------------------------------------------------------- Return random seed
                   13342: 
1.32      www      13343: sub numval {
                   13344:     my $txt=shift;
                   13345:     $txt=~tr/A-J/0-9/;
                   13346:     $txt=~tr/a-j/0-9/;
                   13347:     $txt=~tr/K-T/0-9/;
                   13348:     $txt=~tr/k-t/0-9/;
                   13349:     $txt=~tr/U-Z/0-5/;
                   13350:     $txt=~tr/u-z/0-5/;
                   13351:     $txt=~s/\D//g;
1.564     albertel 13352:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13353:     return int($txt);
1.368     albertel 13354: }
                   13355: 
1.484     albertel 13356: sub numval2 {
                   13357:     my $txt=shift;
                   13358:     $txt=~tr/A-J/0-9/;
                   13359:     $txt=~tr/a-j/0-9/;
                   13360:     $txt=~tr/K-T/0-9/;
                   13361:     $txt=~tr/k-t/0-9/;
                   13362:     $txt=~tr/U-Z/0-5/;
                   13363:     $txt=~tr/u-z/0-5/;
                   13364:     $txt=~s/\D//g;
                   13365:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13366:     my $total;
                   13367:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13368:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13369:     return int($total);
                   13370: }
                   13371: 
1.575     albertel 13372: sub numval3 {
                   13373:     use integer;
                   13374:     my $txt=shift;
                   13375:     $txt=~tr/A-J/0-9/;
                   13376:     $txt=~tr/a-j/0-9/;
                   13377:     $txt=~tr/K-T/0-9/;
                   13378:     $txt=~tr/k-t/0-9/;
                   13379:     $txt=~tr/U-Z/0-5/;
                   13380:     $txt=~tr/u-z/0-5/;
                   13381:     $txt=~s/\D//g;
                   13382:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13383:     my $total;
                   13384:     foreach my $val (@txts) { $total+=$val; }
                   13385:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13386:     return $total;
                   13387: }
                   13388: 
1.675     albertel 13389: sub digest {
                   13390:     my ($data)=@_;
                   13391:     my $digest=&Digest::MD5::md5($data);
                   13392:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13393:     my ($e,$f);
                   13394:     {
                   13395:         use integer;
                   13396:         $e=($a+$b);
                   13397:         $f=($c+$d);
                   13398:         if ($_64bit) {
                   13399:             $e=(($e<<32)>>32);
                   13400:             $f=(($f<<32)>>32);
                   13401:         }
                   13402:     }
                   13403:     if (wantarray) {
                   13404: 	return ($e,$f);
                   13405:     } else {
                   13406: 	my $g;
                   13407: 	{
                   13408: 	    use integer;
                   13409: 	    $g=($e+$f);
                   13410: 	    if ($_64bit) {
                   13411: 		$g=(($g<<32)>>32);
                   13412: 	    }
                   13413: 	}
                   13414: 	return $g;
                   13415:     }
                   13416: }
                   13417: 
1.368     albertel 13418: sub latest_rnd_algorithm_id {
1.675     albertel 13419:     return '64bit5';
1.366     albertel 13420: }
1.32      www      13421: 
1.503     albertel 13422: sub get_rand_alg {
                   13423:     my ($courseid)=@_;
1.790     albertel 13424:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13425:     if ($courseid) {
1.620     albertel 13426: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13427:     }
                   13428:     return &latest_rnd_algorithm_id();
                   13429: }
                   13430: 
1.562     albertel 13431: sub validCODE {
                   13432:     my ($CODE)=@_;
                   13433:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13434:     return 0;
                   13435: }
                   13436: 
1.491     albertel 13437: sub getCODE {
1.620     albertel 13438:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13439:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13440: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13441: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13442: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13443:     }
                   13444:     return undef;
                   13445: }
1.1133    foxr     13446: #
                   13447: #  Determines the random seed for a specific context:
                   13448: #
                   13449: # parameters:
                   13450: #   symb      - in course context the symb for the seed.
                   13451: #   course_id - The course id of the form domain_coursenum.
                   13452: #   domain    - Domain for the user.
                   13453: #   course    - Course for the user.
                   13454: #   cenv      - environment of the course.
                   13455: #
                   13456: # NOTE:
                   13457: #   All parameters are picked out of the environment if missing
                   13458: #   or not defined.
                   13459: #   If a symb cannot be determined the current time is used instead.
                   13460: #
                   13461: #  For a given well defined symb, courside, domain, username,
                   13462: #  and course environment, the seed is reproducible.
                   13463: #
1.31      www      13464: sub rndseed {
1.1133    foxr     13465:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13466:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13467:     if (!defined($symb)) {
1.366     albertel 13468: 	unless ($symb=$wsymb) { return time; }
                   13469:     }
1.1146    foxr     13470:     if (!defined $courseid) { 
                   13471: 	$courseid=$wcourseid; 
                   13472:     }
                   13473:     if (!defined $domain) { $domain=$wdomain; }
                   13474:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13475: 
                   13476:     my $which;
                   13477:     if (defined($cenv->{'rndseed'})) {
                   13478: 	$which = $cenv->{'rndseed'};
                   13479:     } else {
                   13480: 	$which =&get_rand_alg($courseid);
                   13481:     }
1.491     albertel 13482:     if (defined(&getCODE())) {
1.675     albertel 13483: 	if ($which eq '64bit5') {
                   13484: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13485: 	} elsif ($which eq '64bit4') {
1.575     albertel 13486: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13487: 	} else {
                   13488: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13489: 	}
1.675     albertel 13490:     } elsif ($which eq '64bit5') {
                   13491: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13492:     } elsif ($which eq '64bit4') {
                   13493: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13494:     } elsif ($which eq '64bit3') {
                   13495: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13496:     } elsif ($which eq '64bit2') {
                   13497: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13498:     } elsif ($which eq '64bit') {
                   13499: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13500:     }
                   13501:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13502: }
                   13503: 
                   13504: sub rndseed_32bit {
                   13505:     my ($symb,$courseid,$domain,$username)=@_;
                   13506:     {
                   13507: 	use integer;
                   13508: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13509: 	my $symbseed=numval($symb) << 22;
                   13510: 	my $namechck=unpack("%32C*",$username) << 17;
                   13511: 	my $nameseed=numval($username) << 12;
                   13512: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13513: 	my $courseseed=unpack("%32C*",$courseid);
                   13514: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13515: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13516: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13517: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13518: 	return $num;
                   13519:     }
                   13520: }
                   13521: 
                   13522: sub rndseed_64bit {
                   13523:     my ($symb,$courseid,$domain,$username)=@_;
                   13524:     {
                   13525: 	use integer;
                   13526: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13527: 	my $symbseed=numval($symb) << 10;
                   13528: 	my $namechck=unpack("%32S*",$username);
                   13529: 	
                   13530: 	my $nameseed=numval($username) << 21;
                   13531: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13532: 	my $courseseed=unpack("%32S*",$courseid);
                   13533: 	
                   13534: 	my $num1=$symbchck+$symbseed+$namechck;
                   13535: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13536: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13537: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13538: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13539: 	return "$num1,$num2";
1.155     albertel 13540:     }
1.366     albertel 13541: }
                   13542: 
1.443     albertel 13543: sub rndseed_64bit2 {
                   13544:     my ($symb,$courseid,$domain,$username)=@_;
                   13545:     {
                   13546: 	use integer;
                   13547: 	# strings need to be an even # of cahracters long, it it is odd the
                   13548:         # last characters gets thrown away
                   13549: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13550: 	my $symbseed=numval($symb) << 10;
                   13551: 	my $namechck=unpack("%32S*",$username.' ');
                   13552: 	
                   13553: 	my $nameseed=numval($username) << 21;
1.501     albertel 13554: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13555: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13556: 	
                   13557: 	my $num1=$symbchck+$symbseed+$namechck;
                   13558: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13559: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13560: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13561: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13562: 	return "$num1,$num2";
                   13563:     }
                   13564: }
                   13565: 
                   13566: sub rndseed_64bit3 {
                   13567:     my ($symb,$courseid,$domain,$username)=@_;
                   13568:     {
                   13569: 	use integer;
                   13570: 	# strings need to be an even # of cahracters long, it it is odd the
                   13571:         # last characters gets thrown away
                   13572: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13573: 	my $symbseed=numval2($symb) << 10;
                   13574: 	my $namechck=unpack("%32S*",$username.' ');
                   13575: 	
                   13576: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13577: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13578: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13579: 	
                   13580: 	my $num1=$symbchck+$symbseed+$namechck;
                   13581: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13582: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13583: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13584: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13585: 	
1.503     albertel 13586: 	return "$num1:$num2";
1.443     albertel 13587:     }
                   13588: }
                   13589: 
1.575     albertel 13590: sub rndseed_64bit4 {
                   13591:     my ($symb,$courseid,$domain,$username)=@_;
                   13592:     {
                   13593: 	use integer;
                   13594: 	# strings need to be an even # of cahracters long, it it is odd the
                   13595:         # last characters gets thrown away
                   13596: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13597: 	my $symbseed=numval3($symb) << 10;
                   13598: 	my $namechck=unpack("%32S*",$username.' ');
                   13599: 	
                   13600: 	my $nameseed=numval3($username) << 21;
                   13601: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13602: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13603: 	
                   13604: 	my $num1=$symbchck+$symbseed+$namechck;
                   13605: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13606: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13607: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13608: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13609: 	
1.575     albertel 13610: 	return "$num1:$num2";
                   13611:     }
                   13612: }
                   13613: 
1.675     albertel 13614: sub rndseed_64bit5 {
                   13615:     my ($symb,$courseid,$domain,$username)=@_;
                   13616:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13617:     return "$num1:$num2";
                   13618: }
                   13619: 
1.366     albertel 13620: sub rndseed_CODE_64bit {
                   13621:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13622:     {
1.366     albertel 13623: 	use integer;
1.443     albertel 13624: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13625: 	my $symbseed=numval2($symb);
1.491     albertel 13626: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13627: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13628: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13629: 	my $num1=$symbseed+$CODEchck;
                   13630: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13631: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13632: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13633: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13634: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13635: 	return "$num1:$num2";
1.366     albertel 13636:     }
                   13637: }
                   13638: 
1.575     albertel 13639: sub rndseed_CODE_64bit4 {
                   13640:     my ($symb,$courseid,$domain,$username)=@_;
                   13641:     {
                   13642: 	use integer;
                   13643: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13644: 	my $symbseed=numval3($symb);
                   13645: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13646: 	my $CODEseed=numval3(&getCODE());
                   13647: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13648: 	my $num1=$symbseed+$CODEchck;
                   13649: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13650: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13651: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13652: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13653: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13654: 	return "$num1:$num2";
                   13655:     }
                   13656: }
                   13657: 
1.675     albertel 13658: sub rndseed_CODE_64bit5 {
                   13659:     my ($symb,$courseid,$domain,$username)=@_;
                   13660:     my $code = &getCODE();
                   13661:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13662:     return "$num1:$num2";
                   13663: }
                   13664: 
1.366     albertel 13665: sub setup_random_from_rndseed {
                   13666:     my ($rndseed)=@_;
1.503     albertel 13667:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13668: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13669:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13670:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13671:         } else {
                   13672:             &Math::Random::random_set_seed($num1,$num2);
                   13673:         }
1.366     albertel 13674:     } else {
                   13675: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13676:     }
1.36      albertel 13677: }
                   13678: 
1.474     albertel 13679: sub latest_receipt_algorithm_id {
1.835     albertel 13680:     return 'receipt3';
1.474     albertel 13681: }
                   13682: 
1.480     www      13683: sub recunique {
                   13684:     my $fucourseid=shift;
                   13685:     my $unique;
1.835     albertel 13686:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13687: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13688: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13689:     } else {
                   13690: 	$unique=$perlvar{'lonReceipt'};
                   13691:     }
                   13692:     return unpack("%32C*",$unique);
                   13693: }
                   13694: 
                   13695: sub recprefix {
                   13696:     my $fucourseid=shift;
                   13697:     my $prefix;
1.835     albertel 13698:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13699: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13700: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13701:     } else {
                   13702: 	$prefix=$perlvar{'lonHostID'};
                   13703:     }
                   13704:     return unpack("%32C*",$prefix);
                   13705: }
                   13706: 
1.76      www      13707: sub ireceipt {
1.474     albertel 13708:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13709: 
                   13710:     my $return =&recprefix($fucourseid).'-';
                   13711: 
                   13712:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13713: 	$env{'request.state'} eq 'construct') {
                   13714: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13715: 	return $return;
                   13716:     }
                   13717: 
1.76      www      13718:     my $cuname=unpack("%32C*",$funame);
                   13719:     my $cudom=unpack("%32C*",$fudom);
                   13720:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13721:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13722:     my $cunique=&recunique($fucourseid);
1.474     albertel 13723:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13724:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13725: 
1.790     albertel 13726: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13727: 			       
                   13728: 	$return.= ($cunique%$cuname+
                   13729: 		   $cunique%$cudom+
                   13730: 		   $cusymb%$cuname+
                   13731: 		   $cusymb%$cudom+
                   13732: 		   $cucourseid%$cuname+
                   13733: 		   $cucourseid%$cudom+
                   13734: 		   $cpart%$cuname+
                   13735: 		   $cpart%$cudom);
                   13736:     } else {
                   13737: 	$return.= ($cunique%$cuname+
                   13738: 		   $cunique%$cudom+
                   13739: 		   $cusymb%$cuname+
                   13740: 		   $cusymb%$cudom+
                   13741: 		   $cucourseid%$cuname+
                   13742: 		   $cucourseid%$cudom);
                   13743:     }
                   13744:     return $return;
1.76      www      13745: }
                   13746: 
                   13747: sub receipt {
1.474     albertel 13748:     my ($part)=@_;
1.790     albertel 13749:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13750:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13751: }
1.260     ng       13752: 
1.790     albertel 13753: sub whichuser {
                   13754:     my ($passedsymb)=@_;
                   13755:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13756:     if (defined($env{'form.grade_symb'})) {
                   13757: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13758: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13759: 	if (!$allowed &&
                   13760: 	    exists($env{'request.course.sec'}) &&
                   13761: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13762: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13763: 			      '/'.$env{'request.course.sec'});
                   13764: 	}
                   13765: 	if ($allowed) {
                   13766: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13767: 	    $courseid=$tmp_courseid;
                   13768: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13769: 	    ($name)=&get_env_multiple('form.grade_username');
                   13770: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13771: 	}
                   13772:     }
                   13773:     if (!$passedsymb) {
                   13774: 	$symb=&symbread();
                   13775:     } else {
                   13776: 	$symb=$passedsymb;
                   13777:     }
                   13778:     $courseid=$env{'request.course.id'};
                   13779:     $domain=$env{'user.domain'};
                   13780:     $name=$env{'user.name'};
                   13781:     if ($name eq 'public' && $domain eq 'public') {
                   13782: 	if (!defined($env{'form.username'})) {
                   13783: 	    $env{'form.username'}.=time.rand(10000000);
                   13784: 	}
                   13785: 	$name.=$env{'form.username'};
                   13786:     }
                   13787:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13788: 
                   13789: }
                   13790: 
1.36      albertel 13791: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13792: # returns either the contents of the file or 
                   13793: # -1 if the file doesn't exist
1.481     raeburn  13794: #
                   13795: # if the target is a file that was uploaded via DOCS, 
                   13796: # a check will be made to see if a current copy exists on the local server,
                   13797: # if it does this will be served, otherwise a copy will be retrieved from
                   13798: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13799: # the local server.   
1.472     albertel 13800: 
1.36      albertel 13801: sub getfile {
1.538     albertel 13802:     my ($file) = @_;
1.609     banghart 13803:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13804:     &repcopy($file);
                   13805:     return &readfile($file);
                   13806: }
                   13807: 
                   13808: sub repcopy_userfile {
                   13809:     my ($file)=@_;
1.1142    raeburn  13810:     my $londocroot = $perlvar{'lonDocRoot'};
                   13811:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13812:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13813:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13814: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13815:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13816:     if (-e "$file") {
1.828     www      13817: # we already have a local copy, check it out
1.538     albertel 13818: 	my @fileinfo = stat($file);
1.828     www      13819: 	my $rtncode;
                   13820: 	my $info;
1.538     albertel 13821: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13822: 	if ($lwpresp ne 'ok') {
1.828     www      13823: # there is no such file anymore, even though we had a local copy
1.482     albertel 13824: 	    if ($rtncode eq '404') {
1.538     albertel 13825: 		unlink($file);
1.482     albertel 13826: 	    }
                   13827: 	    return -1;
                   13828: 	}
                   13829: 	if ($info < $fileinfo[9]) {
1.828     www      13830: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13831: 	    return 'ok';
1.828     www      13832: 	} else {
                   13833: # the file is outdated, get rid of it
                   13834: 	    unlink($file);
1.482     albertel 13835: 	}
1.828     www      13836:     }
                   13837: # one way or the other, at this point, we don't have the file
                   13838: # construct the correct path for the file
                   13839:     my @parts = ($cdom,$cnum); 
                   13840:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13841: 	push @parts, split(/\//,$1);
                   13842:     }
                   13843:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13844:     foreach my $part (@parts) {
                   13845: 	$path .= '/'.$part;
                   13846: 	if (!-e $path) {
                   13847: 	    mkdir($path,0770);
1.482     albertel 13848: 	}
                   13849:     }
1.828     www      13850: # now the path exists for sure
                   13851: # get a user agent
                   13852:     my $ua=new LWP::UserAgent;
                   13853:     my $transferfile=$file.'.in.transfer';
                   13854: # FIXME: this should flock
                   13855:     if (-e $transferfile) { return 'ok'; }
                   13856:     my $request;
                   13857:     $uri=~s/^\///;
1.980     raeburn  13858:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13859:     my $hostname = &hostname($homeserver);
1.980     raeburn  13860:     my $protocol = $protocol{$homeserver};
                   13861:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13862:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13863:     my $response=$ua->request($request,$transferfile);
                   13864: # did it work?
                   13865:     if ($response->is_error()) {
                   13866: 	unlink($transferfile);
                   13867: 	&logthis("Userfile repcopy failed for $uri");
                   13868: 	return -1;
                   13869:     }
                   13870: # worked, rename the transfer file
                   13871:     rename($transferfile,$file);
1.607     raeburn  13872:     return 'ok';
1.481     raeburn  13873: }
                   13874: 
1.517     albertel 13875: sub tokenwrapper {
                   13876:     my $uri=shift;
1.980     raeburn  13877:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13878:     $uri=~s|^/||;
1.620     albertel 13879:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13880:     my $token=$1;
1.552     albertel 13881:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13882:     if ($udom && $uname && $file) {
                   13883: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13884:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13885:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13886:         my $hostname = &hostname($homeserver);
1.980     raeburn  13887:         my $protocol = $protocol{$homeserver};
                   13888:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13889:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13890:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13891:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13892:     } else {
                   13893:         return '/adm/notfound.html';
                   13894:     }
                   13895: }
                   13896: 
1.828     www      13897: # call with reqtype HEAD: get last modification time
                   13898: # call with reqtype GET: get the file contents
                   13899: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13900: #
1.481     raeburn  13901: sub getuploaded {
                   13902:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13903:     $uri=~s/^\///;
1.980     raeburn  13904:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13905:     my $hostname = &hostname($homeserver);
1.980     raeburn  13906:     my $protocol = $protocol{$homeserver};
                   13907:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13908:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13909:     my $ua=new LWP::UserAgent;
                   13910:     my $request=new HTTP::Request($reqtype,$uri);
                   13911:     my $response=$ua->request($request);
                   13912:     $$rtncode = $response->code;
1.482     albertel 13913:     if (! $response->is_success()) {
                   13914: 	return 'failed';
                   13915:     }      
                   13916:     if ($reqtype eq 'HEAD') {
1.486     www      13917: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13918:     } elsif ($reqtype eq 'GET') {
                   13919: 	$$info = $response->content;
1.472     albertel 13920:     }
1.482     albertel 13921:     return 'ok';
1.36      albertel 13922: }
                   13923: 
1.481     raeburn  13924: sub readfile {
                   13925:     my $file = shift;
                   13926:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13927:     my $fh;
1.1172.2.96  raeburn  13928:     open($fh,"<",$file);
1.481     raeburn  13929:     my $a='';
1.800     albertel 13930:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13931:     return $a;
                   13932: }
                   13933: 
1.36      albertel 13934: sub filelocation {
1.590     banghart 13935:     my ($dir,$file) = @_;
                   13936:     my $location;
                   13937:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13938: 
                   13939:     if ($file =~ m-^/adm/-) {
                   13940: 	$file=~s-^/adm/wrapper/-/-;
                   13941: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13942:     }
1.882     albertel 13943: 
1.1139    www      13944:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13945:         $location = $file;
1.609     banghart 13946:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13947:         my ($udom,$uname,$filename)=
1.811     albertel 13948:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13949:         my $home=&homeserver($uname,$udom);
                   13950:         my $is_me=0;
                   13951:         my @ids=&current_machine_ids();
                   13952:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13953:         if ($is_me) {
1.1117    foxr     13954:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13955:         } else {
                   13956:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13957:   	      $udom.'/'.$uname.'/'.$filename;
                   13958:         }
1.882     albertel 13959:     } elsif ($file =~ m-^/adm/-) {
                   13960: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13961:     } else {
                   13962:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13963:         $file=~s:^/(res|priv)/:/:;
                   13964:         my $space=$1;
1.590     banghart 13965:         if ( !( $file =~ m:^/:) ) {
                   13966:             $location = $dir. '/'.$file;
                   13967:         } else {
1.1142    raeburn  13968:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13969:         }
1.59      albertel 13970:     }
1.590     banghart 13971:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13972:     while ($location=~m{/\.\./}) {
                   13973: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13974: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13975: 	} else {
                   13976: 	    $location=~ s{/\.\./}{/}g;
                   13977: 	}
                   13978:     } #remove dir/..
1.590     banghart 13979:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13980:     return $location;
1.46      www      13981: }
1.36      albertel 13982: 
1.46      www      13983: sub hreflocation {
                   13984:     my ($dir,$file)=@_;
1.980     raeburn  13985:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13986: 	$file=filelocation($dir,$file);
1.700     albertel 13987:     } elsif ($file=~m-^/adm/-) {
                   13988: 	$file=~s-^/adm/wrapper/-/-;
                   13989: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13990:     }
                   13991:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13992: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13993:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13994: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13995: 	        {/uploaded/$1/$2/}x;
1.46      www      13996:     }
1.913     albertel 13997:     if ($file=~ m{^/userfiles/}) {
                   13998: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13999:     }
1.462     albertel 14000:     return $file;
1.465     albertel 14001: }
                   14002: 
1.1139    www      14003: 
                   14004: 
                   14005: 
                   14006: 
1.465     albertel 14007: sub current_machine_domains {
1.853     albertel 14008:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14009: }
                   14010: 
                   14011: sub machine_domains {
                   14012:     my ($hostname) = @_;
1.465     albertel 14013:     my @domains;
1.838     albertel 14014:     my %hostname = &all_hostnames();
1.465     albertel 14015:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14016: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14017: 	if ($hostname eq $name) {
1.844     albertel 14018: 	    push(@domains,&host_domain($id));
1.465     albertel 14019: 	}
                   14020:     }
                   14021:     return @domains;
                   14022: }
                   14023: 
                   14024: sub current_machine_ids {
1.853     albertel 14025:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14026: }
                   14027: 
                   14028: sub machine_ids {
                   14029:     my ($hostname) = @_;
                   14030:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14031:     my @ids;
1.888     albertel 14032:     my %name_to_host = &all_names();
1.889     albertel 14033:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14034: 	return @{ $name_to_host{$hostname} };
                   14035:     }
                   14036:     return;
1.31      www      14037: }
                   14038: 
1.824     raeburn  14039: sub additional_machine_domains {
                   14040:     my @domains;
1.1172.2.142  raeburn  14041:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14042:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14043:             while( my $line = <$fh>) {
                   14044:                 chomp($line);
                   14045:                 $line =~ s/\s//g;
                   14046:                 push(@domains,$line);
                   14047:             }
                   14048:             close($fh);
                   14049:         }
1.824     raeburn  14050:     }
                   14051:     return @domains;
                   14052: }
                   14053: 
                   14054: sub default_login_domain {
                   14055:     my $domain = $perlvar{'lonDefDomain'};
                   14056:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14057:     foreach my $posdom (&current_machine_domains(),
                   14058:                         &additional_machine_domains()) {
                   14059:         if (lc($posdom) eq lc($testdomain)) {
                   14060:             $domain=$posdom;
                   14061:             last;
                   14062:         }
                   14063:     }
                   14064:     return $domain;
                   14065: }
                   14066: 
1.1172.2.106  raeburn  14067: sub shared_institution {
1.1172.2.136  raeburn  14068:     my ($dom,$lonhost) = @_;
                   14069:     if ($lonhost eq '') {
                   14070:         $lonhost = $perlvar{'lonHostID'};
                   14071:     }
1.1172.2.106  raeburn  14072:     my $same_intdom;
1.1172.2.136  raeburn  14073:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14074:     if ($hostintdom ne '') {
                   14075:         my %iphost = &get_iphost();
                   14076:         my $primary_id = &domain($dom,'primary');
                   14077:         my $primary_ip = &get_host_ip($primary_id);
                   14078:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14079:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14080:                 my $intdom = &internet_dom($id);
                   14081:                 if ($intdom eq $hostintdom) {
                   14082:                     $same_intdom = 1;
                   14083:                     last;
                   14084:                 }
                   14085:             }
                   14086:         }
                   14087:     }
                   14088:     return $same_intdom;
                   14089: }
                   14090: 
1.1172.2.120  raeburn  14091: sub uses_sts {
                   14092:     my ($ignore_cache) = @_;
                   14093:     my $lonhost = $perlvar{'lonHostID'};
                   14094:     my $hostname = &hostname($lonhost);
                   14095:     my $sts_on;
                   14096:     if ($protocol{$lonhost} eq 'https') {
                   14097:         my $cachetime = 12*3600;
                   14098:         if (!$ignore_cache) {
                   14099:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14100:             if (defined($cached)) {
                   14101:                 return $sts_on;
                   14102:             }
                   14103:         }
1.1172.2.121  raeburn  14104:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14105:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14106:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14107:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14108:         if ($response->is_success) {
                   14109:             my $has_sts = $response->header('Strict-Transport-Security');
                   14110:             if ($has_sts eq '') {
                   14111:                 $sts_on = 0;
                   14112:             } else {
                   14113:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14114:                     my $maxage = $1;
                   14115:                     if ($maxage) {
                   14116:                         $sts_on = 1;
                   14117:                     } else {
                   14118:                         $sts_on = 0;
                   14119:                     }
                   14120:                 } else {
                   14121:                     $sts_on = 0;
                   14122:                 }
                   14123:             }
                   14124:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14125:         }
                   14126:     }
                   14127:     return;
                   14128: }
                   14129: 
1.1172.2.142  raeburn  14130: sub waf_allssl {
                   14131:     my ($host_name) = @_;
                   14132:     my $alias = &get_proxy_alias();
                   14133:     if ($host_name eq '') {
                   14134:         $host_name = $ENV{'SERVER_NAME'};
                   14135:     }
                   14136:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14137:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14138:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14139:         if ($defdomdefaults{'waf_sslopt'}) {
                   14140:             return $defdomdefaults{'waf_sslopt'};
                   14141:         }
                   14142:     }
                   14143:     return;
                   14144: }
                   14145: 
1.1172.2.134  raeburn  14146: sub get_requestor_ip {
                   14147:     my ($r,$nolookup,$noproxy) = @_;
                   14148:     my $from_ip;
                   14149:     if (ref($r)) {
1.1172.2.142  raeburn  14150:         if ($r->can('useragent_ip')) {
                   14151:             if ($noproxy && $r->can('client_ip')) {
                   14152:                 $from_ip = $r->client_ip();
                   14153:             } else {
                   14154:                 $from_ip = $r->useragent_ip();
                   14155:             }
                   14156:         } elsif ($r->connection->can('remote_ip')) {
                   14157:             $from_ip = $r->connection->remote_ip();
                   14158:         } else {
                   14159:             $from_ip = $r->get_remote_host($nolookup);
                   14160:         }
1.1172.2.134  raeburn  14161:     } else {
                   14162:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14163:     }
1.1172.2.142  raeburn  14164:     return $from_ip if ($noproxy);
                   14165:    # Who controls proxy settings for server
                   14166:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14167:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14168:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14169:         if ($proxyinfo->{'vpnint'}) {
                   14170:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14171:                 return $from_ip;
                   14172:             }
                   14173:         }
                   14174:         if ($proxyinfo->{'trusted'}) {
                   14175:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14176:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14177:                 my ($ip,$xfor);
                   14178:                 if (ref($r)) {
                   14179:                     if ($ipheader) {
                   14180:                         $ip = $r->headers_in->{$ipheader};
                   14181:                     }
                   14182:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14183:                 } else {
                   14184:                     if ($ipheader) {
                   14185:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14186:                     }
                   14187:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14188:                 }
                   14189:                 if (($ip eq '') && ($xfor ne '')) {
                   14190:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14191:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14192:                             $ip = $poss_ip;
                   14193:                             last;
                   14194:                         }
                   14195:                     }
                   14196:                 }
                   14197:                 if ($ip ne '') {
                   14198:                     return $ip;
                   14199:                 }
                   14200:             }
                   14201:         }
                   14202:     }
1.1172.2.134  raeburn  14203:     return $from_ip;
                   14204: }
                   14205: 
1.1172.2.142  raeburn  14206: sub get_proxy_settings {
                   14207:     my ($dom_in_use) = @_;
                   14208:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14209:     my $proxyinfo = {
                   14210:                        ipheader => $domdefaults{'waf_ipheader'},
                   14211:                        trusted  => $domdefaults{'waf_trusted'},
                   14212:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14213:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14214:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14215:                     };
                   14216:     return $proxyinfo;
                   14217: }
                   14218: 
                   14219: sub ip_match {
                   14220:     my ($ip,$pattern_str) = @_;
                   14221:     $ip=Net::CIDR::cidrvalidate($ip);
                   14222:     if ($ip) {
                   14223:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14224:     }
                   14225:     return;
                   14226: }
                   14227: 
                   14228: sub get_proxy_alias {
                   14229:     my ($lonid) = @_;
                   14230:     if ($lonid eq '') {
                   14231:         $lonid = $perlvar{'lonHostID'};
                   14232:     }
                   14233:     if (!defined(&hostname($lonid))) {
                   14234:         return;
                   14235:     }
                   14236:     if ($lonid ne '') {
                   14237:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14238:         if ($cached) {
                   14239:             return $alias;
                   14240:         }
                   14241:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14242:         if ($dom ne '') {
                   14243:             my $cachetime = 60*60*24;
                   14244:             my %domconfig =
                   14245:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14246:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14247:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14248:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14249:                 }
                   14250:             }
                   14251:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14252:         }
                   14253:     }
                   14254:     return;
                   14255: }
                   14256: 
                   14257: sub use_proxy_alias {
                   14258:     my ($r,$lonid) = @_;
                   14259:     my $alias = &get_proxy_alias($lonid);
                   14260:     if ($alias) {
                   14261:         my $dom = &host_domain($lonid);
                   14262:         if ($dom ne '') {
                   14263:             my $proxyinfo = &get_proxy_settings($dom);
                   14264:             my ($vpnint,$remote_ip);
                   14265:             if (ref($proxyinfo) eq 'HASH') {
                   14266:                 $vpnint = $proxyinfo->{'vpnint'};
                   14267:                 if ($vpnint) {
                   14268:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14269:                 }
                   14270:             }
                   14271:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14272:                 return $alias;
                   14273:             }
                   14274:         }
                   14275:     }
                   14276:     return;
                   14277: }
                   14278: 
                   14279: sub alias_sso {
                   14280:     my ($lonid) = @_;
                   14281:     if ($lonid eq '') {
                   14282:         $lonid = $perlvar{'lonHostID'};
                   14283:     }
                   14284:     if (!defined(&hostname($lonid))) {
                   14285:         return;
                   14286:     }
                   14287:     if ($lonid ne '') {
                   14288:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14289:         if ($cached) {
                   14290:             return $use_alias;
                   14291:         }
                   14292:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14293:         if ($dom ne '') {
                   14294:             my $cachetime = 60*60*24;
                   14295:             my %domconfig =
                   14296:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14297:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14298:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14299:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14300:                 }
                   14301:             }
                   14302:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14303:         }
                   14304:     }
                   14305:     return;
                   14306: }
                   14307: 
                   14308: sub get_saml_landing {
                   14309:     my ($lonid) = @_;
                   14310:     if ($lonid eq '') {
                   14311:         my $defdom = &default_login_domain();
                   14312:         my @hosts = &current_machine_ids();
                   14313:         if (@hosts > 1) {
                   14314:             foreach my $hostid (@hosts) {
                   14315:                 if (&host_domain($hostid) eq $defdom) {
                   14316:                     $lonid = $hostid;
                   14317:                     last;
                   14318:                 }
                   14319:             }
                   14320:         } else {
                   14321:             $lonid = $perlvar{'lonHostID'};
                   14322:         }
                   14323:         if ($lonid) {
                   14324:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14325:                 return;
                   14326:             }
                   14327:         } else {
                   14328:             return;
                   14329:         }
                   14330:     } elsif (!defined(&hostname($lonid))) {
                   14331:         return;
                   14332:     }
                   14333:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14334:     if ($cached) {
                   14335:         return $landing;
                   14336:     }
                   14337:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14338:     if ($dom ne '') {
                   14339:         my $cachetime = 60*60*24;
                   14340:         my %domconfig =
                   14341:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14342:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14343:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14344:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14345:                     $landing = 1;
                   14346:                 }
                   14347:             }
                   14348:         }
                   14349:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14350:     }
                   14351:     return;
                   14352: }
                   14353: 
1.31      www      14354: # ------------------------------------------------------------- Declutters URLs
                   14355: 
                   14356: sub declutter {
                   14357:     my $thisfn=shift;
1.569     albertel 14358:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14359:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14360:         $thisfn=~s{^/home/httpd/html}{};
                   14361:     }
1.31      www      14362:     $thisfn=~s/^\///;
1.697     albertel 14363:     $thisfn=~s|^adm/wrapper/||;
                   14364:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14365:     $thisfn=~s/^res\///;
1.1172    bisitz   14366:     $thisfn=~s/^priv\///;
1.1032    raeburn  14367:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14368:         $thisfn=~s/\?.+$//;
                   14369:     }
1.268     www      14370:     return $thisfn;
                   14371: }
                   14372: 
                   14373: # ------------------------------------------------------------- Clutter up URLs
                   14374: 
                   14375: sub clutter {
                   14376:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14377:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14378: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14379:        $thisfn='/res'.$thisfn; 
                   14380:     }
1.1031    raeburn  14381:     if ($thisfn !~m|^/adm|) {
                   14382: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14383: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14384: 	} else {
                   14385: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14386: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14387: 	    if ($embstyle eq 'ssi'
                   14388: 		|| ($embstyle eq 'hdn')
                   14389: 		|| ($embstyle eq 'rat')
                   14390: 		|| ($embstyle eq 'prv')
                   14391: 		|| ($embstyle eq 'ign')) {
                   14392: 		#do nothing with these
                   14393: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14394: 		|| ($embstyle eq 'emb')
                   14395: 		|| ($embstyle eq 'wrp')) {
                   14396: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14397: 	    } elsif ($embstyle eq 'unk'
                   14398: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14399: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14400: 	    } else {
1.718     www      14401: #		&logthis("Got a blank emb style");
1.695     albertel 14402: 	    }
1.694     albertel 14403: 	}
1.1172.2.146.  .1(raebu 14404:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14405:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14406:     }
1.31      www      14407:     return $thisfn;
1.12      www      14408: }
                   14409: 
1.787     albertel 14410: sub clutter_with_no_wrapper {
                   14411:     my $uri = &clutter(shift);
                   14412:     if ($uri =~ m-^/adm/-) {
                   14413: 	$uri =~ s-^/adm/wrapper/-/-;
                   14414: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14415:     }
                   14416:     return $uri;
                   14417: }
                   14418: 
1.557     albertel 14419: sub freeze_escape {
                   14420:     my ($value)=@_;
                   14421:     if (ref($value)) {
                   14422: 	$value=&nfreeze($value);
                   14423: 	return '__FROZEN__'.&escape($value);
                   14424:     }
                   14425:     return &escape($value);
                   14426: }
                   14427: 
1.11      www      14428: 
1.557     albertel 14429: sub thaw_unescape {
                   14430:     my ($value)=@_;
                   14431:     if ($value =~ /^__FROZEN__/) {
                   14432: 	substr($value,0,10,undef);
                   14433: 	$value=&unescape($value);
                   14434: 	return &thaw($value);
                   14435:     }
                   14436:     return &unescape($value);
                   14437: }
                   14438: 
1.436     albertel 14439: sub correct_line_ends {
                   14440:     my ($result)=@_;
                   14441:     $$result =~s/\r\n/\n/mg;
                   14442:     $$result =~s/\r/\n/mg;
1.415     albertel 14443: }
1.1       albertel 14444: # ================================================================ Main Program
                   14445: 
1.184     www      14446: sub goodbye {
1.204     albertel 14447:    &logthis("Starting Shut down");
1.443     albertel 14448: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14449:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14450: #converted
1.599     albertel 14451: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14452:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14453: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14454: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14455: #1.1 only
1.870     albertel 14456: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14457: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14458: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14459: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14460:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14461:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14462:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14463:    &flushcourselogs();
                   14464:    &logthis("Shutting down");
                   14465: }
                   14466: 
1.852     albertel 14467: sub get_dns {
1.1172.2.17  raeburn  14468:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14469:     if (!$ignore_cache) {
                   14470: 	my ($content,$cached)=
                   14471: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14472: 	if ($cached) {
1.1172.2.17  raeburn  14473: 	    &$func($content,$hashref);
1.869     albertel 14474: 	    return;
                   14475: 	}
                   14476:     }
                   14477: 
                   14478:     my %alldns;
1.1172.2.96  raeburn  14479:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14480:         foreach my $dns (<$config>) {
                   14481: 	    next if ($dns !~ /^\^(\S*)/x);
                   14482:             my $line = $1;
                   14483:             my ($host,$protocol) = split(/:/,$line);
                   14484:             if ($protocol ne 'https') {
                   14485:                 $protocol = 'http';
                   14486:             }
                   14487: 	    $alldns{$host} = $protocol;
1.979     raeburn  14488:         }
1.1172.2.96  raeburn  14489:         close($config);
1.869     albertel 14490:     }
                   14491:     while (%alldns) {
1.1172.2.52  raeburn  14492: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14493:         my @content;
                   14494:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14495:             my $command = (split('/',$url))[3];
                   14496:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14497:             delete($alldns{$dns});
                   14498:             next if (($dir eq '') || ($file eq ''));
                   14499:             if (open(my $config,'<',"$dir/$file")) {
                   14500:                 @content = <$config>;
                   14501:                 close($config);
                   14502:             }
                   14503:         } else {
                   14504: 	    my $ua=new LWP::UserAgent;
                   14505:             $ua->timeout(30);
                   14506: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14507: 	    my $response=$ua->request($request);
                   14508:             delete($alldns{$dns});
                   14509: 	    next if ($response->is_error());
                   14510: 	    @content = split("\n",$response->content);
                   14511:         }
1.1172.2.17  raeburn  14512:         unless ($nocache) {
1.1172.2.23  raeburn  14513: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14514:         }
                   14515: 	&$func(\@content,$hashref);
1.869     albertel 14516: 	return;
1.852     albertel 14517:     }
1.871     albertel 14518:     my $which = (split('/',$url))[3];
                   14519:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14520:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14521:         my @content = <$config>;
                   14522:         &$func(\@content,$hashref);
                   14523:     }
1.1172.2.17  raeburn  14524:     return;
                   14525: }
                   14526: 
                   14527: # ------------------------------------------------------Get DNS checksums file
                   14528: sub parse_dns_checksums_tab {
                   14529:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14530:     my $lonhost = $perlvar{'lonHostID'};
                   14531:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14532:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14533:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14534:     my $webconfdir = '/etc/httpd/conf';
                   14535:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14536:         $webconfdir = '/etc/apache2';
                   14537:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14538:         if ($1 >= 10) {
                   14539:             $webconfdir = '/etc/apache2';
                   14540:         }
                   14541:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14542:         if ($1 >= 10.0) {
                   14543:             $webconfdir = '/etc/apache2';
                   14544:         }
                   14545:     }
1.1172.2.17  raeburn  14546:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14547:     my (%chksum,%revnum);
                   14548:     if (ref($lines) eq 'ARRAY') {
                   14549:         chomp(@{$lines});
1.1172.2.34  raeburn  14550:         my $version = shift(@{$lines});
                   14551:         if ($version eq $release) {
1.1172.2.17  raeburn  14552:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14553:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14554:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14555:                     if ($webconfdir eq '/etc/apache2') {
                   14556:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14557:                     }
                   14558:                 }
1.1172.2.34  raeburn  14559:                 $chksum{$file} = $shasum;
                   14560:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14561:             }
                   14562:             if (ref($hashref) eq 'HASH') {
                   14563:                 %{$hashref} = (
                   14564:                                 sums     => \%chksum,
                   14565:                                 versions => \%revnum,
                   14566:                               );
                   14567:             }
                   14568:         }
                   14569:     }
1.869     albertel 14570:     return;
1.852     albertel 14571: }
1.1172.2.17  raeburn  14572: 
                   14573: sub fetch_dns_checksums {
                   14574:     my %checksums;
1.1172.2.34  raeburn  14575:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14576:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14577:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14578:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14579:              \%checksums);
                   14580:     return \%checksums;
                   14581: }
                   14582: 
1.1172.2.142  raeburn  14583: sub parse_getdns_url {
                   14584:     my ($command,$url) = @_;
                   14585:     my $dir = $perlvar{'lonTabDir'};
                   14586:     my $file;
                   14587:     if ($command eq 'hosts') {
                   14588:         $file = 'dns_hosts.tab';
                   14589:     } elsif ($command eq 'domain') {
                   14590:         $file = 'dns_domain.tab';
                   14591:     } elsif ($command eq 'checksums') {
                   14592:         my $version = (split('/',$url))[4];
                   14593:         $file = "dns_checksums/$version.tab",
                   14594:     }
                   14595:     return ($dir,$file);
                   14596: }
                   14597: 
1.327     albertel 14598: # ------------------------------------------------------------ Read domain file
                   14599: {
1.852     albertel 14600:     my $loaded;
1.846     albertel 14601:     my %domain;
                   14602: 
1.852     albertel 14603:     sub parse_domain_tab {
                   14604: 	my ($lines) = @_;
                   14605: 	foreach my $line (@$lines) {
                   14606: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14607: 
1.846     albertel 14608: 	    chomp($line);
1.852     albertel 14609: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14610: 	    my %this_domain;
                   14611: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14612: 			       'lang_def', 'city', 'longi', 'lati',
                   14613: 			       'primary') {
                   14614: 		$this_domain{$field} = shift(@elements);
                   14615: 	    }
                   14616: 	    $domain{$name} = \%this_domain;
1.852     albertel 14617: 	}
                   14618:     }
1.864     albertel 14619: 
                   14620:     sub reset_domain_info {
                   14621: 	undef($loaded);
                   14622: 	undef(%domain);
                   14623:     }
                   14624: 
1.852     albertel 14625:     sub load_domain_tab {
1.1172.2.70  raeburn  14626: 	my ($ignore_cache,$nocache) = @_;
                   14627: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14628: 	my $fh;
1.1172.2.96  raeburn  14629: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14630: 	    my @lines = <$fh>;
                   14631: 	    &parse_domain_tab(\@lines);
1.448     albertel 14632: 	}
1.852     albertel 14633: 	close($fh);
                   14634: 	$loaded = 1;
1.327     albertel 14635:     }
1.846     albertel 14636: 
                   14637:     sub domain {
1.852     albertel 14638: 	&load_domain_tab() if (!$loaded);
                   14639: 
1.846     albertel 14640: 	my ($name,$what) = @_;
                   14641: 	return if ( !exists($domain{$name}) );
                   14642: 
                   14643: 	if (!$what) {
                   14644: 	    return $domain{$name}{'description'};
                   14645: 	}
                   14646: 	return $domain{$name}{$what};
                   14647:     }
1.974     raeburn  14648: 
                   14649:     sub domain_info {
                   14650:         &load_domain_tab() if (!$loaded);
                   14651:         return %domain;
                   14652:     }
                   14653: 
1.327     albertel 14654: }
                   14655: 
                   14656: 
1.1       albertel 14657: # ------------------------------------------------------------- Read hosts file
                   14658: {
1.838     albertel 14659:     my %hostname;
1.844     albertel 14660:     my %hostdom;
1.845     albertel 14661:     my %libserv;
1.852     albertel 14662:     my $loaded;
1.888     albertel 14663:     my %name_to_host;
1.1074    raeburn  14664:     my %internetdom;
1.1107    raeburn  14665:     my %LC_dns_serv;
1.852     albertel 14666: 
                   14667:     sub parse_hosts_tab {
                   14668: 	my ($file) = @_;
                   14669: 	foreach my $configline (@$file) {
                   14670: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14671:             chomp($configline);
                   14672: 	    if ($configline =~ /^\^/) {
                   14673:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14674:                     $LC_dns_serv{$1} = 1;
                   14675:                 }
                   14676:                 next;
                   14677:             }
1.1074    raeburn  14678: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14679: 	    $name=~s/\s//g;
                   14680: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14681:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14682:                     my $curr = $hostname{$id};
                   14683:                     my $skip;
                   14684:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14685:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14686:                             $skip = 1;
                   14687:                         } else {
                   14688:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14689:                         }
                   14690:                     }
                   14691:                     unless ($skip) {
                   14692:                         push(@{$name_to_host{$name}},$id);
                   14693:                     }
                   14694:                 } else {
                   14695:                     push(@{$name_to_host{$name}},$id);
                   14696:                 }
1.852     albertel 14697: 		$hostname{$id}=$name;
                   14698: 		$hostdom{$id}=$domain;
                   14699: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14700:                 if (defined($protocol)) {
                   14701:                     if ($protocol eq 'https') {
                   14702:                         $protocol{$id} = $protocol;
                   14703:                     } else {
                   14704:                         $protocol{$id} = 'http'; 
                   14705:                     }
1.968     raeburn  14706:                 } else {
1.969     raeburn  14707:                     $protocol{$id} = 'http';
1.968     raeburn  14708:                 }
1.1074    raeburn  14709:                 if (defined($intdom)) {
                   14710:                     $internetdom{$id} = $intdom;
                   14711:                 }
1.852     albertel 14712: 	    }
                   14713: 	}
                   14714:     }
1.864     albertel 14715:     
                   14716:     sub reset_hosts_info {
1.897     albertel 14717: 	&purge_remembered();
1.864     albertel 14718: 	&reset_domain_info();
                   14719: 	&reset_hosts_ip_info();
1.892     albertel 14720: 	undef(%name_to_host);
1.864     albertel 14721: 	undef(%hostname);
                   14722: 	undef(%hostdom);
                   14723: 	undef(%libserv);
                   14724: 	undef($loaded);
                   14725:     }
1.1       albertel 14726: 
1.852     albertel 14727:     sub load_hosts_tab {
1.1172.2.70  raeburn  14728: 	my ($ignore_cache,$nocache) = @_;
                   14729: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14730: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14731: 	my @config = <$config>;
                   14732: 	&parse_hosts_tab(\@config);
                   14733: 	close($config);
                   14734: 	$loaded=1;
1.1       albertel 14735:     }
1.852     albertel 14736: 
1.838     albertel 14737:     sub hostname {
1.852     albertel 14738: 	&load_hosts_tab() if (!$loaded);
                   14739: 
1.838     albertel 14740: 	my ($lonid) = @_;
                   14741: 	return $hostname{$lonid};
                   14742:     }
1.845     albertel 14743: 
1.838     albertel 14744:     sub all_hostnames {
1.852     albertel 14745: 	&load_hosts_tab() if (!$loaded);
                   14746: 
1.838     albertel 14747: 	return %hostname;
                   14748:     }
1.845     albertel 14749: 
1.888     albertel 14750:     sub all_names {
1.1172.2.70  raeburn  14751:         my ($ignore_cache,$nocache) = @_;
                   14752: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14753: 
                   14754: 	return %name_to_host;
                   14755:     }
                   14756: 
1.974     raeburn  14757:     sub all_host_domain {
                   14758:         &load_hosts_tab() if (!$loaded);
                   14759:         return %hostdom;
                   14760:     }
                   14761: 
1.845     albertel 14762:     sub is_library {
1.852     albertel 14763: 	&load_hosts_tab() if (!$loaded);
                   14764: 
1.845     albertel 14765: 	return exists($libserv{$_[0]});
                   14766:     }
                   14767: 
                   14768:     sub all_library {
1.852     albertel 14769: 	&load_hosts_tab() if (!$loaded);
                   14770: 
1.845     albertel 14771: 	return %libserv;
                   14772:     }
                   14773: 
1.1062    droeschl 14774:     sub unique_library {
                   14775: 	#2x reverse removes all hostnames that appear more than once
                   14776:         my %unique = reverse &all_library();
                   14777:         return reverse %unique;
                   14778:     }
                   14779: 
1.841     albertel 14780:     sub get_servers {
1.852     albertel 14781: 	&load_hosts_tab() if (!$loaded);
                   14782: 
1.841     albertel 14783: 	my ($domain,$type) = @_;
                   14784: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14785: 	                                          : %hostname;
                   14786: 	my %result;
1.842     albertel 14787: 	if (ref($domain) eq 'ARRAY') {
                   14788: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14789: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14790: 		    $result{$host} = $hostname;
                   14791: 		}
                   14792: 	    }
                   14793: 	} else {
                   14794: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14795: 		if ($hostdom{$host} eq $domain) {
                   14796: 		    $result{$host} = $hostname;
                   14797: 		}
1.841     albertel 14798: 	    }
                   14799: 	}
                   14800: 	return %result;
                   14801:     }
1.845     albertel 14802: 
1.1062    droeschl 14803:     sub get_unique_servers {
                   14804:         my %unique = reverse &get_servers(@_);
                   14805: 	return reverse %unique;
                   14806:     }
                   14807: 
1.844     albertel 14808:     sub host_domain {
1.852     albertel 14809: 	&load_hosts_tab() if (!$loaded);
                   14810: 
1.844     albertel 14811: 	my ($lonid) = @_;
                   14812: 	return $hostdom{$lonid};
                   14813:     }
                   14814: 
1.841     albertel 14815:     sub all_domains {
1.852     albertel 14816: 	&load_hosts_tab() if (!$loaded);
                   14817: 
1.841     albertel 14818: 	my %seen;
                   14819: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14820: 	return @uniq;
                   14821:     }
1.1074    raeburn  14822: 
                   14823:     sub internet_dom {
                   14824:         &load_hosts_tab() if (!$loaded);
                   14825: 
                   14826:         my ($lonid) = @_;
                   14827:         return $internetdom{$lonid};
                   14828:     }
1.1107    raeburn  14829: 
                   14830:     sub is_LC_dns {
                   14831:         &load_hosts_tab() if (!$loaded);
                   14832: 
                   14833:         my ($hostname) = @_;
                   14834:         return exists($LC_dns_serv{$hostname});
                   14835:     }
                   14836: 
1.1       albertel 14837: }
                   14838: 
1.847     albertel 14839: { 
                   14840:     my %iphost;
1.856     albertel 14841:     my %name_to_ip;
                   14842:     my %lonid_to_ip;
1.869     albertel 14843: 
1.847     albertel 14844:     sub get_hosts_from_ip {
                   14845: 	my ($ip) = @_;
                   14846: 	my %iphosts = &get_iphost();
                   14847: 	if (ref($iphosts{$ip})) {
                   14848: 	    return @{$iphosts{$ip}};
                   14849: 	}
                   14850: 	return;
1.839     albertel 14851:     }
1.864     albertel 14852:     
                   14853:     sub reset_hosts_ip_info {
                   14854: 	undef(%iphost);
                   14855: 	undef(%name_to_ip);
                   14856: 	undef(%lonid_to_ip);
                   14857:     }
1.856     albertel 14858: 
                   14859:     sub get_host_ip {
                   14860: 	my ($lonid) = @_;
                   14861: 	if (exists($lonid_to_ip{$lonid})) {
                   14862: 	    return $lonid_to_ip{$lonid};
                   14863: 	}
                   14864: 	my $name=&hostname($lonid);
                   14865:    	my $ip = gethostbyname($name);
                   14866: 	return if (!$ip || length($ip) ne 4);
                   14867: 	$ip=inet_ntoa($ip);
                   14868: 	$name_to_ip{$name}   = $ip;
                   14869: 	$lonid_to_ip{$lonid} = $ip;
                   14870: 	return $ip;
                   14871:     }
1.847     albertel 14872:     
                   14873:     sub get_iphost {
1.1172.2.70  raeburn  14874: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14875: 
1.869     albertel 14876: 	if (!$ignore_cache) {
                   14877: 	    if (%iphost) {
                   14878: 		return %iphost;
                   14879: 	    }
                   14880: 	    my ($ip_info,$cached)=
                   14881: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14882: 	    if ($cached) {
                   14883: 		%iphost      = %{$ip_info->[0]};
                   14884: 		%name_to_ip  = %{$ip_info->[1]};
                   14885: 		%lonid_to_ip = %{$ip_info->[2]};
                   14886: 		return %iphost;
                   14887: 	    }
                   14888: 	}
1.894     albertel 14889: 
                   14890: 	# get yesterday's info for fallback
                   14891: 	my %old_name_to_ip;
                   14892: 	my ($ip_info,$cached)=
                   14893: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14894: 	if ($cached) {
                   14895: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14896: 	}
                   14897: 
1.1172.2.70  raeburn  14898: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14899: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14900: 	    my $ip;
                   14901: 	    if (!exists($name_to_ip{$name})) {
                   14902: 		$ip = gethostbyname($name);
                   14903: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14904: 		    if (defined($old_name_to_ip{$name})) {
                   14905: 			$ip = $old_name_to_ip{$name};
                   14906: 			&logthis("Can't find $name defaulting to old $ip");
                   14907: 		    } else {
                   14908: 			&logthis("Name $name no IP found");
                   14909: 			next;
                   14910: 		    }
                   14911: 		} else {
                   14912: 		    $ip=inet_ntoa($ip);
1.847     albertel 14913: 		}
                   14914: 		$name_to_ip{$name} = $ip;
                   14915: 	    } else {
                   14916: 		$ip = $name_to_ip{$name};
1.653     albertel 14917: 	    }
1.888     albertel 14918: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14919: 		$lonid_to_ip{$id} = $ip;
                   14920: 	    }
                   14921: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14922: 	}
1.1172.2.70  raeburn  14923:         unless ($nocache) {
                   14924: 	    &do_cache_new('iphost','iphost',
                   14925: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14926: 		          48*60*60);
                   14927:         }
1.869     albertel 14928: 
1.847     albertel 14929: 	return %iphost;
1.598     albertel 14930:     }
                   14931: 
1.992     raeburn  14932:     #
                   14933:     #  Given a DNS returns the loncapa host name for that DNS 
                   14934:     # 
                   14935:     sub host_from_dns {
                   14936:         my ($dns) = @_;
                   14937:         my @hosts;
                   14938:         my $ip;
                   14939: 
1.993     raeburn  14940:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14941:             $ip = $name_to_ip{$dns};
                   14942:         }
                   14943:         if (!$ip) {
                   14944:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14945:             if (length($ip) == 4) { 
                   14946: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14947:             }
                   14948:         }
                   14949:         if ($ip) {
                   14950: 	    @hosts = get_hosts_from_ip($ip);
                   14951: 	    return $hosts[0];
                   14952:         }
                   14953:         return undef;
1.986     foxr     14954:     }
1.992     raeburn  14955: 
1.1074    raeburn  14956:     sub get_internet_names {
                   14957:         my ($lonid) = @_;
                   14958:         return if ($lonid eq '');
                   14959:         my ($idnref,$cached)=
                   14960:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14961:         if ($cached) {
                   14962:             return $idnref;
                   14963:         }
                   14964:         my $ip = &get_host_ip($lonid);
                   14965:         my @hosts = &get_hosts_from_ip($ip);
                   14966:         my %iphost = &get_iphost();
                   14967:         my (@idns,%seen);
                   14968:         foreach my $id (@hosts) {
                   14969:             my $dom = &host_domain($id);
                   14970:             my $prim_id = &domain($dom,'primary');
                   14971:             my $prim_ip = &get_host_ip($prim_id);
                   14972:             next if ($seen{$prim_ip});
                   14973:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14974:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14975:                     my $intdom = &internet_dom($id);
                   14976:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14977:                         push(@idns,$intdom);
                   14978:                     }
                   14979:                 }
                   14980:             }
                   14981:             $seen{$prim_ip} = 1;
                   14982:         }
1.1172.2.23  raeburn  14983:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14984:     }
                   14985: 
1.986     foxr     14986: }
                   14987: 
1.1079    raeburn  14988: sub all_loncaparevs {
1.1172.2.39  raeburn  14989:     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  14990: }
                   14991: 
1.1172.2.27  raeburn  14992: # ------------------------------------------------------- Read loncaparev table
                   14993: {
                   14994:     sub load_loncaparevs {
                   14995:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14996:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14997:                 while (my $configline=<$config>) {
                   14998:                     chomp($configline);
                   14999:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15000:                     $loncaparevs{$hostid}=$loncaparev;
                   15001:                 }
                   15002:                 close($config);
                   15003:             }
                   15004:         }
                   15005:     }
                   15006: }
                   15007: 
                   15008: # ----------------------------------------------------- Read serverhostID table
                   15009: {
                   15010:     sub load_serverhomeIDs {
                   15011:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15012:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15013:                 while (my $configline=<$config>) {
                   15014:                     chomp($configline);
                   15015:                     my ($name,$id)=split(/:/,$configline);
                   15016:                     $serverhomeIDs{$name}=$id;
                   15017:                 }
                   15018:                 close($config);
                   15019:             }
                   15020:         }
                   15021:     }
                   15022: }
                   15023: 
                   15024: 
1.862     albertel 15025: BEGIN {
                   15026: 
                   15027: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15028:     unless ($readit) {
                   15029: {
                   15030:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15031:     %perlvar = (%perlvar,%{$configvars});
                   15032: }
                   15033: 
                   15034: 
1.1       albertel 15035: # ------------------------------------------------------ Read spare server file
                   15036: {
1.1172.2.96  raeburn  15037:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15038: 
                   15039:     while (my $configline=<$config>) {
                   15040:        chomp($configline);
1.284     matthew  15041:        if ($configline) {
1.784     albertel 15042: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15043: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15044: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15045:        }
                   15046:     }
1.448     albertel 15047:     close($config);
1.1       albertel 15048: }
1.11      www      15049: # ------------------------------------------------------------ Read permissions
                   15050: {
1.1172.2.96  raeburn  15051:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15052: 
                   15053:     while (my $configline=<$config>) {
1.448     albertel 15054: 	chomp($configline);
                   15055: 	if ($configline) {
                   15056: 	    my ($role,$perm)=split(/ /,$configline);
                   15057: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15058: 	}
1.11      www      15059:     }
1.448     albertel 15060:     close($config);
1.11      www      15061: }
                   15062: 
                   15063: # -------------------------------------------- Read plain texts for permissions
                   15064: {
1.1172.2.96  raeburn  15065:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15066: 
                   15067:     while (my $configline=<$config>) {
1.448     albertel 15068: 	chomp($configline);
                   15069: 	if ($configline) {
1.742     raeburn  15070: 	    my ($short,@plain)=split(/:/,$configline);
                   15071:             %{$prp{$short}} = ();
                   15072: 	    if (@plain > 0) {
                   15073:                 $prp{$short}{'std'} = $plain[0];
                   15074:                 for (my $i=1; $i<@plain; $i++) {
                   15075:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15076:                 }
                   15077:             }
1.448     albertel 15078: 	}
1.135     www      15079:     }
1.448     albertel 15080:     close($config);
1.135     www      15081: }
                   15082: 
                   15083: # ---------------------------------------------------------- Read package table
                   15084: {
1.1172.2.96  raeburn  15085:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15086: 
                   15087:     while (my $configline=<$config>) {
1.483     albertel 15088: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15089: 	chomp($configline);
                   15090: 	my ($short,$plain)=split(/:/,$configline);
                   15091: 	my ($pack,$name)=split(/\&/,$short);
                   15092: 	if ($plain ne '') {
                   15093: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15094: 	    $packagetab{$short}=$plain; 
                   15095: 	}
1.11      www      15096:     }
1.448     albertel 15097:     close($config);
1.329     matthew  15098: }
                   15099: 
1.1172.2.27  raeburn  15100: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15101: 
1.1172.2.27  raeburn  15102: &load_loncaparevs();
                   15103: 
                   15104: # ------------------------------------------------------- Read serverhostID table
                   15105: 
                   15106: &load_serverhomeIDs();
1.1074    raeburn  15107: 
1.1172.2.27  raeburn  15108: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15109: {
                   15110:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15111:     if (-e $file) {
                   15112:         my $parser = HTML::LCParser->new($file);
                   15113:         while (my $token = $parser->get_token()) {
                   15114:             if ($token->[0] eq 'S') {
                   15115:                 my $item = $token->[1];
                   15116:                 my $name = $token->[2]{'name'};
                   15117:                 my $value = $token->[2]{'value'};
                   15118:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15119:                     my $release = $parser->get_text();
                   15120:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15121:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15122:                 }
                   15123:             }
                   15124:         }
                   15125:     }
1.1073    raeburn  15126: }
                   15127: 
1.1138    raeburn  15128: # ---------------------------------------------------------- Read managers table
                   15129: {
                   15130:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15131:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15132:             while (my $configline=<$config>) {
                   15133:                 chomp($configline);
                   15134:                 next if ($configline =~ /^\#/);
                   15135:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15136:                     $managerstab{$configline} = 1;
                   15137:                 }
                   15138:             }
                   15139:             close($config);
                   15140:         }
                   15141:     }
                   15142: }
                   15143: 
1.329     matthew  15144: # ------------- set up temporary directory
                   15145: {
1.1117    foxr     15146:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15147: 
1.11      www      15148: }
                   15149: 
1.1172.2.104  raeburn  15150: # ------------- set default texengine (domain default overrides this)
                   15151: {
                   15152:     $deftex = LONCAPA::texengine();
                   15153: }
                   15154: 
1.1172.2.114  raeburn  15155: # ------------- set default minimum length for passwords for internal auth users
                   15156: {
                   15157:     $passwdmin = LONCAPA::passwd_min();
                   15158: }
                   15159: 
1.794     albertel 15160: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15161: 				'compress_threshold'=> 20_000,
                   15162:  			        });
1.185     www      15163: 
1.281     www      15164: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15165: $dumpcount=0;
1.958     www      15166: $locknum=0;
1.22      www      15167: 
1.163     harris41 15168: &logtouch();
1.672     albertel 15169: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15170: $readit=1;
1.564     albertel 15171:     {
                   15172: 	use integer;
                   15173: 	my $test=(2**32)+1;
1.568     albertel 15174: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15175: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15176:     }
1.195     www      15177: }
1.1       albertel 15178: }
1.179     www      15179: 
1.1       albertel 15180: 1;
1.191     harris41 15181: __END__
                   15182: 
1.243     albertel 15183: =pod
                   15184: 
1.191     harris41 15185: =head1 NAME
                   15186: 
1.243     albertel 15187: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15188: 
                   15189: =head1 SYNOPSIS
                   15190: 
1.243     albertel 15191: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15192: 
                   15193:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15194: 
1.243     albertel 15195: Common parameters:
                   15196: 
                   15197: =over 4
                   15198: 
                   15199: =item *
                   15200: 
                   15201: $uname : an internal username (if $cname expecting a course Id specifically)
                   15202: 
                   15203: =item *
                   15204: 
                   15205: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15206: 
                   15207: =item *
                   15208: 
                   15209: $symb : a resource instance identifier
                   15210: 
                   15211: =item *
                   15212: 
                   15213: $namespace : the name of a .db file that contains the data needed or
                   15214: being set.
                   15215: 
                   15216: =back
                   15217: 
1.394     bowersj2 15218: =head1 OVERVIEW
1.191     harris41 15219: 
1.394     bowersj2 15220: lonnet provides subroutines which interact with the
                   15221: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15222: about classes, users, and resources.
1.243     albertel 15223: 
                   15224: For many of these objects you can also use this to store data about
                   15225: them or modify them in various ways.
1.191     harris41 15226: 
1.394     bowersj2 15227: =head2 Symbs
1.191     harris41 15228: 
1.394     bowersj2 15229: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15230: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15231: map, the resource number of the resource in the map, and the URL of
                   15232: the resource itself. The latter is somewhat redundant, but might help
                   15233: if maps change.
                   15234: 
                   15235: An example is
                   15236: 
                   15237:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15238: 
                   15239: The respective map entry is
                   15240: 
                   15241:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15242:   title="Problem 2">
                   15243:  </resource>
                   15244: 
                   15245: Symbs are used by the random number generator, as well as to store and
                   15246: restore data specific to a certain instance of for example a problem.
                   15247: 
                   15248: =head2 Storing And Retrieving Data
                   15249: 
                   15250: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15251: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15252: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15253: is is the non-critical message twin of cstore. These functions are for
                   15254: handlers to store a perl hash to a user's permanent data space in an
                   15255: easy manner, and to retrieve it again on another call. It is expected
                   15256: that a handler would use this once at the beginning to retrieve data,
                   15257: and then again once at the end to send only the new data back.
                   15258: 
                   15259: The data is stored in the user's data directory on the user's
                   15260: homeserver under the ID of the course.
                   15261: 
                   15262: The hash that is returned by restore will have all of the previous
                   15263: value for all of the elements of the hash.
                   15264: 
                   15265: Example:
                   15266: 
                   15267:  #creating a hash
                   15268:  my %hash;
                   15269:  $hash{'foo'}='bar';
                   15270: 
                   15271:  #storing it
                   15272:  &Apache::lonnet::cstore(\%hash);
                   15273: 
                   15274:  #changing a value
                   15275:  $hash{'foo'}='notbar';
                   15276: 
                   15277:  #adding a new value
                   15278:  $hash{'bar'}='foo';
                   15279:  &Apache::lonnet::cstore(\%hash);
                   15280: 
                   15281:  #retrieving the hash
                   15282:  my %history=&Apache::lonnet::restore();
                   15283: 
                   15284:  #print the hash
                   15285:  foreach my $key (sort(keys(%history))) {
                   15286:    print("\%history{$key} = $history{$key}");
                   15287:  }
                   15288: 
                   15289: Will print out:
1.191     harris41 15290: 
1.394     bowersj2 15291:  %history{1:foo} = bar
                   15292:  %history{1:keys} = foo:timestamp
                   15293:  %history{1:timestamp} = 990455579
                   15294:  %history{2:bar} = foo
                   15295:  %history{2:foo} = notbar
                   15296:  %history{2:keys} = foo:bar:timestamp
                   15297:  %history{2:timestamp} = 990455580
                   15298:  %history{bar} = foo
                   15299:  %history{foo} = notbar
                   15300:  %history{timestamp} = 990455580
                   15301:  %history{version} = 2
                   15302: 
                   15303: Note that the special hash entries C<keys>, C<version> and
                   15304: C<timestamp> were added to the hash. C<version> will be equal to the
                   15305: total number of versions of the data that have been stored. The
                   15306: C<timestamp> attribute will be the UNIX time the hash was
                   15307: stored. C<keys> is available in every historical section to list which
                   15308: keys were added or changed at a specific historical revision of a
                   15309: hash.
                   15310: 
                   15311: B<Warning>: do not store the hash that restore returns directly. This
                   15312: will cause a mess since it will restore the historical keys as if the
                   15313: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15314: 
1.394     bowersj2 15315: Calling convention:
1.191     harris41 15316: 
1.1172.2.27  raeburn  15317:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15318:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15319: 
1.394     bowersj2 15320: For more detailed information, see lonnet specific documentation.
1.191     harris41 15321: 
1.394     bowersj2 15322: =head1 RETURN MESSAGES
1.191     harris41 15323: 
1.394     bowersj2 15324: =over 4
1.191     harris41 15325: 
1.394     bowersj2 15326: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15327: 
1.394     bowersj2 15328: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15329: when the connection is brought back up
1.191     harris41 15330: 
1.394     bowersj2 15331: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15332: for later delivery
1.191     harris41 15333: 
1.967     bisitz   15334: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15335: 
1.394     bowersj2 15336: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15337: that was requested
1.191     harris41 15338: 
1.243     albertel 15339: =back
1.191     harris41 15340: 
1.243     albertel 15341: =head1 PUBLIC SUBROUTINES
1.191     harris41 15342: 
1.243     albertel 15343: =head2 Session Environment Functions
1.191     harris41 15344: 
1.243     albertel 15345: =over 4
1.191     harris41 15346: 
1.394     bowersj2 15347: =item * 
                   15348: X<appenv()>
1.949     raeburn  15349: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15350: the user envirnoment file, and will be restored for each access this
1.620     albertel 15351: user makes during this session, also modifies the %env for the current
1.949     raeburn  15352: process. Optional rolesarrayref - if defined contains a reference to an array
                   15353: of roles which are exempt from the restriction on modifying user.role entries 
                   15354: in the user's environment.db and in %env.    
1.191     harris41 15355: 
                   15356: =item *
1.394     bowersj2 15357: X<delenv()>
1.987     raeburn  15358: B<delenv($delthis,$regexp)>: removes all items from the session
                   15359: environment file that begin with $delthis. If the 
                   15360: optional second arg - $regexp - is true, $delthis is treated as a 
                   15361: regular expression, otherwise \Q$delthis\E is used. 
                   15362: The values are also deleted from the current processes %env.
1.191     harris41 15363: 
1.795     albertel 15364: =item * get_env_multiple($name) 
                   15365: 
                   15366: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15367: values may be defined and end up as an array ref.
                   15368: 
                   15369: returns an array of values
                   15370: 
1.243     albertel 15371: =back
                   15372: 
                   15373: =head2 User Information
1.191     harris41 15374: 
1.243     albertel 15375: =over 4
1.191     harris41 15376: 
                   15377: =item *
1.394     bowersj2 15378: X<queryauthenticate()>
                   15379: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15380: authentication scheme
                   15381: 
                   15382: =item *
1.394     bowersj2 15383: X<authenticate()>
1.1073    raeburn  15384: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15385: authenticate user from domain's lib servers (first use the current
                   15386: one). C<$upass> should be the users password.
1.1073    raeburn  15387: $checkdefauth is optional (value is 1 if a check should be made to
                   15388:    authenticate user using default authentication method, and allow
                   15389:    account creation if username does not have account in the domain).
                   15390: $clientcancheckhost is optional (value is 1 if checking whether the
                   15391:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15392: 
                   15393: =item *
1.394     bowersj2 15394: X<homeserver()>
                   15395: B<homeserver($uname,$udom)>: find the server which has
                   15396: the user's directory and files (there must be only one), this caches
                   15397: the answer, and also caches if there is a borken connection.
1.191     harris41 15398: 
                   15399: =item *
1.394     bowersj2 15400: X<idget()>
                   15401: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15402: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15403: username, and only 1 username per ID in a specific domain) (returns
                   15404: hash: id=>name,id=>name)
1.191     harris41 15405: 
                   15406: =item *
1.394     bowersj2 15407: X<idrget()>
                   15408: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15409: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15410: 
                   15411: =item *
1.394     bowersj2 15412: X<idput()>
                   15413: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15414: 
                   15415: =item *
1.394     bowersj2 15416: X<rolesinit()>
1.1169    droeschl 15417: B<rolesinit($udom,$username)>: get user privileges.
                   15418: returns user role, first access and timer interval hashes
1.243     albertel 15419: 
                   15420: =item *
1.1171    droeschl 15421: X<privileged()>
                   15422: B<privileged($username,$domain)>: returns a true if user has a
                   15423: privileged and active role (i.e. su or dc), false otherwise.
                   15424: 
                   15425: =item *
1.551     albertel 15426: X<getsection()>
                   15427: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15428: course $cname, return section name/number or '' for "not in course"
                   15429: and '-1' for "no section"
                   15430: 
                   15431: =item *
1.394     bowersj2 15432: X<userenvironment()>
                   15433: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15434: passed in @what from the requested user's environment, returns a hash
                   15435: 
1.858     raeburn  15436: =item * 
                   15437: X<userlog_query()>
1.859     albertel 15438: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15439: activity.log file. %filters defines filters applied when parsing the
                   15440: log file. These can be start or end timestamps, or the type of action
                   15441: - log to look for Login or Logout events, check for Checkin or
                   15442: Checkout, role for role selection. The response is in the form
                   15443: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15444: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15445: 
1.243     albertel 15446: =back
                   15447: 
                   15448: =head2 User Roles
                   15449: 
                   15450: =over 4
                   15451: 
                   15452: =item *
                   15453: 
1.1172.2.65  raeburn  15454: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15455: returns codes for allowed actions.
                   15456: 
                   15457: The first argument is required, all others are optional.
                   15458: 
                   15459: $priv is the privilege being checked.
                   15460: $uri contains additional information about what is being checked for access (e.g.,
                   15461: URL, course ID etc.).
                   15462: $symb is the unique resource instance identifier in a course; if needed,
                   15463: but not provided, it will be retrieved via a call to &symbread().
                   15464: $role is the role for which a priv is being checked (only used if priv is evb).
                   15465: $clientip is the user's IP address (only used when checking for access to portfolio
                   15466: files).
                   15467: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15468: prevents recursive calls to &allowed.
                   15469: 
1.243     albertel 15470:  F: full access
                   15471:  U,I,K: authentication modes (cxx only)
                   15472:  '': forbidden
                   15473:  1: user needs to choose course
                   15474:  2: browse allowed
1.766     albertel 15475:  A: passphrase authentication needed
1.1172.2.65  raeburn  15476:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15477:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15478: 
                   15479: =item *
                   15480: 
1.1172.2.13  raeburn  15481: constructaccess($url,$setpriv) : check for access to construction space URL
                   15482: 
                   15483: See if the owner domain and name in the URL match those in the
                   15484: expected environment.  If so, return three element list
                   15485: ($ownername,$ownerdomain,$ownerhome).
                   15486: 
                   15487: Otherwise return the null string.
                   15488: 
                   15489: If second argument 'setpriv' is true, it assigns the privileges,
                   15490: and returns the same three element list, unless the owner has
                   15491: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15492: in which case the null string is returned.
                   15493: 
                   15494: =item *
                   15495: 
1.1172.2.84  raeburn  15496: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15497: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15498: for system, domain, and course level. $uname and $udom are optional (current
                   15499: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15500: 
                   15501: =item *
                   15502: 
1.988     raeburn  15503: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15504: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15505: $type is Course (default) or Community.
1.988     raeburn  15506: If $forcedefault evaluates to true, text returned will be default 
                   15507: text for $type. Otherwise, if this is a course, the text returned 
                   15508: will be a custom name for the role (if defined in the course's 
                   15509: environment).  If no custom name is defined the default is returned.
                   15510:    
1.832     raeburn  15511: =item *
                   15512: 
1.1172.2.23  raeburn  15513: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15514: All arguments are optional. Returns a hash of a roles, either for
                   15515: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15516: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15517: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15518: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15519: For each key, value is set to colon-separated start and end times for
                   15520: the role.  If no username and domain are specified, will default to
1.934     raeburn  15521: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15522: of role statuses (active, future or previous), roles 
                   15523: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15524: to restrict the list of roles reported. If no array ref is 
                   15525: provided for types, will default to return only active roles.
1.834     albertel 15526: 
1.1172.2.13  raeburn  15527: =item *
                   15528: 
                   15529: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15530: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15531: 
                   15532: Additional optional arguments are: $type (if role checking is to be restricted
                   15533: to certain user status types -- previous (expired roles), active (currently
                   15534: available roles) or future (roles available in the future), and
                   15535: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15536: have active Domain Coordinator role in course's domain or in additional
                   15537: domains (specified in 'Domains to check for privileged users' in course
                   15538: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15539: 
                   15540: =item *
                   15541: 
                   15542: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15543: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15544: $possdomains and $possroles are optional array refs -- to domains to check and
                   15545: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15546: users' roles.db to check for a dc or su role in any domain. This can be
                   15547: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15548: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15549: this then allows &privileged_by_domain() to be used, which caches the identity
                   15550: of privileged users, eliminating the need for repeated calls to &dump().
                   15551: 
                   15552: =item *
                   15553: 
                   15554: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15555: where the outer hash keys are domains specified in the $possdomains array ref,
                   15556: next inner hash keys are privileged roles specified in the $roles array ref,
                   15557: and the innermost hash contains key = value pairs for username:domain = end:start
                   15558: for active or future "privileged" users with that role in that domain. To avoid
                   15559: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15560: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15561: 
1.243     albertel 15562: =back
                   15563: 
                   15564: =head2 User Modification
                   15565: 
                   15566: =over 4
                   15567: 
                   15568: =item *
                   15569: 
1.957     raeburn  15570: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15571: user for the level given by URL.  Optional start and end dates (leave empty
                   15572: string or zero for "no date")
1.191     harris41 15573: 
                   15574: =item *
                   15575: 
1.243     albertel 15576: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15577: change a users, password, possible return values are: ok,
                   15578: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15579: refused
1.191     harris41 15580: 
                   15581: =item *
                   15582: 
1.243     albertel 15583: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15584: 
                   15585: =item *
                   15586: 
1.1058    raeburn  15587: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15588:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15589: 
                   15590: will update user information (firstname,middlename,lastname,generation,
                   15591: permanentemail), and if forceid is true, student/employee ID also.
                   15592: A user's institutional affiliation(s) can also be updated.
                   15593: User information fields will not be overwritten with empty entries 
                   15594: unless the field is included in the $candelete array reference.
                   15595: This array is included when a single user is modified via "Manage Users",
                   15596: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15597: 
                   15598: =item *
                   15599: 
1.286     matthew  15600: modifystudent
                   15601: 
1.957     raeburn  15602: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15603: The course id is resolved based on the current user's environment.  
                   15604: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15605: associated with a course.
                   15606: 
1.297     matthew  15607: This call is essentially a wrapper for lonnet::modifyuser and
                   15608: lonnet::modify_student_enrollment
1.286     matthew  15609: 
                   15610: Inputs: 
                   15611: 
                   15612: =over 4
                   15613: 
1.957     raeburn  15614: =item B<$udom> Student's loncapa domain
1.286     matthew  15615: 
1.957     raeburn  15616: =item B<$uname> Student's loncapa login name
1.286     matthew  15617: 
1.964     bisitz   15618: =item B<$uid> Student/Employee ID
1.286     matthew  15619: 
1.957     raeburn  15620: =item B<$umode> Student's authentication mode
1.286     matthew  15621: 
1.957     raeburn  15622: =item B<$upass> Student's password
1.286     matthew  15623: 
1.957     raeburn  15624: =item B<$first> Student's first name
1.286     matthew  15625: 
1.957     raeburn  15626: =item B<$middle> Student's middle name
1.286     matthew  15627: 
1.957     raeburn  15628: =item B<$last> Student's last name
1.286     matthew  15629: 
1.957     raeburn  15630: =item B<$gene> Student's generation
1.286     matthew  15631: 
1.957     raeburn  15632: =item B<$usec> Student's section in course
1.286     matthew  15633: 
                   15634: =item B<$end> Unix time of the roles expiration
                   15635: 
                   15636: =item B<$start> Unix time of the roles start date
                   15637: 
                   15638: =item B<$forceid> If defined, allow $uid to be changed
                   15639: 
                   15640: =item B<$desiredhome> server to use as home server for student
                   15641: 
1.957     raeburn  15642: =item B<$email> Student's permanent e-mail address
                   15643: 
                   15644: =item B<$type> Type of enrollment (auto or manual)
                   15645: 
1.963     raeburn  15646: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15647: 
                   15648: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15649: 
1.963     raeburn  15650: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15651: 
1.963     raeburn  15652: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15653: 
1.1172.2.19  raeburn  15654: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15655: 
                   15656: =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  15657: 
1.286     matthew  15658: =back
1.297     matthew  15659: 
                   15660: =item *
                   15661: 
                   15662: modify_student_enrollment
                   15663: 
1.1172.2.31  raeburn  15664: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15665: 'role.request.course' must be defined for this function to proceed.
                   15666: 
                   15667: Inputs:
                   15668: 
                   15669: =over 4
                   15670: 
1.1172.2.31  raeburn  15671: =item $udom, student's domain
1.297     matthew  15672: 
1.1172.2.31  raeburn  15673: =item $uname, student's name
1.297     matthew  15674: 
1.1172.2.31  raeburn  15675: =item $uid, student's user id
1.297     matthew  15676: 
1.1172.2.31  raeburn  15677: =item $first, student's first name
1.297     matthew  15678: 
                   15679: =item $middle
                   15680: 
                   15681: =item $last
                   15682: 
                   15683: =item $gene
                   15684: 
                   15685: =item $usec
                   15686: 
                   15687: =item $end
                   15688: 
                   15689: =item $start
                   15690: 
1.957     raeburn  15691: =item $type
                   15692: 
                   15693: =item $locktype
                   15694: 
                   15695: =item $cid
                   15696: 
                   15697: =item $selfenroll
                   15698: 
                   15699: =item $context
                   15700: 
1.1172.2.19  raeburn  15701: =item $credits, number of credits student will earn from this class
                   15702: 
1.1172.2.76  raeburn  15703: =item $instsec, institutional course section code for student
                   15704: 
1.297     matthew  15705: =back
                   15706: 
1.191     harris41 15707: 
                   15708: =item *
                   15709: 
1.243     albertel 15710: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15711: custom role; give a custom role to a user for the level given by URL.  Specify
                   15712: name and domain of role author, and role name
1.191     harris41 15713: 
                   15714: =item *
                   15715: 
1.243     albertel 15716: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15717: 
                   15718: =item *
                   15719: 
1.243     albertel 15720: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15721: 
                   15722: =back
                   15723: 
                   15724: =head2 Course Infomation
                   15725: 
                   15726: =over 4
1.191     harris41 15727: 
                   15728: =item *
                   15729: 
1.1118    foxr     15730: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15731: specified course id, including all environment settings for the
                   15732: course, the description of the course will be in the hash under the
                   15733: key 'description'
1.191     harris41 15734: 
1.1118    foxr     15735: $options is an optional parameter that if supplied is a hash reference that controls
                   15736: what how this function works.  It has the following key/values:
                   15737: 
                   15738: =over 4
                   15739: 
                   15740: =item freshen_cache
                   15741: 
                   15742: If defined, and the environment cache for the course is valid, it is 
                   15743: returned in the returned hash.
                   15744: 
                   15745: =item one_time
                   15746: 
                   15747: If defined, the last cache time is set to _now_
                   15748: 
                   15749: =item user
                   15750: 
                   15751: If defined, the supplied username is used instead of the current user.
                   15752: 
                   15753: 
                   15754: =back
                   15755: 
1.191     harris41 15756: =item *
                   15757: 
1.624     albertel 15758: resdata($name,$domain,$type,@which) : request for current parameter
                   15759: setting for a specific $type, where $type is either 'course' or 'user',
                   15760: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15761: answers for 10 minutes.
1.243     albertel 15762: 
1.877     foxr     15763: =item *
                   15764: 
                   15765: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15766: data base, returning a hash that is keyed by the resource name and has
                   15767: values that are the resource value.  I believe that the timestamps and
                   15768: versions are also returned.
                   15769: 
1.243     albertel 15770: =back
                   15771: 
                   15772: =head2 Course Modification
                   15773: 
                   15774: =over 4
1.191     harris41 15775: 
                   15776: =item *
                   15777: 
1.243     albertel 15778: writecoursepref($courseid,%prefs) : write preferences (environment
                   15779: database) for a course
1.191     harris41 15780: 
                   15781: =item *
                   15782: 
1.1011    raeburn  15783: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15784: 
                   15785: =item *
                   15786: 
1.1038    raeburn  15787: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15788: 
1.1167    droeschl 15789: =item *
                   15790: 
                   15791: is_course($courseid), is_course($cdom, $cnum)
                   15792: 
                   15793: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15794: two component version $cdom, $cnum. It checks if the specified course exists.
                   15795: 
                   15796: Returns:
                   15797:     undef if the course doesn't exist, otherwise
                   15798:     in scalar context the combined courseid.
                   15799:     in list context the two components of the course identifier, domain and 
                   15800:     courseid.    
                   15801: 
1.243     albertel 15802: =back
                   15803: 
1.1172.2.109  raeburn  15804: =head2 Bubblesheet Configuration
                   15805: 
                   15806: =over 4
                   15807: 
                   15808: =item *
                   15809: 
                   15810: get_scantron_config($which)
                   15811: 
                   15812: $which - the name of the configuration to parse from the file.
                   15813: 
                   15814: Parses and returns the bubblesheet configuration line selected as a
                   15815: hash of configuration file fields.
                   15816: 
                   15817: 
                   15818: Returns:
                   15819:     If the named configuration is not in the file, an empty
                   15820:     hash is returned.
                   15821: 
                   15822:     a hash with the fields
                   15823:       name         - internal name for the this configuration setup
                   15824:       description  - text to display to operator that describes this config
                   15825:       CODElocation - if 0 or the string 'none'
                   15826:                           - no CODE exists for this config
                   15827:                      if -1 || the string 'letter'
                   15828:                           - a CODE exists for this config and is
                   15829:                             a string of letters
                   15830:                      Unsupported value (but planned for future support)
                   15831:                           if a positive integer
                   15832:                                - The CODE exists as the first n items from
                   15833:                                  the question section of the form
                   15834:                           if the string 'number'
                   15835:                                - The CODE exists for this config and is
                   15836:                                  a string of numbers
                   15837:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15838:                      the CODE starts
                   15839:       CODElength  - length of the CODE
                   15840:       IDstart     - column where the student/employee ID starts
                   15841:       IDlength    - length of the student/employee ID info
                   15842:       Qstart      - column where the information from the bubbled
                   15843:                     'questions' start
                   15844:       Qlength     - number of columns comprising a single bubble line from
                   15845:                     the sheet. (usually either 1 or 10)
                   15846:       Qon         - either a single character representing the character used
                   15847:                     to signal a bubble was chosen in the positional setup, or
                   15848:                     the string 'letter' if the letter of the chosen bubble is
                   15849:                     in the final, or 'number' if a number representing the
                   15850:                     chosen bubble is in the file (1->A 0->J)
                   15851:       Qoff        - the character used to represent that a bubble was
                   15852:                     left blank
                   15853:       PaperID     - if the scanning process generates a unique number for each
                   15854:                     sheet scanned the column that this ID number starts in
                   15855:       PaperIDlength - number of columns that comprise the unique ID number
                   15856:                       for the sheet of paper
                   15857:       FirstName   - column that the first name starts in
                   15858:       FirstNameLength - number of columns that the first name spans
                   15859:       LastName    - column that the last name starts in
                   15860:       LastNameLength - number of columns that the last name spans
                   15861:       BubblesPerRow - number of bubbles available in each row used to
                   15862:                       bubble an answer. (If not specified, 10 assumed).
                   15863: 
                   15864: 
                   15865: =item *
                   15866: 
                   15867: get_scantronformat_file($cdom)
                   15868: 
                   15869: $cdom - the course's domain (optional); if not supplied, uses
                   15870: domain for current $env{'request.course.id'}.
                   15871: 
                   15872: Returns an array containing lines from the scantron format file for
                   15873: the domain of the course.
                   15874: 
                   15875: If a url for a custom.tab file is listed in domain's configuration.db,
                   15876: lines are from this file.
                   15877: 
                   15878: Otherwise, if a default.tab has been published in RES space by the
                   15879: domainconfig user, lines are from this file.
                   15880: 
                   15881: Otherwise, fall back to getting lines from the legacy file on the
                   15882: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15883: 
                   15884: =back
                   15885: 
1.243     albertel 15886: =head2 Resource Subroutines
                   15887: 
                   15888: =over 4
1.191     harris41 15889: 
                   15890: =item *
                   15891: 
1.243     albertel 15892: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15893: 
                   15894: =item *
                   15895: 
1.243     albertel 15896: repcopy($filename) : subscribes to the requested file, and attempts to
                   15897: replicate from the owning library server, Might return
1.607     raeburn  15898: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15899: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15900: resource. Expects the local filesystem pathname
                   15901: (/home/httpd/html/res/....)
                   15902: 
                   15903: =back
                   15904: 
                   15905: =head2 Resource Information
                   15906: 
                   15907: =over 4
1.191     harris41 15908: 
                   15909: =item *
                   15910: 
1.1172.2.28  raeburn  15911: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15912: and returns the value of a variety of different possible values,
                   15913: $varname should be a request string, and the other parameters can be
                   15914: used to specify who and what one is asking about. Ordinarily, $cid 
                   15915: does not need to be specified, as it is retrived from 
                   15916: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15917: within lonuserstate::loadmap() when initializing a course, before
                   15918: $env{'request.course.id'} has been set, so it needs to be provided
                   15919: in that one case.
1.243     albertel 15920: 
                   15921: Possible values for $varname are environment.lastname (or other item
                   15922: from the envirnment hash), user.name (or someother aspect about the
                   15923: user), resource.0.maxtries (or some other part and parameter of a
                   15924: resource)
1.204     albertel 15925: 
                   15926: =item *
                   15927: 
1.243     albertel 15928: directcondval($number) : get current value of a condition; reads from a state
                   15929: string
1.204     albertel 15930: 
                   15931: =item *
                   15932: 
1.243     albertel 15933: condval($condidx) : value of condition index based on state
1.204     albertel 15934: 
                   15935: =item *
                   15936: 
1.243     albertel 15937: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15938: resource's metadata, $what should be either a specific key, or either
                   15939: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15940: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15941: 
                   15942: this function automatically caches all requests
1.191     harris41 15943: 
                   15944: =item *
                   15945: 
1.243     albertel 15946: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15947: network of library servers; returns file handle of where SQL and regex results
                   15948: will be stored for query
1.191     harris41 15949: 
                   15950: =item *
                   15951: 
1.1172.2.66  raeburn  15952: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15953: return symbolic list entry (all arguments optional).
                   15954: 
                   15955: Args: filename is the filename (including path) for the file for which a symb
                   15956: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15957: to check access status if more than one resource was found in the bighash
                   15958: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15959: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15960: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15961: cause possible symbs to be checked to determine if they are subject to content
                   15962: blocking, if so they will not be included as possible symbs; possibles is a
                   15963: ref to a hash, which, as a side effect, will be populated with all possible
                   15964: symbs (content blocking not tested).
                   15965: 
1.243     albertel 15966: returns the data handle
1.191     harris41 15967: 
                   15968: =item *
                   15969: 
1.1172.2.17  raeburn  15970: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15971: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15972: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15973: on failure, user must be in a course, as it assumes the existence of
                   15974: the course initial hash, and uses $env('request.course.id'}.  The third
                   15975: arg is an optional reference to a scalar.  If this arg is passed in the
                   15976: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15977: encrypted; otherwise it will be null.
1.243     albertel 15978: 
1.191     harris41 15979: =item *
                   15980: 
1.243     albertel 15981: symbclean($symb) : removes versions numbers from a symb, returns the
                   15982: cleaned symb
1.191     harris41 15983: 
                   15984: =item *
                   15985: 
1.243     albertel 15986: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15987: course map, user must be in a course for it to work.
1.191     harris41 15988: 
                   15989: =item *
                   15990: 
1.243     albertel 15991: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15992: 
                   15993: =item *
                   15994: 
1.243     albertel 15995: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15996: a random seed, all arguments are optional, if they aren't sent it uses the
                   15997: environment to derive them. Note: if symb isn't sent and it can't get one
                   15998: from &symbread it will use the current time as its return value
1.191     harris41 15999: 
                   16000: =item *
                   16001: 
1.243     albertel 16002: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16003: unfakeable, receipt
1.191     harris41 16004: 
                   16005: =item *
                   16006: 
1.620     albertel 16007: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16008: 
                   16009: =item *
                   16010: 
1.243     albertel 16011: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16012: 
                   16013: =item *
                   16014: 
1.243     albertel 16015: 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 16016: 
                   16017: =item *
                   16018: 
1.243     albertel 16019: 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 16020: 
                   16021: =item *
                   16022: 
1.243     albertel 16023: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16024: 
                   16025: =item *
                   16026: 
1.243     albertel 16027: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16028: forcing spreadsheet to reevaluate the resource scores next time.
                   16029: 
1.1172.2.13  raeburn  16030: =item *
                   16031: 
                   16032: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16033: when viewing in course context.
                   16034: 
                   16035:  input: six args -- filename (decluttered), course number, course domain,
                   16036:                     url, symb (if registered) and group (if this is a
                   16037:                     group item -- e.g., bulletin board, group page etc.).
                   16038: 
                   16039:  output: array of five scalars --
                   16040:          $cfile -- url for file editing if editable on current server
                   16041:          $home -- homeserver of resource (i.e., for author if published,
                   16042:                                           or course if uploaded.).
                   16043:          $switchserver --  1 if server switch will be needed.
                   16044:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16045:          $forceview -- 1 if icon/link should be to go to view mode
                   16046: 
                   16047: =item *
                   16048: 
                   16049: is_course_upload($file,$cnum,$cdom)
                   16050: 
                   16051: Used in course context to determine if current file was uploaded to
                   16052: the course (i.e., would be found in /userfiles/docs on the course's
                   16053: homeserver.
                   16054: 
                   16055:   input: 3 args -- filename (decluttered), course number and course domain.
                   16056:   output: boolean -- 1 if file was uploaded.
                   16057: 
1.243     albertel 16058: =back
                   16059: 
                   16060: =head2 Storing/Retreiving Data
                   16061: 
                   16062: =over 4
1.191     harris41 16063: 
                   16064: =item *
                   16065: 
1.1172.2.64  raeburn  16066: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16067: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16068: the remaining args aren't required and if they aren't passed or are '' they will
                   16069: be derived from the env (with the exception of $laststore, which is an
                   16070: optional arg used when a user's submission is stored in grading).
                   16071: $laststore is $version=$timestamp, where $version is the most recent version
                   16072: number retrieved for the corresponding $symb in the $namespace db file, and
                   16073: $timestamp is the timestamp for that transaction (UNIX time).
                   16074: $laststore is currently only passed when cstore() is called by
                   16075: structuretags::finalize_storage().
1.191     harris41 16076: 
                   16077: =item *
                   16078: 
1.1172.2.64  raeburn  16079: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16080: but uses critical subroutine
1.191     harris41 16081: 
                   16082: =item *
                   16083: 
1.243     albertel 16084: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16085: all args are optional
1.191     harris41 16086: 
                   16087: =item *
                   16088: 
1.717     albertel 16089: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16090: dumps the complete (or key matching regexp) namespace into a hash
                   16091: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16092: normally &store()ed into
                   16093: 
                   16094: $range should be either an integer '100' (give me the first 100
                   16095:                                            matching records)
                   16096:               or be  two integers sperated by a - with no spaces
                   16097:                  '30-50' (give me the 30th through the 50th matching
                   16098:                           records)
                   16099: 
                   16100: 
                   16101: =item *
                   16102: 
1.1172.2.59  raeburn  16103: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16104: replaces a &store() version of data with a replacement set of data
                   16105: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16106: reference. If $tolog is true, the transaction is logged in the courselog
                   16107: with an action=PUTSTORE.
1.717     albertel 16108: 
                   16109: =item *
                   16110: 
1.243     albertel 16111: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16112: works very similar to store/cstore, but all data is stored in a
                   16113: temporary location and can be reset using tmpreset, $storehash should
                   16114: be a hash reference, returns nothing on success
1.191     harris41 16115: 
                   16116: =item *
                   16117: 
1.243     albertel 16118: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16119: similar to restore, but all data is stored in a temporary location and
                   16120: can be reset using tmpreset. Returns a hash of values on success,
                   16121: error string otherwise.
1.191     harris41 16122: 
                   16123: =item *
                   16124: 
1.243     albertel 16125: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16126: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16127: 
                   16128: =item *
                   16129: 
1.243     albertel 16130: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16131: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16132: 
                   16133: =item *
                   16134: 
1.243     albertel 16135: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16136: namesp ($udom and $uname are optional)
1.191     harris41 16137: 
                   16138: =item *
                   16139: 
1.702     albertel 16140: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16141: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16142: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16143: 
1.702     albertel 16144: $range should be either an integer '100' (give me the first 100
                   16145:                                            matching records)
                   16146:               or be  two integers sperated by a - with no spaces
                   16147:                  '30-50' (give me the 30th through the 50th matching
                   16148:                           records)
1.449     matthew  16149: =item *
                   16150: 
                   16151: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16152: $store can be a scalar, an array reference, or if the amount to be 
                   16153: incremented is > 1, a hash reference.
                   16154: 
                   16155: ($udom and $uname are optional)
1.191     harris41 16156: 
                   16157: =item *
                   16158: 
1.243     albertel 16159: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16160: ($udom and $uname are optional)
1.191     harris41 16161: 
                   16162: =item *
                   16163: 
1.243     albertel 16164: cput($namespace,$storehash,$udom,$uname) : critical put
                   16165: ($udom and $uname are optional)
1.191     harris41 16166: 
                   16167: =item *
                   16168: 
1.748     albertel 16169: newput($namespace,$storehash,$udom,$uname) :
                   16170: 
                   16171: Attempts to store the items in the $storehash, but only if they don't
                   16172: currently exist, if this succeeds you can be certain that you have 
                   16173: successfully created a new key value pair in the $namespace db.
                   16174: 
                   16175: 
                   16176: Args:
                   16177:  $namespace: name of database to store values to
                   16178:  $storehash: hashref to store to the db
                   16179:  $udom: (optional) domain of user containing the db
                   16180:  $uname: (optional) name of user caontaining the db
                   16181: 
                   16182: Returns:
                   16183:  'ok' -> succeeded in storing all keys of $storehash
                   16184:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16185:                         least <key> already existed in the db (other
                   16186:                         requested keys may also already exist)
1.967     bisitz   16187:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16188:  'con_lost' -> unable to contact request server
                   16189:  'refused' -> action was not allowed by remote machine
                   16190: 
                   16191: 
                   16192: =item *
                   16193: 
1.243     albertel 16194: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16195: reference filled in from namesp (encrypts the return communication)
                   16196: ($udom and $uname are optional)
1.191     harris41 16197: 
                   16198: =item *
                   16199: 
1.243     albertel 16200: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16201: critical subroutine
                   16202: 
1.806     raeburn  16203: =item *
                   16204: 
1.860     raeburn  16205: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16206: array reference filled in from namespace found in domain level on either
                   16207: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16208: 
                   16209: =item *
                   16210: 
1.860     raeburn  16211: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16212: domain level either on specified domain server ($uhome) or primary domain 
                   16213: server ($udom and $uhome are optional)
1.806     raeburn  16214: 
1.943     raeburn  16215: =item * 
                   16216: 
1.1172.2.35  raeburn  16217: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16218: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16219: the target domain.
                   16220: 
                   16221: May also include additional key => value pairs for the following groups:
                   16222: 
                   16223: =over
                   16224: 
                   16225: =item
                   16226: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16227: 
                   16228: =over
                   16229: 
                   16230: =item defaultquota, authorquota
                   16231: 
                   16232: =back
                   16233: 
                   16234: =item
                   16235: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16236: portfolio for users).
                   16237: 
                   16238: =over
                   16239: 
                   16240: =item
                   16241: aboutme, blog, webdav, portfolio
                   16242: 
                   16243: =back
                   16244: 
                   16245: =item
                   16246: requestcourses: ability to request courses, and how requests are processed.
                   16247: 
                   16248: =over
                   16249: 
                   16250: =item
1.1172.2.37  raeburn  16251: official, unofficial, community, textbook
1.1172.2.35  raeburn  16252: 
                   16253: =back
                   16254: 
                   16255: =item
                   16256: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16257: 
                   16258: =over
                   16259: 
                   16260: =item
1.1172.2.44  raeburn  16261: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16262: 
                   16263: =back
                   16264: 
                   16265: =item
                   16266: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16267: for course's uploaded content.
                   16268: 
                   16269: =over
                   16270: 
                   16271: =item
1.1172.2.68  raeburn  16272: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16273: communityquota, textbookquota
1.1172.2.35  raeburn  16274: 
                   16275: =back
                   16276: 
                   16277: =item
                   16278: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16279: on your servers.
                   16280: 
                   16281: =over
                   16282: 
                   16283: =item
                   16284: remotesessions, hostedsessions
                   16285: 
                   16286: =back
                   16287: 
                   16288: =back
                   16289: 
                   16290: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16291: utility to create a configuration.db file on a domain's primary library server
                   16292: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16293: -- corresponding values are authentication type (internal, krb4, krb5,
                   16294: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16295: will be available. Values are retrieved from cache (if current), unless the
                   16296: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16297: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16298: 
                   16299: Typical usage:
1.943     raeburn  16300: 
1.1172.2.35  raeburn  16301: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16302: 
1.243     albertel 16303: =back
                   16304: 
                   16305: =head2 Network Status Functions
                   16306: 
                   16307: =over 4
1.191     harris41 16308: 
                   16309: =item *
                   16310: 
1.1137    raeburn  16311: dirlist() : return directory list based on URI (first arg).
                   16312: 
                   16313: Inputs: 1 required, 5 optional.
                   16314: 
                   16315: =over
                   16316: 
                   16317: =item 
                   16318: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16319: 
                   16320: =item
                   16321: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16322: 
                   16323: =item
                   16324: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16325: 
                   16326: =item
                   16327: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16328: 
                   16329: =item
                   16330: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16331: 
                   16332: =item 
                   16333: $alternateRoot - path to prepend in place of path from $uri.
                   16334: 
                   16335: =back
                   16336: 
                   16337: Returns: Array of up to two items.
                   16338: 
                   16339: =over
                   16340: 
                   16341: a reference to an array of files/subdirectories
                   16342: 
                   16343: =over
                   16344: 
                   16345: Each element in the array of files/subdirectories is a & separated list of
                   16346: item name and the result of running stat on the item.  If dirlist was requested
                   16347: for a file instead of a directory, the item name will be ''. For a directory 
                   16348: listing, if the item is a metadata file, the element will end &N&M 
                   16349: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16350: default copyright set (1).  
                   16351: 
                   16352: =back
                   16353: 
                   16354: a scalar containing error condition (if encountered).
                   16355: 
                   16356: =over
                   16357: 
                   16358: =item 
                   16359: no_host (no homeserver identified for $username:$domain).
                   16360: 
                   16361: =item 
                   16362: no_such_host (server contacted for listing not identified as valid host).
                   16363: 
                   16364: =item 
                   16365: con_lost (connection to remote server failed).
                   16366: 
                   16367: =item 
                   16368: refused (invalid $username:$domain received on lond side).
                   16369: 
                   16370: =item 
                   16371: no_such_dir (directory at specified path on lond side does not exist). 
                   16372: 
                   16373: =item 
                   16374: empty (directory at specified path on lond side is empty).
                   16375: 
                   16376: =over
                   16377: 
                   16378: This is currently not encountered because the &ls3, &ls2, 
                   16379: &ls (_handler) routines on the lond side do not filter out
                   16380: . and .. from a directory listing. 
                   16381: 
                   16382: =back
                   16383: 
                   16384: =back
                   16385: 
                   16386: =back
1.191     harris41 16387: 
                   16388: =item *
                   16389: 
1.243     albertel 16390: spareserver() : find server with least workload from spare.tab
                   16391: 
1.986     foxr     16392: 
                   16393: =item *
                   16394: 
                   16395: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16396: if there is no corresponding loncapa host.
                   16397: 
1.243     albertel 16398: =back
                   16399: 
1.986     foxr     16400: 
1.243     albertel 16401: =head2 Apache Request
                   16402: 
                   16403: =over 4
1.191     harris41 16404: 
                   16405: =item *
                   16406: 
1.243     albertel 16407: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16408: localhost, posts hash
                   16409: 
                   16410: =back
                   16411: 
                   16412: =head2 Data to String to Data
                   16413: 
                   16414: =over 4
1.191     harris41 16415: 
                   16416: =item *
                   16417: 
1.243     albertel 16418: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16419: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16420: 
                   16421: =item *
                   16422: 
1.243     albertel 16423: hashref2str($hashref) : convert a hashref into a string complete with
                   16424: escaping and '=' and '&' separators, supports elements that are
                   16425: arrayrefs and hashrefs
1.191     harris41 16426: 
                   16427: =item *
                   16428: 
1.243     albertel 16429: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16430: with escaping and '&' separators, supports elements that are arrayrefs
                   16431: and hashrefs
1.191     harris41 16432: 
                   16433: =item *
                   16434: 
1.243     albertel 16435: str2hash($string) : convert string to hash using unescaping and
                   16436: splitting on '=' and '&', supports elements that are arrayrefs and
                   16437: hashrefs
1.191     harris41 16438: 
                   16439: =item *
                   16440: 
1.243     albertel 16441: str2array($string) : convert string to hash using unescaping and
                   16442: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16443: 
                   16444: =back
                   16445: 
                   16446: =head2 Logging Routines
                   16447: 
                   16448: 
                   16449: These routines allow one to make log messages in the lonnet.log and
                   16450: lonnet.perm logfiles.
1.191     harris41 16451: 
1.1119    foxr     16452: =over 4
                   16453: 
1.191     harris41 16454: =item *
                   16455: 
1.243     albertel 16456: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16457: 
                   16458: =item *
                   16459: 
1.243     albertel 16460: logthis() : append message to the normal lonnet.log file, it gets
                   16461: preiodically rolled over and deleted.
1.191     harris41 16462: 
                   16463: =item *
                   16464: 
1.243     albertel 16465: logperm() : append a permanent message to lonnet.perm.log, this log
                   16466: file never gets deleted by any automated portion of the system, only
                   16467: messages of critical importance should go in here.
                   16468: 
1.1119    foxr     16469: 
1.243     albertel 16470: =back
                   16471: 
                   16472: =head2 General File Helper Routines
                   16473: 
                   16474: =over 4
1.191     harris41 16475: 
                   16476: =item *
                   16477: 
1.481     raeburn  16478: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16479: (a) files in /uploaded
                   16480:   (i) If a local copy of the file exists - 
                   16481:       compares modification date of local copy with last-modified date for 
                   16482:       definitive version stored on home server for course. If local copy is 
                   16483:       stale, requests a new version from the home server and stores it. 
                   16484:       If the original has been removed from the home server, then local copy 
                   16485:       is unlinked.
                   16486:   (ii) If local copy does not exist -
                   16487:       requests the file from the home server and stores it. 
                   16488:   
                   16489:   If $caller is 'uploadrep':  
                   16490:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16491:     for request for files originally uploaded via DOCS. 
                   16492:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16493:   
                   16494:   Otherwise:
                   16495:      This indicates a call from the content generation phase of the request.
                   16496:      -  returns the entire contents of the file or -1.
                   16497:      
                   16498: (b) files in /res
                   16499:    - returns the entire contents of a file or -1; 
                   16500:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16501: 
1.712     albertel 16502: 
                   16503: =item *
                   16504: 
                   16505: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16506:                   reference
                   16507: 
                   16508: returns either a stat() list of data about the file or an empty list
                   16509: if the file doesn't exist or couldn't find out about it (connection
                   16510: problems or user unknown)
                   16511: 
1.191     harris41 16512: =item *
                   16513: 
1.243     albertel 16514: filelocation($dir,$file) : returns file system location of a file
                   16515: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16516: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16517: and a file of ../bob will become /a/bob)
1.191     harris41 16518: 
                   16519: =item *
                   16520: 
                   16521: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16522: filelocation except for hrefs
                   16523: 
                   16524: =item *
                   16525: 
1.1172.2.49  raeburn  16526: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16527: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16528: 
1.243     albertel 16529: =back
                   16530: 
1.608     albertel 16531: =head2 Usererfile file routines (/uploaded*)
                   16532: 
                   16533: =over 4
                   16534: 
                   16535: =item *
                   16536: 
                   16537: userfileupload(): main rotine for putting a file in a user or course's
                   16538:                   filespace, arguments are,
                   16539: 
1.620     albertel 16540:  formname - required - this is the name of the element in $env where the
1.608     albertel 16541:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16542:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16543:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16544:  context - if coursedoc, store the file in the course of the active role
                   16545:              of the current user; 
                   16546:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16547:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16548:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16549:          if undefined, it will be placed in "unknown"
                   16550: 
                   16551:  (This routine calls clean_filename() to remove any dangerous
                   16552:  characters from the filename, and then calls finuserfileupload() to
                   16553:  complete the transaction)
                   16554: 
                   16555:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16556:  and /adm/notfound.html if unsuccessful
                   16557: 
                   16558: =item *
                   16559: 
                   16560: clean_filename(): routine for cleaing a filename up for storage in
                   16561:                  userfile space, argument is:
                   16562: 
                   16563:  filename - proposed filename
                   16564: 
                   16565: returns: the new clean filename
                   16566: 
                   16567: =item *
                   16568: 
1.1090    raeburn  16569: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16570: userspace, probably shouldn't be called directly
                   16571: 
                   16572:   docuname: username or courseid of destination for the file
                   16573:   docudom: domain of user/course of destination for the file
                   16574:   formname: same as for userfileupload()
1.1090    raeburn  16575:   fname: filename (including subdirectories) for the file
                   16576:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16577:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16578:   allfiles: reference to hash used to store objects found by parser
                   16579:   codebase: reference to hash used for codebases of java objects found by parser
                   16580:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16581:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16582:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16583:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16584:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16585:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16586:   mimetype: reference to scalar to accommodate mime type determined
                   16587:             from File::MMagic if $parser = parse.
1.608     albertel 16588: 
                   16589:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16590:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16591:  was 'overwrite').
                   16592:  
1.608     albertel 16593: 
                   16594: =item *
                   16595: 
                   16596: renameuserfile(): renames an existing userfile to a new name
                   16597: 
                   16598:   Args:
                   16599:    docuname: username or courseid of destination for the file
                   16600:    docudom: domain of user/course of destination for the file
                   16601:    old: current file name (including any subdirs under userfiles)
                   16602:    new: desired file name (including any subdirs under userfiles)
                   16603: 
                   16604: =item *
                   16605: 
                   16606: mkdiruserfile(): creates a directory is a userfiles dir
                   16607: 
                   16608:   Args:
                   16609:    docuname: username or courseid of destination for the file
                   16610:    docudom: domain of user/course of destination for the file
                   16611:    dir: dir to create (including any subdirs under userfiles)
                   16612: 
                   16613: =item *
                   16614: 
                   16615: removeuserfile(): removes a file that exists in userfiles
                   16616: 
                   16617:   Args:
                   16618:    docuname: username or courseid of destination for the file
                   16619:    docudom: domain of user/course of destination for the file
                   16620:    fname: filname to delete (including any subdirs under userfiles)
                   16621: 
                   16622: =item *
                   16623: 
                   16624: removeuploadedurl(): convience function for removeuserfile()
                   16625: 
                   16626:   Args:
                   16627:    url:  a full /uploaded/... url to delete
                   16628: 
1.747     albertel 16629: =item * 
                   16630: 
                   16631: get_portfile_permissions():
                   16632:   Args:
                   16633:     domain: domain of user or course contain the portfolio files
                   16634:     user: name of user or num of course contain the portfolio files
                   16635:   Returns:
                   16636:     hashref of a dump of the proper file_permissions.db
                   16637:    
                   16638: 
                   16639: =item * 
                   16640: 
                   16641: get_access_controls():
                   16642: 
                   16643: Args:
                   16644:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16645:   group: (optional) the group you want the files associated with
                   16646:   file: (optional) the file you want access info on
                   16647: 
                   16648: Returns:
1.749     raeburn  16649:     a hash (keys are file names) of hashes containing
                   16650:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16651:         values are XML containing access control settings (see below) 
1.747     albertel 16652: 
                   16653: Internal notes:
                   16654: 
1.749     raeburn  16655:  access controls are stored in file_permissions.db as key=value pairs.
                   16656:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16657:         where scope -> public,guest,course,group,domains or users.
                   16658:               end -> UNIX time for end of access (0 -> no end date)
                   16659:               start -> UNIX time for start of access
                   16660: 
                   16661:     value -> XML description of access control
                   16662:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16663:             <start></start>
                   16664:             <end></end>
                   16665: 
                   16666:             <password></password>  for scope type = guest
                   16667: 
                   16668:             <domain></domain>     for scope type = course or group
                   16669:             <number></number>
                   16670:             <roles id="">
                   16671:              <role></role>
                   16672:              <access></access>
                   16673:              <section></section>
                   16674:              <group></group>
                   16675:             </roles>
                   16676: 
                   16677:             <dom></dom>         for scope type = domains
                   16678: 
                   16679:             <users>             for scope type = users
                   16680:              <user>
                   16681:               <uname></uname>
                   16682:               <udom></udom>
                   16683:              </user>
                   16684:             </users>
                   16685:            </scope> 
                   16686:               
                   16687:  Access data is also aggregated for each file in an additional key=value pair:
                   16688:  key -> path to file/file_name\0accesscontrol 
                   16689:  value -> reference to hash
                   16690:           hash contains key = value pairs
                   16691:           where key = uniqueID:scope_end_start
                   16692:                 value = UNIX time record was last updated
                   16693: 
                   16694:           Used to improve speed of look-ups of access controls for each file.  
                   16695:  
                   16696:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16697: 
1.1172.2.13  raeburn  16698: =item *
                   16699: 
1.749     raeburn  16700: modify_access_controls():
                   16701: 
                   16702: Modifies access controls for a portfolio file
                   16703: Args
                   16704: 1. file name
                   16705: 2. reference to hash of required changes,
                   16706: 3. domain
                   16707: 4. username
                   16708:   where domain,username are the domain of the portfolio owner 
                   16709:   (either a user or a course) 
                   16710: 
                   16711: Returns:
                   16712: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16713: 2. result of deletions ('ok' or 'error', with error message).
                   16714: 3. reference to hash of any new or updated access controls.
                   16715: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16716:    key = integer (inbound ID)
1.1172.2.13  raeburn  16717:    value = uniqueID
                   16718: 
                   16719: =item *
                   16720: 
                   16721: get_timebased_id():
                   16722: 
                   16723: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16724: course via the Course Editor (e.g., folders, composite pages,
                   16725: group bulletin boards).
                   16726: 
                   16727: Args: (first three required; six others optional)
                   16728: 
                   16729: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16730:    docssequence, or name of group
                   16731: 
                   16732: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16733:    e.g., num, boardids
                   16734: 
                   16735: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16736:    file will be named nohist_namespace.db
                   16737: 
                   16738: 4. cdom: domain of course; default is current course domain from %env
                   16739: 
                   16740: 5. cnum: course number; default is current course number from %env
                   16741: 
                   16742: 6. idtype: set to concat if an additional digit is to be appended to the
                   16743:    unix timestamp to form the suffix, if the plain timestamp is already
                   16744:    in use.  Default is to not do this, but simply increment the unix
                   16745:    timestamp by 1 until a unique key is obtained.
                   16746: 
                   16747: 7. who: holder of locking key; defaults to user:domain for user.
                   16748: 
                   16749: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16750:    retrying); default is 3.
                   16751: 
                   16752: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16753: 
                   16754: Returns:
                   16755: 
                   16756: 1. suffix obtained (numeric)
                   16757: 
                   16758: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16759: 
                   16760: 3. error: contains (localized) error message if an error occurred.
                   16761: 
1.747     albertel 16762: 
1.608     albertel 16763: =back
                   16764: 
1.243     albertel 16765: =head2 HTTP Helper Routines
                   16766: 
                   16767: =over 4
                   16768: 
1.191     harris41 16769: =item *
                   16770: 
                   16771: escape() : unpack non-word characters into CGI-compatible hex codes
                   16772: 
                   16773: =item *
                   16774: 
                   16775: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16776: 
1.243     albertel 16777: =back
                   16778: 
                   16779: =head1 PRIVATE SUBROUTINES
                   16780: 
                   16781: =head2 Underlying communication routines (Shouldn't call)
                   16782: 
                   16783: =over 4
                   16784: 
                   16785: =item *
                   16786: 
                   16787: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16788: 
                   16789: =item *
                   16790: 
                   16791: reply() : uses subreply to send a message to remote machine, logs all failures
                   16792: 
                   16793: =item *
                   16794: 
                   16795: critical() : passes a critical message to another server; if cannot
                   16796: get through then place message in connection buffer directory and
                   16797: returns con_delayed, if incapable of saving message, returns
                   16798: con_failed
                   16799: 
                   16800: =item *
                   16801: 
                   16802: reconlonc() : tries to reconnect lonc client processes.
                   16803: 
                   16804: =back
                   16805: 
                   16806: =head2 Resource Access Logging
                   16807: 
                   16808: =over 4
                   16809: 
                   16810: =item *
                   16811: 
                   16812: flushcourselogs() : flush (save) buffer logs and access logs
                   16813: 
                   16814: =item *
                   16815: 
                   16816: courselog($what) : save message for course in hash
                   16817: 
                   16818: =item *
                   16819: 
                   16820: courseacclog($what) : save message for course using &courselog().  Perform
                   16821: special processing for specific resource types (problems, exams, quizzes, etc).
                   16822: 
1.191     harris41 16823: =item *
                   16824: 
                   16825: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16826: as a PerlChildExitHandler
1.243     albertel 16827: 
                   16828: =back
                   16829: 
                   16830: =head2 Other
                   16831: 
                   16832: =over 4
                   16833: 
                   16834: =item *
                   16835: 
                   16836: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16837: 
                   16838: =back
                   16839: 
                   16840: =cut
1.877     foxr     16841: 

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