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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .11(raeb    4:-23): # $Id: lonnet.pm,v 1.1172.2.146.2.10 2023/01/22 17:32: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 = {
1.1172.2.146.  .10(raeb 2642:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2643:                                 codes => \%codes,
                   2644:                                 codetitles => \@codetitles,
                   2645:                                 cat_titles => \%cat_titles,
                   2646:                                 cat_order => \%cat_order,
                   2647:                             };
                   2648:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2649:             }
                   2650:         }
                   2651:     }
                   2652:     return $instcats;
                   2653: }
                   2654: 
                   2655: sub retrieve_instcodes {
                   2656:     my ($coursecodes,$dom) = @_;
                   2657:     my $totcodes;
                   2658:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2659:     foreach my $course (keys(%courses)) {
                   2660:         if (ref($courses{$course}) eq 'HASH') {
                   2661:             if ($courses{$course}{'inst_code'} ne '') {
                   2662:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2663:                 $totcodes ++;
                   2664:             }
                   2665:         }
                   2666:     }
                   2667:     return $totcodes;
                   2668: }
                   2669: 
1.1172.2.113  raeburn  2670: # --------------------------------------------- Get domain config for passwords
                   2671: 
                   2672: sub get_passwdconf {
                   2673:     my ($dom) = @_;
                   2674:     my (%passwdconf,$gotconf,$lookup);
                   2675:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2676:     if (defined($cached)) {
                   2677:         if (ref($result) eq 'HASH') {
                   2678:             %passwdconf = %{$result};
                   2679:             $gotconf = 1;
                   2680:         }
                   2681:     }
                   2682:     unless ($gotconf) {
                   2683:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2684:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2685:             %passwdconf = %{$domconfig{'passwords'}};
                   2686:         }
                   2687:         my $cachetime = 24*60*60;
                   2688:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2689:     }
                   2690:     return %passwdconf;
                   2691: }
                   2692: 
1.1172.2.146.  .1(raebu 2693:22): sub course_portal_url {
                   2694:22):     my ($cnum,$cdom,$r) = @_;
                   2695:22):     my $chome = &homeserver($cnum,$cdom);
                   2696:22):     my $hostname = &hostname($chome);
                   2697:22):     my $protocol = $protocol{$chome};
                   2698:22):     $protocol = 'http' if ($protocol ne 'https');
                   2699:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2700:22):     my $firsturl;
                   2701:22):     if ($domdefaults{'portal_def'}) {
                   2702:22):         $firsturl = $domdefaults{'portal_def'};
                   2703:22):     } else {
                   2704:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2705:22):         $hostname = $alias if ($alias ne '');
                   2706:22):         $firsturl = $protocol.'://'.$hostname;
                   2707:22):     }
                   2708:22):     return $firsturl;
                   2709:22): }
                   2710:22): 
1.344     www      2711: # --------------------------------------------------- Assign a key to a student
                   2712: 
                   2713: sub assign_access_key {
1.364     www      2714: #
                   2715: # a valid key looks like uname:udom#comments
                   2716: # comments are being appended
                   2717: #
1.498     www      2718:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2719:     $kdom=
1.620     albertel 2720:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2721:     $knum=
1.620     albertel 2722:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2723:     $cdom=
1.620     albertel 2724:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2725:     $cnum=
1.620     albertel 2726:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2727:     $udom=$env{'user.name'} unless (defined($udom));
                   2728:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2729:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2730:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2731:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2732:                                                   # assigned to this person
                   2733:                                                   # - this should not happen,
1.345     www      2734:                                                   # unless something went wrong
                   2735:                                                   # the first time around
                   2736: # ready to assign
1.364     www      2737:         $logentry=$1.'; '.$logentry;
1.496     www      2738:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2739:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2740: # key now belongs to user
1.346     www      2741: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2742:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2743:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2744:                 return 'ok';
                   2745:             } else {
                   2746:                 return 
                   2747:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2748: 	    }
                   2749:         } else {
                   2750:             return 'error: Could not assign key, try again later.';
                   2751:         }
1.364     www      2752:     } elsif (!$existing{$ckey}) {
1.345     www      2753: # the key does not exist
                   2754: 	return 'error: The key does not exist';
                   2755:     } else {
                   2756: # the key is somebody else's
                   2757: 	return 'error: The key is already in use';
                   2758:     }
1.344     www      2759: }
                   2760: 
1.364     www      2761: # ------------------------------------------ put an additional comment on a key
                   2762: 
                   2763: sub comment_access_key {
                   2764: #
                   2765: # a valid key looks like uname:udom#comments
                   2766: # comments are being appended
                   2767: #
                   2768:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2769:     $cdom=
1.620     albertel 2770:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2771:     $cnum=
1.620     albertel 2772:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2773:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2774:     if ($existing{$ckey}) {
                   2775:         $existing{$ckey}.='; '.$logentry;
                   2776: # ready to assign
1.367     www      2777:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2778:                                                  $cdom,$cnum) eq 'ok') {
                   2779: 	    return 'ok';
                   2780:         } else {
                   2781: 	    return 'error: Count not store comment.';
                   2782:         }
                   2783:     } else {
                   2784: # the key does not exist
                   2785: 	return 'error: The key does not exist';
                   2786:     }
                   2787: }
                   2788: 
1.344     www      2789: # ------------------------------------------------------ Generate a set of keys
                   2790: 
                   2791: sub generate_access_keys {
1.364     www      2792:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2793:     $cdom=
1.620     albertel 2794:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2795:     $cnum=
1.620     albertel 2796:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2797:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2798:     unless (($cdom) && ($cnum)) { return 0; }
                   2799:     if ($number>10000) { return 0; }
                   2800:     sleep(2); # make sure don't get same seed twice
                   2801:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2802:     my $total=0;
                   2803:     for (my $i=1;$i<=$number;$i++) {
                   2804:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2805:                   sprintf("%lx",int(100000*rand)).'-'.
                   2806:                   sprintf("%lx",int(100000*rand));
                   2807:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2808:        $newkey=~s/0/h/g; # and also 0 and O
                   2809:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2810:        if ($existing{$newkey}) {
                   2811:            $i--;
                   2812:        } else {
1.364     www      2813: 	  if (&put('accesskeys',
                   2814:               { $newkey => '# generated '.localtime().
1.620     albertel 2815:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2816:                            '; '.$logentry },
                   2817: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2818:               $total++;
                   2819: 	  }
                   2820:        }
                   2821:     }
1.620     albertel 2822:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2823:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2824:     return $total;
                   2825: }
                   2826: 
                   2827: # ------------------------------------------------------- Validate an accesskey
                   2828: 
                   2829: sub validate_access_key {
                   2830:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2831:     $cdom=
1.620     albertel 2832:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2833:     $cnum=
1.620     albertel 2834:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2835:     $udom=$env{'user.domain'} unless (defined($udom));
                   2836:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2837:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2838:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2839: }
                   2840: 
                   2841: # ------------------------------------- Find the section of student in a course
1.652     albertel 2842: sub devalidate_getsection_cache {
                   2843:     my ($udom,$unam,$courseid)=@_;
                   2844:     my $hashid="$udom:$unam:$courseid";
                   2845:     &devalidate_cache_new('getsection',$hashid);
                   2846: }
1.298     matthew  2847: 
1.815     albertel 2848: sub courseid_to_courseurl {
                   2849:     my ($courseid) = @_;
                   2850:     #already url style courseid
                   2851:     return $courseid if ($courseid =~ m{^/});
                   2852: 
                   2853:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2854: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2855: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2856: 	return "/$cdom/$cnum";
                   2857:     }
                   2858: 
                   2859:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2860:     if (exists($courseinfo{'num'})) {
                   2861: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2862:     }
                   2863: 
                   2864:     return undef;
                   2865: }
                   2866: 
1.298     matthew  2867: sub getsection {
                   2868:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2869:     my $cachetime=1800;
1.551     albertel 2870: 
                   2871:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2872:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2873:     if (defined($cached)) { return $result; }
                   2874: 
1.298     matthew  2875:     my %Pending; 
                   2876:     my %Expired;
                   2877:     #
                   2878:     # Each role can either have not started yet (pending), be active, 
                   2879:     #    or have expired.
                   2880:     #
                   2881:     # If there is an active role, we are done.
                   2882:     #
                   2883:     # If there is more than one role which has not started yet, 
                   2884:     #     choose the one which will start sooner
                   2885:     # If there is one role which has not started yet, return it.
                   2886:     #
                   2887:     # If there is more than one expired role, choose the one which ended last.
                   2888:     # If there is a role which has expired, return it.
                   2889:     #
1.815     albertel 2890:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2891:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2892:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2893:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2894:         my $section=$1;
                   2895:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2896:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2897:         my $now=time;
1.548     albertel 2898:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2899:             $Expired{$end}=$section;
                   2900:             next;
                   2901:         }
1.548     albertel 2902:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2903:             $Pending{$start}=$section;
                   2904:             next;
                   2905:         }
1.599     albertel 2906:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2907:     }
                   2908:     #
                   2909:     # Presumedly there will be few matching roles from the above
                   2910:     # loop and the sorting time will be negligible.
                   2911:     if (scalar(keys(%Pending))) {
                   2912:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2913:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2914:     } 
                   2915:     if (scalar(keys(%Expired))) {
                   2916:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2917:         my $time = pop(@sorted);
1.599     albertel 2918:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2919:     }
1.599     albertel 2920:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2921: }
1.70      www      2922: 
1.599     albertel 2923: sub save_cache {
                   2924:     &purge_remembered();
1.722     albertel 2925:     #&Apache::loncommon::validate_page();
1.620     albertel 2926:     undef(%env);
1.780     albertel 2927:     undef($env_loaded);
1.599     albertel 2928: }
1.452     albertel 2929: 
1.599     albertel 2930: my $to_remember=-1;
                   2931: my %remembered;
                   2932: my %accessed;
                   2933: my $kicks=0;
                   2934: my $hits=0;
1.849     albertel 2935: sub make_key {
                   2936:     my ($name,$id) = @_;
1.872     albertel 2937:     if (length($id) > 65 
                   2938: 	&& length(&escape($id)) > 200) {
                   2939: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2940:     }
1.849     albertel 2941:     return &escape($name.':'.$id);
                   2942: }
                   2943: 
1.599     albertel 2944: sub devalidate_cache_new {
                   2945:     my ($name,$id,$debug) = @_;
                   2946:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2947:     my $remembered_id=$name.':'.$id;
1.849     albertel 2948:     $id=&make_key($name,$id);
1.599     albertel 2949:     $memcache->delete($id);
1.1172.2.81  raeburn  2950:     delete($remembered{$remembered_id});
                   2951:     delete($accessed{$remembered_id});
1.599     albertel 2952: }
                   2953: 
                   2954: sub is_cached_new {
                   2955:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2956:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2957:                                      # keys in %remembered hash, which persists for
                   2958:                                      # duration of request (no restriction on key length).
                   2959:     if (exists($remembered{$remembered_id})) {
                   2960: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2961: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2962: 	$hits++;
1.1172.2.81  raeburn  2963: 	return ($remembered{$remembered_id},1);
1.599     albertel 2964:     }
1.1172.2.81  raeburn  2965:     $id=&make_key($name,$id);
1.599     albertel 2966:     my $value = $memcache->get($id);
                   2967:     if (!(defined($value))) {
                   2968: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2969: 	return (undef,undef);
1.416     albertel 2970:     }
1.599     albertel 2971:     if ($value eq '__undef__') {
                   2972: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2973: 	$value=undef;
                   2974:     }
1.1172.2.81  raeburn  2975:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2976:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2977:     return ($value,1);
                   2978: }
                   2979: 
                   2980: sub do_cache_new {
                   2981:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2982:     my $remembered_id=$name.':'.$id;
1.849     albertel 2983:     $id=&make_key($name,$id);
1.599     albertel 2984:     my $setvalue=$value;
                   2985:     if (!defined($setvalue)) {
                   2986: 	$setvalue='__undef__';
                   2987:     }
1.623     albertel 2988:     if (!defined($time) ) {
                   2989: 	$time=600;
                   2990:     }
1.599     albertel 2991:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2992:     my $result = $memcache->set($id,$setvalue,$time);
                   2993:     if (! $result) {
1.872     albertel 2994: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2995: 	$memcache->disconnect_all();
1.872     albertel 2996:     }
1.600     albertel 2997:     # need to make a copy of $value
1.1172.2.81  raeburn  2998:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2999:     return $value;
                   3000: }
                   3001: 
                   3002: sub make_room {
1.1172.2.81  raeburn  3003:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3004: 
1.1172.2.81  raeburn  3005:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3006:                                     : $value;
1.599     albertel 3007:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3008:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3009:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3010:     my $to_kick;
                   3011:     my $max_time=0;
                   3012:     foreach my $other (keys(%accessed)) {
                   3013: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3014: 	    $to_kick=$other;
                   3015: 	    $max_time=&tv_interval($accessed{$other});
                   3016: 	}
                   3017:     }
                   3018:     delete($remembered{$to_kick});
                   3019:     delete($accessed{$to_kick});
                   3020:     $kicks++;
                   3021:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3022:     return;
                   3023: }
                   3024: 
1.599     albertel 3025: sub purge_remembered {
1.604     albertel 3026:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3027:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3028:     undef(%remembered);
                   3029:     undef(%accessed);
1.428     albertel 3030: }
1.70      www      3031: # ------------------------------------- Read an entry from a user's environment
                   3032: 
                   3033: sub userenvironment {
                   3034:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3035:     my $items;
                   3036:     foreach my $item (@what) {
                   3037:         $items.=&escape($item).'&';
                   3038:     }
                   3039:     $items=~s/\&$//;
1.70      www      3040:     my %returnhash=();
1.1009    raeburn  3041:     my $uhome = &homeserver($unam,$udom);
                   3042:     unless ($uhome eq 'no_host') {
                   3043:         my @answer=split(/\&/, 
                   3044:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3045:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3046:             return %returnhash;
                   3047:         }
1.1009    raeburn  3048:         my $i;
                   3049:         for ($i=0;$i<=$#what;$i++) {
                   3050: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3051:         }
1.70      www      3052:     }
                   3053:     return %returnhash;
1.1       albertel 3054: }
                   3055: 
1.617     albertel 3056: # ---------------------------------------------------------- Get a studentphoto
                   3057: sub studentphoto {
                   3058:     my ($udom,$unam,$ext) = @_;
                   3059:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3060:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3061:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3062:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3063:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3064:             } else {
                   3065:                 my ($result,$perm_reqd)=
1.707     albertel 3066: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3067:                 if ($result eq 'ok') {
                   3068:                     if (!($perm_reqd eq 'yes')) {
                   3069:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3070:                     }
                   3071:                 }
                   3072:             }
                   3073:         }
                   3074:     } else {
                   3075:         my ($result,$perm_reqd) = 
1.707     albertel 3076: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3077:         if ($result eq 'ok') {
                   3078:             if (!($perm_reqd eq 'yes')) {
                   3079:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3080:             }
                   3081:         }
                   3082:     }
                   3083:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3084: }
                   3085: 
                   3086: sub retrievestudentphoto {
                   3087:     my ($udom,$unam,$ext,$type) = @_;
                   3088:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3089:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3090:     if ($ret eq 'ok') {
                   3091:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3092:         if ($type eq 'thumbnail') {
                   3093:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3094:         }
                   3095:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3096:         return $tokenurl;
                   3097:     } else {
                   3098:         if ($type eq 'thumbnail') {
                   3099:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3100:         } else { 
                   3101:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3102:         }
1.617     albertel 3103:     }
                   3104: }
                   3105: 
1.263     www      3106: # -------------------------------------------------------------------- New chat
                   3107: 
                   3108: sub chatsend {
1.724     raeburn  3109:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3110:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3111:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3112:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3113:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3114: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3115: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3116: }
                   3117: 
                   3118: # ------------------------------------------ Find current version of a resource
                   3119: 
                   3120: sub getversion {
                   3121:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3122:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3123:     return &currentversion(&filelocation('',$fname));
                   3124: }
                   3125: 
                   3126: sub currentversion {
                   3127:     my $fname=shift;
                   3128:     my $author=$fname;
                   3129:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3130:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3131:     my $home=&homeserver($uname,$udom);
1.292     www      3132:     if ($home eq 'no_host') { 
                   3133:         return -1; 
                   3134:     }
1.1112    www      3135:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3136:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3137: 	return -1;
                   3138:     }
1.1112    www      3139:     return $answer;
1.263     www      3140: }
                   3141: 
1.1111    www      3142: #
                   3143: # Return special version number of resource if set by override, empty otherwise
                   3144: #
                   3145: sub usedversion {
                   3146:     my $fname=shift;
                   3147:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3148:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3149:     if ($urlversion) { return $urlversion; }
                   3150:     return '';
                   3151: }
                   3152: 
1.1       albertel 3153: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3154: 
1.1       albertel 3155: sub subscribe {
                   3156:     my $fname=shift;
1.761     raeburn  3157:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3158:     $fname=~s/[\n\r]//g;
1.1       albertel 3159:     my $author=$fname;
                   3160:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3161:     my ($udom,$uname)=split(/\//,$author);
                   3162:     my $home=homeserver($uname,$udom);
1.335     albertel 3163:     if ($home eq 'no_host') {
                   3164:         return 'not_found';
1.1       albertel 3165:     }
                   3166:     my $answer=reply("sub:$fname",$home);
1.64      www      3167:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3168: 	$answer.=' by '.$home;
                   3169:     }
1.1       albertel 3170:     return $answer;
                   3171: }
                   3172:     
1.8       www      3173: # -------------------------------------------------------------- Replicate file
                   3174: 
                   3175: sub repcopy {
                   3176:     my $filename=shift;
1.23      www      3177:     $filename=~s/\/+/\//g;
1.1142    raeburn  3178:     my $londocroot = $perlvar{'lonDocRoot'};
                   3179:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3180:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3181:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3182: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3183: 	return &repcopy_userfile($filename);
                   3184:     }
1.532     albertel 3185:     $filename=~s/[\n\r]//g;
1.8       www      3186:     my $transname="$filename.in.transfer";
1.828     www      3187: # FIXME: this should flock
1.607     raeburn  3188:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3189:     my $remoteurl=subscribe($filename);
1.64      www      3190:     if ($remoteurl =~ /^con_lost by/) {
                   3191: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3192:            return 'unavailable';
1.8       www      3193:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3194: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3195: 	   return 'not_found';
1.64      www      3196:     } elsif ($remoteurl =~ /^rejected by/) {
                   3197: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3198:            return 'forbidden';
1.20      www      3199:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3200:            return 'ok';
1.8       www      3201:     } else {
1.290     www      3202:         my $author=$filename;
                   3203:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3204:         my ($udom,$uname)=split(/\//,$author);
                   3205:         my $home=homeserver($uname,$udom);
                   3206:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3207:            my @parts=split(/\//,$filename);
                   3208:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3209:            if ($path ne "$londocroot/res") {
1.8       www      3210:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3211: 	       return 'bad_request';
1.8       www      3212:            }
                   3213:            my $count;
                   3214:            for ($count=5;$count<$#parts;$count++) {
                   3215:                $path.="/$parts[$count]";
                   3216:                if ((-e $path)!=1) {
                   3217: 		   mkdir($path,0777);
                   3218:                }
                   3219:            }
                   3220:            my $ua=new LWP::UserAgent;
                   3221:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3222:            my $response=$ua->request($request,$transname);
                   3223:            if ($response->is_error()) {
                   3224: 	       unlink($transname);
                   3225:                my $message=$response->status_line;
1.672     albertel 3226:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3227:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3228:                return 'unavailable';
1.8       www      3229:            } else {
1.16      www      3230: 	       if ($remoteurl!~/\.meta$/) {
                   3231:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3232:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3233:                   if ($mresponse->is_error()) {
                   3234: 		      unlink($filename.'.meta');
                   3235:                       &logthis(
1.672     albertel 3236:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3237:                   }
                   3238: 	       }
1.8       www      3239:                rename($transname,$filename);
1.607     raeburn  3240:                return 'ok';
1.8       www      3241:            }
1.290     www      3242:        }
1.8       www      3243:     }
1.330     www      3244: }
                   3245: 
1.1172.2.124  raeburn  3246: # ------------------------------------------------- Unsubscribe from a resource
                   3247: 
                   3248: sub unsubscribe {
                   3249:     my ($fname) = @_;
                   3250:     my $answer;
                   3251:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3252:     $fname=~s/[\n\r]//g;
                   3253:     my $author=$fname;
                   3254:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3255:     my ($udom,$uname)=split(/\//,$author);
                   3256:     my $home=homeserver($uname,$udom);
                   3257:     if ($home eq 'no_host') {
                   3258:         $answer = 'no_host';
                   3259:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3260:         $answer = 'home';
                   3261:     } else {
1.1172.2.125  raeburn  3262:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3263:     }
                   3264:     return $answer;
                   3265: }
                   3266: 
1.330     www      3267: # ------------------------------------------------ Get server side include body
                   3268: sub ssi_body {
1.381     albertel 3269:     my ($filelink,%form)=@_;
1.606     matthew  3270:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3271:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3272:     }
1.953     www      3273:     my $output='';
                   3274:     my $response;
1.980     raeburn  3275:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3276:        ($output,$response)=&externalssi($filelink);
1.953     www      3277:     } else {
1.1004    droeschl 3278:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3279:        $filelink .= 'inhibitmenu=yes';
1.953     www      3280:        ($output,$response)=&ssi($filelink,%form);
                   3281:     }
1.778     albertel 3282:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3283:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3284:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3285:     if (wantarray) {
                   3286:         return ($output, $response);
                   3287:     } else {
                   3288:         return $output;
                   3289:     }
1.8       www      3290: }
                   3291: 
1.15      www      3292: # --------------------------------------------------------- Server Side Include
                   3293: 
1.782     albertel 3294: sub absolute_url {
1.1172.2.145  raeburn  3295:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3296:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3297:     if ($host_name eq '') {
                   3298: 	$host_name = $ENV{'SERVER_NAME'};
                   3299:     }
1.1172.2.145  raeburn  3300:     if ($unalias) {
                   3301:         my $alias = &get_proxy_alias();
                   3302:         if ($alias eq $host_name) {
                   3303:             my $lonhost = $perlvar{'lonHostID'};
                   3304:             my $hostname = &hostname($lonhost);
                   3305:             my $lcproto;
                   3306:             if (($keep_proto) || ($hostname eq '')) {
                   3307:                 $lcproto = $protocol;
                   3308:             } else {
                   3309:                 $lcproto = $protocol{$lonhost};
                   3310:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3311:                 $lcproto .= '://';
                   3312:             }
                   3313:             unless ($hostname eq '') {
                   3314:                 return $lcproto.$hostname;
                   3315:             }
                   3316:         }
                   3317:     } 
1.782     albertel 3318:     return $protocol.$host_name;
                   3319: }
                   3320: 
1.942     foxr     3321: #
                   3322: #   Server side include.
                   3323: # Parameters:
                   3324: #  fn     Possibly encrypted resource name/id.
                   3325: #  form   Hash that describes how the rendering should be done
                   3326: #         and other things.
1.944     foxr     3327: # Returns:
1.950     raeburn  3328: #   Scalar context: The content of the response.
                   3329: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3330: #     
1.15      www      3331: sub ssi {
                   3332: 
1.944     foxr     3333:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3334:     my ($host,$request,$response);
                   3335:     $host = &absolute_url('',1);
1.711     albertel 3336: 
                   3337:     $form{'no_update_last_known'}=1;
1.895     albertel 3338:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3339:     if (%form) {
1.1172.2.145  raeburn  3340:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3341:       $request->content(join('&',map {
                   3342:             my $name = escape($_);
                   3343:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3344:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3345:             : &escape($form{$_}) );
                   3346:         } keys(%form)));
1.23      www      3347:     } else {
1.1172.2.145  raeburn  3348:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3349:     }
                   3350: 
1.15      www      3351:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3352: 
1.1172.2.101  raeburn  3353:     if (($env{'request.course.id'}) &&
                   3354:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3355:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3356:         ($form{'grade_symb'} ne '') &&
                   3357:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3358:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3359:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3360:             my $ua=new LWP::UserAgent;
                   3361:             $ua->local_address('127.0.0.1');
                   3362:             $response = $ua->request($request);
                   3363:         } else {
                   3364:             {
                   3365:                 require LWP::Protocol::http;
                   3366:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3367:                 my $ua=new LWP::UserAgent;
                   3368:                 $response = $ua->request($request);
                   3369:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3370:             }
                   3371:         }
                   3372:     } else {
                   3373:         my $ua=new LWP::UserAgent;
                   3374:         $response = $ua->request($request);
                   3375:     }
1.944     foxr     3376:     if (wantarray) {
1.1172.2.3  raeburn  3377: 	return ($response->content, $response);
1.944     foxr     3378:     } else {
1.1172.2.3  raeburn  3379: 	return $response->content;
1.942     foxr     3380:     }
1.324     www      3381: }
                   3382: 
                   3383: sub externalssi {
                   3384:     my ($url)=@_;
                   3385:     my $ua=new LWP::UserAgent;
                   3386:     my $request=new HTTP::Request('GET',$url);
                   3387:     my $response=$ua->request($request);
1.954     raeburn  3388:     if (wantarray) {
                   3389:         return ($response->content, $response);
                   3390:     } else {
                   3391:         return $response->content;
                   3392:     }
1.15      www      3393: }
1.254     www      3394: 
1.1172.2.98  raeburn  3395: # If the local copy of a replicated resource is outdated, trigger a
                   3396: # connection from the homeserver to flush the delayed queue. If no update
                   3397: # happens, remove local copies of outdated resource (and corresponding
                   3398: # metadata file).
                   3399: 
                   3400: sub remove_stale_resfile {
                   3401:     my ($url) = @_;
                   3402:     my $removed;
                   3403:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3404:         my $audom = $1;
                   3405:         my $auname = $2;
                   3406:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3407:             my $homeserver = &homeserver($auname,$audom);
                   3408:             unless (($homeserver eq 'no_host') ||
                   3409:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3410:                 my $fname = &filelocation('',$url);
                   3411:                 if (-e $fname) {
                   3412:                     my $hostname = &hostname($homeserver);
                   3413:                     if ($hostname) {
1.1172.2.120  raeburn  3414:                         my $protocol = $protocol{$homeserver};
                   3415:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3416:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3417:                         my $ua=new LWP::UserAgent;
                   3418:                         $ua->timeout(5);
1.1172.2.98  raeburn  3419:                         my $request=new HTTP::Request('HEAD',$uri);
                   3420:                         my $response=$ua->request($request);
                   3421:                         if ($response->is_success()) {
                   3422:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3423:                             my $locmodtime = (stat($fname))[9];
                   3424:                             if ($locmodtime < $remmodtime) {
                   3425:                                 my $stale;
                   3426:                                 my $answer = &reply('pong',$homeserver);
                   3427:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3428:                                     sleep(0.2);
                   3429:                                     $locmodtime = (stat($fname))[9];
                   3430:                                     if ($locmodtime < $remmodtime) {
                   3431:                                         my $posstransfer = $fname.'.in.transfer';
                   3432:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3433:                                             $removed = 1;
                   3434:                                         } else {
                   3435:                                             $stale = 1;
                   3436:                                         }
                   3437:                                     } else {
                   3438:                                         $removed = 1;
                   3439:                                     }
                   3440:                                 } else {
                   3441:                                     $stale = 1;
                   3442:                                 }
                   3443:                                 if ($stale) {
1.1172.2.124  raeburn  3444:                                     if (unlink($fname)) {
                   3445:                                         if ($uri!~/\.meta$/) {
                   3446:                                             if (-e $fname.'.meta') {
                   3447:                                                 unlink($fname.'.meta');
                   3448:                                             }
                   3449:                                         }
                   3450:                                         my $unsubresult = &unsubscribe($fname);
                   3451:                                         unless ($unsubresult eq 'ok') {
                   3452:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3453:                                         }
                   3454:                                         $removed = 1;
1.1172.2.98  raeburn  3455:                                     }
                   3456:                                 }
                   3457:                             }
                   3458:                         }
                   3459:                     }
                   3460:                 }
                   3461:             }
                   3462:         }
                   3463:     }
                   3464:     return $removed;
                   3465: }
                   3466: 
1.492     albertel 3467: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3468: 
                   3469: sub allowuploaded {
                   3470:     my ($srcurl,$url)=@_;
                   3471:     $url=&clutter(&declutter($url));
                   3472:     my $dir=$url;
                   3473:     $dir=~s/\/[^\/]+$//;
                   3474:     my %httpref=();
                   3475:     my $httpurl=&hreflocation('',$url);
                   3476:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3477:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3478: }
1.477     raeburn  3479: 
1.1172.2.13  raeburn  3480: #
                   3481: # Determine if the current user should be able to edit a particular resource,
                   3482: # when viewing in course context.
                   3483: # (a) When viewing resource used to determine if "Edit" item is included in
                   3484: #     Functions.
                   3485: # (b) When displaying folder contents in course editor, used to determine if
                   3486: #     "Edit" link will be displayed alongside resource.
                   3487: #
                   3488: #  input: six args -- filename (decluttered), course number, course domain,
                   3489: #                   url, symb (if registered) and group (if this is a group
                   3490: #                   item -- e.g., bulletin board, group page etc.).
                   3491: #  output: array of five scalars --
                   3492: #          $cfile -- url for file editing if editable on current server
                   3493: #          $home -- homeserver of resource (i.e., for author if published,
                   3494: #                                           or course if uploaded.).
                   3495: #          $switchserver --  1 if server switch will be needed.
                   3496: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3497: #          $forceview -- 1 if icon/link should be to go to view mode
                   3498: #
                   3499: 
                   3500: sub can_edit_resource {
                   3501:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3502:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3503: #
                   3504: # For aboutme pages user can only edit his/her own.
                   3505: #
                   3506:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3507:         my ($sdom,$sname) = ($1,$2);
                   3508:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3509:             $home = $env{'user.home'};
                   3510:             $cfile = $resurl;
                   3511:             if ($env{'form.forceedit'}) {
                   3512:                 $forceview = 1;
                   3513:             } else {
                   3514:                 $forceedit = 1;
                   3515:             }
                   3516:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3517:         } else {
                   3518:             return;
                   3519:         }
                   3520:     }
                   3521: 
                   3522:     if ($env{'request.course.id'}) {
                   3523:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3524:         if ($group ne '') {
                   3525: # if this is a group homepage or group bulletin board, check group privs
                   3526:             my $allowed = 0;
                   3527:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3528:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3529:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3530:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3531:                     $allowed = 1;
                   3532:                 }
                   3533:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3534:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3535:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3536:                     $allowed = 1;
                   3537:                 }
                   3538:             }
                   3539:             if ($allowed) {
                   3540:                 $home=&homeserver($cnum,$cdom);
                   3541:                 if ($env{'form.forceedit'}) {
                   3542:                     $forceview = 1;
                   3543:                 } else {
                   3544:                     $forceedit = 1;
                   3545:                 }
                   3546:                 $cfile = $resurl;
                   3547:             } else {
                   3548:                 return;
                   3549:             }
                   3550:         } else {
1.1172.2.15  raeburn  3551:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3552:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3553:                     return;
                   3554:                 }
                   3555:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3556: #
                   3557: # No edit allowed where CC has switched to student role.
                   3558: #
                   3559:                 return;
                   3560:             }
                   3561:         }
                   3562:     }
                   3563: 
                   3564:     if ($file ne '') {
                   3565:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3566:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3567:                 $uploaded = 1;
                   3568:                 $incourse = 1;
                   3569:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3570:                     $cfile = &hreflocation('',$file);
                   3571:                     if ($env{'form.forceedit'}) {
                   3572:                         $forceview = 1;
                   3573:                     } else {
                   3574:                         $forceedit = 1;
                   3575:                     }
                   3576:                 }
                   3577:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3578:                 $incourse = 1;
                   3579:                 if ($env{'form.forceedit'}) {
                   3580:                     $forceview = 1;
                   3581:                 } else {
                   3582:                     $forceedit = 1;
                   3583:                 }
                   3584:                 $cfile = $resurl;
                   3585:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3586:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3587:                     $incourse = 1;
                   3588:                     if ($env{'form.forceedit'}) {
                   3589:                         $forceview = 1;
                   3590:                     } else {
                   3591:                         $forceedit = 1;
                   3592:                     }
                   3593:                     $cfile = $resurl;
                   3594:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3595:                     $incourse = 1;
                   3596:                     $cfile = $resurl.'/smpedit';
                   3597:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3598:                     $incourse = 1;
                   3599:                     if ($env{'form.forceedit'}) {
                   3600:                         $forceview = 1;
                   3601:                     } else {
                   3602:                         $forceedit = 1;
                   3603:                     }
                   3604:                     $cfile = $resurl;
1.1172.2.122  raeburn  3605:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3606:                     my ($map,$id,$res) = &decode_symb($symb);
                   3607:                     if ($map =~ /\.page$/) {
                   3608:                         $incourse = 1;
                   3609:                         if ($env{'form.forceedit'}) {
                   3610:                             $forceview = 1;
                   3611:                             $cfile = $map;
                   3612:                         } else {
                   3613:                             $forceedit = 1;
                   3614:                             $cfile =  '/adm/wrapper'.$resurl;
                   3615:                         }
                   3616:                     }
1.1172.2.146.  .1(raebu 3617:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3618:22):                     $incourse = 1;
                   3619:22):                     if ($env{'form.forceedit'}) {
                   3620:22):                         $forceview = 1;
                   3621:22):                     } else {
                   3622:22):                         $forceedit = 1;
                   3623:22):                     }
                   3624:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3625:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3626:                     $incourse = 1;
                   3627:                     if ($env{'form.forceedit'}) {
                   3628:                         $forceview = 1;
                   3629:                     } else {
                   3630:                         $forceedit = 1;
                   3631:                     }
                   3632:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3633:                 }
                   3634:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3635:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3636:                 if (&is_on_map($template)) {
                   3637:                     $incourse = 1;
                   3638:                     $forceview = 1;
                   3639:                     $cfile = $template;
                   3640:                 }
                   3641:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3642:                 $incourse = 1;
                   3643:                 if ($env{'form.forceedit'}) {
                   3644:                     $forceview = 1;
                   3645:                 } else {
                   3646:                     $forceedit = 1;
                   3647:                 }
                   3648:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3649:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3650:22):                 $incourse = 1;
                   3651:22):                 if ($env{'form.forceedit'}) {
                   3652:22):                     $forceview = 1;
                   3653:22):                 } else {
                   3654:22):                     $forceedit = 1;
                   3655:22):                 }
                   3656:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3657:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3658:                 $incourse = 1;
                   3659:                 $forceview = 1;
                   3660:                 if ($symb) {
                   3661:                     my ($map,$id,$res)=&decode_symb($symb);
                   3662:                     $env{'request.symb'} = $symb;
                   3663:                     $cfile = &clutter($res);
                   3664:                 } else {
                   3665:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3666:22):                     my $escfile = &unescape($cfile);
                   3667:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3668:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3669:22):                     } else {
                   3670:22):                         $escfile =~ s{^http://}{};
                   3671:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3672:22):                     }
1.1172.2.13  raeburn  3673:                 }
1.1172.2.31  raeburn  3674:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3675:                 if ($env{'form.forceedit'}) {
                   3676:                     $forceview = 1;
                   3677:                 } else {
                   3678:                     $forceedit = 1;
                   3679:                 }
                   3680:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3681:             }
                   3682:         }
                   3683:         if ($uploaded || $incourse) {
                   3684:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3685:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3686:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3687:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3688:             # Check that the user has permission to edit this resource
                   3689:             my $setpriv = 1;
                   3690:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3691:             if (defined($cfudom)) {
                   3692:                 $home=&homeserver($cfuname,$cfudom);
                   3693:                 $cfile=$file;
                   3694:             }
                   3695:         }
                   3696:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3697:             (($home ne '') && ($home ne 'no_host'))) {
                   3698:             my @ids=&current_machine_ids();
                   3699:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3700:                 $switchserver=1;
                   3701:             }
                   3702:         }
                   3703:     }
                   3704:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3705: }
                   3706: 
                   3707: sub is_course_upload {
                   3708:     my ($file,$cnum,$cdom) = @_;
                   3709:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3710:     $uploadpath =~ s{^\/}{};
                   3711:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3712:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3713:         return 1;
                   3714:     }
                   3715:     return;
                   3716: }
                   3717: 
                   3718: sub in_course {
                   3719:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3720:     if ($hideprivileged) {
                   3721:         my $skipuser;
1.1172.2.23  raeburn  3722:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3723:         my @possdoms = ($cdom);
                   3724:         if ($coursehash{'checkforpriv'}) {
                   3725:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3726:         }
                   3727:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3728:             $skipuser = 1;
                   3729:             if ($coursehash{'nothideprivileged'}) {
                   3730:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3731:                     my $user;
                   3732:                     if ($item =~ /:/) {
                   3733:                         $user = $item;
                   3734:                     } else {
                   3735:                         $user = join(':',split(/[\@]/,$item));
                   3736:                     }
                   3737:                     if ($user eq $uname.':'.$udom) {
                   3738:                         undef($skipuser);
                   3739:                         last;
                   3740:                     }
                   3741:                 }
                   3742:             }
                   3743:             if ($skipuser) {
                   3744:                 return 0;
                   3745:             }
                   3746:         }
                   3747:     }
                   3748:     $type ||= 'any';
                   3749:     if (!defined($cdom) || !defined($cnum)) {
                   3750:         my $cid  = $env{'request.course.id'};
                   3751:         $cdom = $env{'course.'.$cid.'.domain'};
                   3752:         $cnum = $env{'course.'.$cid.'.num'};
                   3753:     }
                   3754:     my $typesref;
                   3755:     if (($type eq 'any') || ($type eq 'all')) {
                   3756:         $typesref = ['active','previous','future'];
                   3757:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3758:         $typesref = [$type];
                   3759:     }
                   3760:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3761:                               $typesref,undef,[$cdom]);
                   3762:     my ($tmp) = keys(%roles);
                   3763:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3764:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3765:     if (@course_roles > 0) {
                   3766:         return 1;
                   3767:     }
                   3768:     return 0;
                   3769: }
                   3770: 
1.478     albertel 3771: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3772: # input: action, courseID, current domain, intended
1.637     raeburn  3773: #        path to file, source of file, instruction to parse file for objects,
                   3774: #        ref to hash for embedded objects,
                   3775: #        ref to hash for codebase of java objects.
1.1095    raeburn  3776: #        reference to scalar to accommodate mime type determined
                   3777: #          from File::MMagic if $parser = parse.
1.637     raeburn  3778: #
1.485     raeburn  3779: # output: url to file (if action was uploaddoc), 
                   3780: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3781: #
1.478     albertel 3782: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3783: # course.
1.477     raeburn  3784: #
1.478     albertel 3785: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3786: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3787: #          course's home server.
1.477     raeburn  3788: #
1.478     albertel 3789: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3790: #          be copied from $source (current location) to 
                   3791: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3792: #         and will then be copied to
                   3793: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3794: #         course's home server.
1.485     raeburn  3795: #
1.481     raeburn  3796: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3797: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3798: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3799: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3800: #         in course's home server.
1.637     raeburn  3801: #
1.477     raeburn  3802: 
                   3803: sub process_coursefile {
1.1095    raeburn  3804:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3805:         $mimetype)=@_;
1.477     raeburn  3806:     my $fetchresult;
1.638     albertel 3807:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3808:     if ($action eq 'propagate') {
1.638     albertel 3809:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3810: 			     $home);
1.481     raeburn  3811:     } else {
1.477     raeburn  3812:         my $fpath = '';
                   3813:         my $fname = $file;
1.478     albertel 3814:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3815:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3816:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3817:         if ($action eq 'copy') {
                   3818:             if ($source eq '') {
                   3819:                 $fetchresult = 'no source file';
                   3820:                 return $fetchresult;
                   3821:             } else {
                   3822:                 my $destination = $filepath.'/'.$fname;
                   3823:                 rename($source,$destination);
                   3824:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3825:                                  $home);
1.481     raeburn  3826:             }
                   3827:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3828:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3829:             print $fh $env{'form.'.$source};
1.481     raeburn  3830:             close($fh);
1.637     raeburn  3831:             if ($parser eq 'parse') {
1.1024    raeburn  3832:                 my $mm = new File::MMagic;
1.1095    raeburn  3833:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3834:                 if ($type eq 'text/html') {
1.1024    raeburn  3835:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3836:                     unless ($parse_result eq 'ok') {
                   3837:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3838:                     }
1.637     raeburn  3839:                 }
1.1095    raeburn  3840:                 if (ref($mimetype)) {
                   3841:                     $$mimetype = $type;
                   3842:                 } 
1.637     raeburn  3843:             }
1.477     raeburn  3844:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3845:                                  $home);
1.481     raeburn  3846:             if ($fetchresult eq 'ok') {
                   3847:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3848:             } else {
                   3849:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3850:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3851:                 return '/adm/notfound.html';
                   3852:             }
1.477     raeburn  3853:         }
                   3854:     }
1.485     raeburn  3855:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3856:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3857:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3858:     }
                   3859:     return $fetchresult;
                   3860: }
                   3861: 
1.637     raeburn  3862: sub build_filepath {
                   3863:     my ($fpath) = @_;
                   3864:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3865:     unless ($fpath eq '') {
                   3866:         my @parts=split('/',$fpath);
                   3867:         foreach my $part (@parts) {
                   3868:             $filepath.= '/'.$part;
                   3869:             if ((-e $filepath)!=1) {
                   3870:                 mkdir($filepath,0777);
                   3871:             }
                   3872:         }
                   3873:     }
                   3874:     return $filepath;
                   3875: }
                   3876: 
                   3877: sub store_edited_file {
1.638     albertel 3878:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3879:     my $file = $primary_url;
                   3880:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3881:     my $fpath = '';
                   3882:     my $fname = $file;
                   3883:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3884:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3885:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3886:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3887:     print $fh $content;
                   3888:     close($fh);
1.638     albertel 3889:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3890:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3891: 			  $home);
1.637     raeburn  3892:     if ($$fetchresult eq 'ok') {
                   3893:         return '/uploaded/'.$fpath.'/'.$fname;
                   3894:     } else {
1.638     albertel 3895:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3896: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3897:         return '/adm/notfound.html';
                   3898:     }
                   3899: }
                   3900: 
1.531     albertel 3901: sub clean_filename {
1.831     albertel 3902:     my ($fname,$args)=@_;
1.315     www      3903: # Replace Windows backslashes by forward slashes
1.257     www      3904:     $fname=~s/\\/\//g;
1.831     albertel 3905:     if (!$args->{'keep_path'}) {
                   3906:         # Get rid of everything but the actual filename
                   3907: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3908:     }
1.315     www      3909: # Replace spaces by underscores
                   3910:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3911: # Transliterate non-ascii text to ascii
                   3912:     my $lang = &Apache::lonlocal::current_language();
                   3913:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3914: # Replace all other weird characters by nothing
1.831     albertel 3915:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3916: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3917: # numbers
                   3918:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3919: # Replace three or more adjacent underscores with one for consistency
                   3920: # with loncfile::filename_check() so complete url can be extracted by
                   3921: # lonnet::decode_symb()
                   3922:     $fname=~s/_{3,}/_/g;
1.531     albertel 3923:     return $fname;
                   3924: }
1.1172.2.110  raeburn  3925: 
1.1051    raeburn  3926: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3927: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3928: # image with the same aspect ratio as the original, but with dimensions which do 
                   3929: # not exceed $resizewidth and $resizeheight.
                   3930:  
1.984     neumanie 3931: sub resizeImage {
1.1051    raeburn  3932:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3933:     my $ima = Image::Magick->new;
                   3934:     my $resized;
                   3935:     if (-e $img_path) {
                   3936:         $ima->Read($img_path);
                   3937:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3938:             my $width = $ima->Get('width');
                   3939:             my $height = $ima->Get('height');
                   3940:             if ($width > $resizewidth) {
                   3941: 	        my $factor = $width/$resizewidth;
                   3942:                 my $newheight = $height/$factor;
                   3943:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3944:                 $resized = 1;
                   3945:             }
                   3946:         }
                   3947:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3948:             my $width = $ima->Get('width');
                   3949:             my $height = $ima->Get('height');
                   3950:             if ($height > $resizeheight) {
                   3951:                 my $factor = $height/$resizeheight;
                   3952:                 my $newwidth = $width/$factor;
                   3953:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3954:                 $resized = 1;
                   3955:             }
                   3956:         }
                   3957:         if ($resized) {
                   3958:             $ima->Write($img_path);
                   3959:         }
                   3960:     }
                   3961:     return;
1.977     amueller 3962: }
                   3963: 
1.608     albertel 3964: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3965: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3966: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3967: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3968: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3969: #                   if 'coursedoc': upload to the current course
                   3970: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3971: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3972: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3973: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3974: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3975: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3976: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3977: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3978: #        $allfiles - reference to hash for embedded objects
                   3979: #        $codebase - reference to hash for codebase of java objects
                   3980: #        $desuname - username for permanent storage of uploaded file
                   3981: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3982: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3983: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3984: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3985: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3986: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3987: #                    from File::MMagic.
1.858     raeburn  3988: # 
1.686     albertel 3989: # output: url of file in userspace, or error: <message> 
                   3990: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3991: 
1.531     albertel 3992: sub userfileupload {
1.1090    raeburn  3993:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3994:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3995:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3996:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3997:     $fname=&clean_filename($fname);
1.1090    raeburn  3998:     # See if there is anything left
1.257     www      3999:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4000:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4001:     if ($fname =~ /^\./) {
                   4002:         my ($s,$usec) = &gettimeofday();
                   4003:         while (length($usec) < 6) {
                   4004:             $usec = '0'.$usec;
                   4005:         }
                   4006:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4007:     }
1.1090    raeburn  4008:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4009:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4010:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4011:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4012:         my $now = time;
1.1090    raeburn  4013:         my $filepath;
1.1095    raeburn  4014:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4015:              $filepath = 'tmp/helprequests/'.$now;
                   4016:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4017:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4018:                          '_'.$env{'user.domain'}.'/pending';
                   4019:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4020:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4021:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4022:                 $docudom = $destudom;
                   4023:             } else {
                   4024:                 $docudom = $env{'user.domain'};
                   4025:             }
1.1172.2.96  raeburn  4026:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4027:                 $docuname = $destuname;
                   4028:             } else {
                   4029:                 $docuname = $env{'user.name'};
                   4030:             }
                   4031:             if (exists($env{'form.group'})) {
                   4032:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4033:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4034:             }
                   4035:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4036:             if ($context eq 'canceloverwrite') {
                   4037:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4038:                 if (-e  $tempfile) {
                   4039:                     my @info = stat($tempfile);
                   4040:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4041:                         unlink($tempfile);
                   4042:                     }
                   4043:                 }
                   4044:                 return;
1.523     raeburn  4045:             }
                   4046:         }
1.1090    raeburn  4047:         # Create the directory if not present
1.741     raeburn  4048:         my @parts=split(/\//,$filepath);
                   4049:         my $fullpath = $perlvar{'lonDaemons'};
                   4050:         for (my $i=0;$i<@parts;$i++) {
                   4051:             $fullpath .= '/'.$parts[$i];
                   4052:             if ((-e $fullpath)!=1) {
                   4053:                 mkdir($fullpath,0777);
                   4054:             }
                   4055:         }
1.1172.2.96  raeburn  4056:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4057:         print $fh $env{'form.'.$formname};
                   4058:         close($fh);
1.1090    raeburn  4059:         if ($context eq 'existingfile') {
                   4060:             my @info = stat($fullpath.'/'.$fname);
                   4061:             return ($fullpath.'/'.$fname,$info[9]);
                   4062:         } else {
                   4063:             return $fullpath.'/'.$fname;
                   4064:         }
1.523     raeburn  4065:     }
1.995     raeburn  4066:     if ($subdir eq 'scantron') {
                   4067:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4068:     } else {
1.995     raeburn  4069:         $fname="$subdir/$fname";
                   4070:     }
1.1090    raeburn  4071:     if ($context eq 'coursedoc') {
1.638     albertel 4072: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4073: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4074:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4075:             return &finishuserfileupload($docuname,$docudom,
                   4076: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4077: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4078:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4079:         } else {
1.1172.2.21  raeburn  4080:             if ($env{'form.folder'}) {
                   4081:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4082:             }
1.638     albertel 4083:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4084: 				       $fname,$formname,$parser,
1.1095    raeburn  4085: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4086:         }
1.719     banghart 4087:     } elsif (defined($destuname)) {
                   4088:         my $docuname=$destuname;
                   4089:         my $docudom=$destudom;
1.860     raeburn  4090: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4091: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4092:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4093:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4094:     } else {
1.638     albertel 4095:         my $docuname=$env{'user.name'};
                   4096:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4097:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4098:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4099:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4100:         }
1.860     raeburn  4101: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4102: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4103:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4104:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4105:     }
1.271     www      4106: }
                   4107: 
                   4108: sub finishuserfileupload {
1.860     raeburn  4109:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4110:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4111:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4112:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4113:   
1.860     raeburn  4114:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4115:     $file=$fname;
                   4116:     if ($fname=~m|/|) {
                   4117:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4118: 	$path.=$fnamepath.'/';
                   4119:     }
1.259     www      4120:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4121:     my $count;
                   4122:     for ($count=4;$count<=$#parts;$count++) {
                   4123:         $filepath.="/$parts[$count]";
                   4124:         if ((-e $filepath)!=1) {
                   4125: 	    mkdir($filepath,0777);
                   4126:         }
                   4127:     }
1.984     neumanie 4128: 
1.258     www      4129: # Save the file
                   4130:     {
1.1172.2.96  raeburn  4131: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4132: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4133: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4134: 	    return '/adm/notfound.html';
                   4135: 	}
1.1090    raeburn  4136:         if ($context eq 'overwrite') {
1.1117    foxr     4137:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4138:             my $target = $filepath.'/'.$file;
                   4139:             if (-e $source) {
                   4140:                 my @info = stat($source);
                   4141:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4142:                     unless (&File::Copy::move($source,$target)) {
                   4143:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4144:                         return "Moving from $source failed";
                   4145:                     }
                   4146:                 } else {
                   4147:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4148:                 }
                   4149:             } else {
                   4150:                 return "Temporary file: $source missing";
                   4151:             }
                   4152:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4153: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4154: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4155: 	    return '/adm/notfound.html';
                   4156: 	}
1.570     albertel 4157: 	close(FH);
1.1051    raeburn  4158:         if ($resizewidth && $resizeheight) {
                   4159:             my $mm = new File::MMagic;
                   4160:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4161:             if ($mime_type =~ m{^image/}) {
                   4162: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4163:             }  
1.977     amueller 4164: 	}
1.258     www      4165:     }
1.1152    raeburn  4166:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4167:         if (ref($mimetype)) {
                   4168:             if ($$mimetype eq '') {
                   4169:                 my $mm = new File::MMagic;
                   4170:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4171:                 $$mimetype = $type;
                   4172:             }
                   4173:         }
                   4174:     }
1.1172.2.109  raeburn  4175:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4176:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4177:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4178:                                                        $allfiles,$codebase);
                   4179:             unless ($parse_result eq 'ok') {
                   4180:                 &logthis('Failed to parse '.$filepath.$file.
                   4181: 	   	         ' for embedded media: '.$parse_result); 
                   4182:             }
1.637     raeburn  4183:         }
1.1172.2.109  raeburn  4184:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4185:         my $format = $env{'form.scantron_format'};
                   4186:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4187:     }
1.860     raeburn  4188:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4189:         my $input = $filepath.'/'.$file;
                   4190:         my $output = $filepath.'/'.'tn-'.$file;
                   4191:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4192:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4193:         system({$args[0]} @args);
1.860     raeburn  4194:         if (-e $filepath.'/'.'tn-'.$file) {
                   4195:             $fetchthumb  = 1; 
                   4196:         }
                   4197:     }
1.858     raeburn  4198:  
1.259     www      4199: # Notify homeserver to grep it
                   4200: #
1.984     neumanie 4201:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4202:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4203:     if ($fetchresult eq 'ok') {
1.860     raeburn  4204:         if ($fetchthumb) {
                   4205:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4206:             if ($thumbresult ne 'ok') {
                   4207:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4208:                          $docuhome.': '.$thumbresult);
                   4209:             }
                   4210:         }
1.259     www      4211: #
1.258     www      4212: # Return the URL to it
1.494     albertel 4213:         return '/uploaded/'.$path.$file;
1.263     www      4214:     } else {
1.494     albertel 4215:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4216: 		 ': '.$fetchresult);
1.263     www      4217:         return '/adm/notfound.html';
1.858     raeburn  4218:     }
1.493     albertel 4219: }
                   4220: 
1.637     raeburn  4221: sub extract_embedded_items {
1.961     raeburn  4222:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4223:     my @state = ();
1.1164    raeburn  4224:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4225:     my %javafiles = (
                   4226:                       codebase => '',
                   4227:                       code => '',
                   4228:                       archive => ''
                   4229:                     );
                   4230:     my %mediafiles = (
                   4231:                       src => '',
                   4232:                       movie => '',
                   4233:                      );
1.648     raeburn  4234:     my $p;
                   4235:     if ($content) {
                   4236:         $p = HTML::LCParser->new($content);
                   4237:     } else {
1.961     raeburn  4238:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4239:     }
1.641     albertel 4240:     while (my $t=$p->get_token()) {
1.640     albertel 4241: 	if ($t->[0] eq 'S') {
                   4242: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4243: 	    push(@state, $tagname);
1.648     raeburn  4244:             if (lc($tagname) eq 'allow') {
                   4245:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4246:             }
1.640     albertel 4247: 	    if (lc($tagname) eq 'img') {
                   4248: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4249: 	    }
1.886     albertel 4250: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4251:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4252: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4253:                 }
1.886     albertel 4254: 	    }
1.645     raeburn  4255:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4256:                 my $src;
1.645     raeburn  4257:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4258:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4259:                 } else {
1.1164    raeburn  4260:                     if ($attr->{'src'} ne '') {
                   4261:                         $src = $attr->{'src'};
                   4262:                         &add_filetype($allfiles,$src,'src');
                   4263:                     }
                   4264:                 }
                   4265:                 my $text = $p->get_trimmed_text();
                   4266:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4267:                     my @swfargs = split(/,/,$1);
                   4268:                     foreach my $item (@swfargs) {
                   4269:                         $item =~ s/["']//g;
                   4270:                         $item =~ s/^\s+//;
                   4271:                         $item =~ s/\s+$//;
                   4272:                     }
                   4273:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4274:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4275:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4276:                         } else {
                   4277:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4278:                         }
                   4279:                     }
1.645     raeburn  4280:                 }
                   4281:             }
                   4282:             if (lc($tagname) eq 'link') {
                   4283:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4284:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4285:                 }
                   4286:             }
1.640     albertel 4287: 	    if (lc($tagname) eq 'object' ||
                   4288: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4289: 		foreach my $item (keys(%javafiles)) {
                   4290: 		    $javafiles{$item} = '';
                   4291: 		}
1.1164    raeburn  4292:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4293:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4294:                 }
1.640     albertel 4295: 	    }
                   4296: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4297: 		my $name = lc($attr->{'name'});
                   4298: 		foreach my $item (keys(%javafiles)) {
                   4299: 		    if ($name eq $item) {
                   4300: 			$javafiles{$item} = $attr->{'value'};
                   4301: 			last;
                   4302: 		    }
                   4303: 		}
1.1164    raeburn  4304:                 my $pathfrom;
1.640     albertel 4305: 		foreach my $item (keys(%mediafiles)) {
                   4306: 		    if ($name eq $item) {
1.1164    raeburn  4307:                         $pathfrom = $attr->{'value'};
                   4308:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4309: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4310: 			last;
                   4311: 		    }
                   4312: 		}
1.1164    raeburn  4313:                 if ($name eq 'flashvars') {
                   4314:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4315:                 }
                   4316:                 if ($pathfrom ne '') {
                   4317:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4318:                                          $pathfrom);
                   4319:                 }
1.640     albertel 4320: 	    }
                   4321: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4322: 		foreach my $item (keys(%javafiles)) {
                   4323: 		    if ($attr->{$item}) {
                   4324: 			$javafiles{$item} = $attr->{$item};
                   4325: 			last;
                   4326: 		    }
                   4327: 		}
                   4328: 		foreach my $item (keys(%mediafiles)) {
                   4329: 		    if ($attr->{$item}) {
                   4330: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4331: 			last;
                   4332: 		    }
                   4333: 		}
1.1164    raeburn  4334:                 if (lc($tagname) eq 'embed') {
                   4335:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4336:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4337:                                              $attr->{'src'});
                   4338:                     }
                   4339:                 }
1.640     albertel 4340: 	    }
1.1172.2.35  raeburn  4341:             if (lc($tagname) eq 'iframe') {
                   4342:                 my $src = $attr->{'src'} ;
                   4343:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4344:                     &add_filetype($allfiles,$src,'src');
                   4345:                 } elsif ($src =~ m{^/}) {
                   4346:                     if ($env{'request.course.id'}) {
                   4347:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4348:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4349:                         my $url = &hreflocation('',$fullpath);
                   4350:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4351:                             my $relpath = $1;
                   4352:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4353:                                 &add_filetype($allfiles,$1,'src');
                   4354:                             }
                   4355:                         }
                   4356:                     }
                   4357:                 }
                   4358:             }
1.1164    raeburn  4359:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4360:                 pop(@state);
1.1164    raeburn  4361:             }
1.640     albertel 4362: 	} elsif ($t->[0] eq 'E') {
                   4363: 	    my ($tagname) = ($t->[1]);
                   4364: 	    if ($javafiles{'codebase'} ne '') {
                   4365: 		$javafiles{'codebase'} .= '/';
                   4366: 	    }  
                   4367: 	    if (lc($tagname) eq 'applet' ||
                   4368: 		lc($tagname) eq 'object' ||
                   4369: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4370: 		) {
                   4371: 		foreach my $item (keys(%javafiles)) {
                   4372: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4373: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4374: 			&add_filetype($allfiles,$file,$item);
                   4375: 		    }
                   4376: 		}
                   4377: 	    } 
                   4378: 	    pop @state;
                   4379: 	}
                   4380:     }
1.1164    raeburn  4381:     foreach my $id (sort(keys(%flashvars))) {
                   4382:         if ($shockwave{$id} ne '') {
                   4383:             my @pairs = split(/\&/,$flashvars{$id});
                   4384:             foreach my $pair (@pairs) {
                   4385:                 my ($key,$value) = split(/\=/,$pair);
                   4386:                 if ($key eq 'thumb') {
                   4387:                     &add_filetype($allfiles,$value,$key);
                   4388:                 } elsif ($key eq 'content') {
                   4389:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4390:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4391:                     if ($ext ne '') {
                   4392:                         &add_filetype($allfiles,$path.$value,$ext);
                   4393:                     }
                   4394:                 }
                   4395:             }
                   4396:         }
                   4397:     }
1.637     raeburn  4398:     return 'ok';
                   4399: }
                   4400: 
1.639     albertel 4401: sub add_filetype {
                   4402:     my ($allfiles,$file,$type)=@_;
                   4403:     if (exists($allfiles->{$file})) {
                   4404: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4405: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4406: 	}
                   4407:     } else {
                   4408: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4409:     }
                   4410: }
                   4411: 
1.1164    raeburn  4412: sub embedded_dependency {
                   4413:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4414:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4415:         if (($identifier ne '') &&
                   4416:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4417:             ($pathfrom ne '')) {
                   4418:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4419:             foreach my $dep (@{$related->{$identifier}}) {
                   4420:                 &add_filetype($allfiles,$path.$dep,'object');
                   4421:             }
                   4422:         }
                   4423:     }
                   4424:     return;
                   4425: }
                   4426: 
1.1172.2.109  raeburn  4427: sub bubblesheet_converter {
                   4428:     my ($cdom,$fullpath,$config,$format) = @_;
                   4429:     if ((&domain($cdom) ne '') &&
                   4430:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4431:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4432:         my (%csvcols,%csvoptions);
                   4433:         if (ref($config->{'fields'}) eq 'HASH') {
                   4434:             %csvcols = %{$config->{'fields'}};
                   4435:         }
                   4436:         if (ref($config->{'options'}) eq 'HASH') {
                   4437:             %csvoptions = %{$config->{'options'}};
                   4438:         }
                   4439:         my %csvbynum = reverse(%csvcols);
                   4440:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4441:         if (keys(%scantronconf)) {
                   4442:             my %bynum = (
                   4443:                           $scantronconf{CODEstart} => 'CODEstart',
                   4444:                           $scantronconf{IDstart}   => 'IDstart',
                   4445:                           $scantronconf{PaperID}   => 'PaperID',
                   4446:                           $scantronconf{FirstName} => 'FirstName',
                   4447:                           $scantronconf{LastName}  => 'LastName',
                   4448:                           $scantronconf{Qstart}    => 'Qstart',
                   4449:                         );
                   4450:             my @ordered;
                   4451:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4452:                 push(@ordered,$bynum{$item});
                   4453:             }
                   4454:             my %mapstart = (
                   4455:                               CODEstart => 'CODE',
                   4456:                               IDstart   => 'ID',
                   4457:                               PaperID   => 'PaperID',
                   4458:                               FirstName => 'FirstName',
                   4459:                               LastName  => 'LastName',
                   4460:                               Qstart    => 'FirstQuestion',
                   4461:                            );
                   4462:             my %maplength = (
                   4463:                               CODEstart => 'CODElength',
                   4464:                               IDstart   => 'IDlength',
                   4465:                               PaperID   => 'PaperIDlength',
                   4466:                               FirstName => 'FirstNamelength',
                   4467:                               LastName  => 'LastNamelength',
                   4468:             );
                   4469:             if (open(my $fh,'<',$fullpath)) {
                   4470:                 my $output;
                   4471:                 my %lettdig = &letter_to_digits();
                   4472:                 my %diglett = reverse(%lettdig);
                   4473:                 my $numletts = scalar(keys(%lettdig));
                   4474:                 my $num = 0;
                   4475:                 while (my $line=<$fh>) {
                   4476:                     $num ++;
                   4477:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4478:                     $line =~ s{[\r\n]+$}{};
                   4479:                     my %found;
1.1172.2.143  raeburn  4480:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4481:                     my ($qstart,$record);
                   4482:                     for (my $i=0; $i<@values; $i++) {
                   4483:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4484:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4485:                             if ($values[$i] eq '') {
                   4486:                                 $values[$i] = $scantronconf{'Qoff'};
                   4487:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4488:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4489:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4490:                                 }
                   4491:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4492:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4493:                                     $values[$i] = $diglett{$values[$i]};
                   4494:                                 }
                   4495:                             } else {
                   4496:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4497:                                     my $digit;
                   4498:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4499:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4500:                                         if ($values[$i] eq 'J') {
                   4501:                                             $digit += $numletts;
                   4502:                                         }
                   4503:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4504:                                         $digit = $values[$i]-1;
                   4505:                                         if ($values[$i] eq '0') {
                   4506:                                             $digit += $numletts;
                   4507:                                         }
                   4508:                                     }
                   4509:                                     my $qval='';
                   4510:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4511:                                         if ($j == $digit) {
                   4512:                                             $qval .= $scantronconf{'Qon'};
                   4513:                                         } else {
                   4514:                                             $qval .= $scantronconf{'Qoff'};
                   4515:                                         }
                   4516:                                     }
                   4517:                                     $values[$i] = $qval;
                   4518:                                 }
                   4519:                             }
                   4520:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4521:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4522:                             }
                   4523:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4524:                             if ($numblank > 0) {
                   4525:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4526:                             }
                   4527:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4528:                                 $qstart = $i;
                   4529:                                 $found{$csvbynum{$i}} = $values[$i];
                   4530:                             } else {
                   4531:                                 $found{'FirstQuestion'} .= $values[$i];
                   4532:                             }
                   4533:                         } elsif (exists($csvbynum{$i})) {
                   4534:                             if ($csvoptions{'rem'}) {
                   4535:                                 $values[$i] =~ s/^\s+//;
                   4536:                             }
                   4537:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4538:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4539:                                     $values[$i] = '0'.$values[$i];
                   4540:                                 }
                   4541:                             }
                   4542:                             $found{$csvbynum{$i}} = $values[$i];
                   4543:                         }
                   4544:                     }
                   4545:                     foreach my $item (@ordered) {
                   4546:                         my $currlength = 1+length($record);
                   4547:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4548:                         if ($numspaces > 0) {
                   4549:                             $record .= (' ' x $numspaces);
                   4550:                         }
                   4551:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4552:                             unless ($item eq 'Qstart') {
                   4553:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4554:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4555:                                 }
                   4556:                             }
                   4557:                             $record .= $found{$mapstart{$item}};
                   4558:                         }
                   4559:                     }
                   4560:                     $output .= "$record\n";
                   4561:                 }
                   4562:                 close($fh);
                   4563:                 if ($output) {
                   4564:                     if (open(my $fh,'>',$fullpath)) {
                   4565:                         print $fh $output;
                   4566:                         close($fh);
                   4567:                     }
                   4568:                 }
                   4569:             }
                   4570:         }
                   4571:         return;
                   4572:     }
                   4573: }
                   4574: 
                   4575: sub letter_to_digits {
                   4576:     my %lettdig = (
                   4577:                     A => 1,
                   4578:                     B => 2,
                   4579:                     C => 3,
                   4580:                     D => 4,
                   4581:                     E => 5,
                   4582:                     F => 6,
                   4583:                     G => 7,
                   4584:                     H => 8,
                   4585:                     I => 9,
                   4586:                     J => 0,
                   4587:                   );
                   4588:     return %lettdig;
                   4589: }
                   4590: 
                   4591: sub get_scantron_config {
                   4592:     my ($which,$cdom) = @_;
                   4593:     my @lines = &get_scantronformat_file($cdom);
                   4594:     my %config;
                   4595:     #FIXME probably should move to XML it has already gotten a bit much now
                   4596:     foreach my $line (@lines) {
                   4597:         my ($name,$descrip)=split(/:/,$line);
                   4598:         if ($name ne $which ) { next; }
                   4599:         chomp($line);
                   4600:         my @config=split(/:/,$line);
                   4601:         $config{'name'}=$config[0];
                   4602:         $config{'description'}=$config[1];
                   4603:         $config{'CODElocation'}=$config[2];
                   4604:         $config{'CODEstart'}=$config[3];
                   4605:         $config{'CODElength'}=$config[4];
                   4606:         $config{'IDstart'}=$config[5];
                   4607:         $config{'IDlength'}=$config[6];
                   4608:         $config{'Qstart'}=$config[7];
                   4609:         $config{'Qlength'}=$config[8];
                   4610:         $config{'Qoff'}=$config[9];
                   4611:         $config{'Qon'}=$config[10];
                   4612:         $config{'PaperID'}=$config[11];
                   4613:         $config{'PaperIDlength'}=$config[12];
                   4614:         $config{'FirstName'}=$config[13];
                   4615:         $config{'FirstNamelength'}=$config[14];
                   4616:         $config{'LastName'}=$config[15];
                   4617:         $config{'LastNamelength'}=$config[16];
                   4618:         $config{'BubblesPerRow'}=$config[17];
                   4619:         last;
                   4620:     }
                   4621:     return %config;
                   4622: }
                   4623: 
                   4624: sub get_scantronformat_file {
                   4625:     my ($cdom) = @_;
                   4626:     if ($cdom eq '') {
                   4627:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4628:     }
                   4629:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4630:     my $gottab = 0;
                   4631:     my @lines;
                   4632:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4633:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4634:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4635:             if ($formatfile ne '-1') {
                   4636:                 @lines = split("\n",$formatfile,-1);
                   4637:                 $gottab = 1;
                   4638:             }
                   4639:         }
                   4640:     }
                   4641:     if (!$gottab) {
                   4642:         my $confname = $cdom.'-domainconfig';
                   4643:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4644:         my $formatfile = &getfile($default);
                   4645:         if ($formatfile ne '-1') {
                   4646:             @lines = split("\n",$formatfile,-1);
                   4647:             $gottab = 1;
                   4648:         }
                   4649:     }
                   4650:     if (!$gottab) {
                   4651:         my @domains = &current_machine_domains();
                   4652:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4653:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4654:                 @lines = <$fh>;
                   4655:                 close($fh);
                   4656:             }
                   4657:         } else {
                   4658:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4659:                 @lines = <$fh>;
                   4660:                 close($fh);
                   4661:             }
                   4662:         }
1.1172.2.146.  .8(raebu 4663:23):         chomp(@lines);
1.1172.2.109  raeburn  4664:     }
                   4665:     return @lines;
                   4666: }
                   4667: 
1.493     albertel 4668: sub removeuploadedurl {
1.984     neumanie 4669:     my ($url)=@_;	
                   4670:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4671:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4672: }
                   4673: 
                   4674: sub removeuserfile {
                   4675:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4676:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4677:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4678:     if ($result eq 'ok') {	
1.798     raeburn  4679:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4680:             my $metafile = $fname.'.meta';
                   4681:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4682: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4683:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4684:             my $sqlresult = 
1.823     albertel 4685:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4686:                                         'portfolio_metadata',$group,
                   4687:                                         'delete');
1.798     raeburn  4688:         }
                   4689:     }
                   4690:     return $result;
1.257     www      4691: }
1.15      www      4692: 
1.530     albertel 4693: sub mkdiruserfile {
                   4694:     my ($docuname,$docudom,$dir)=@_;
                   4695:     my $home=&homeserver($docuname,$docudom);
                   4696:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4697: }
                   4698: 
1.531     albertel 4699: sub renameuserfile {
                   4700:     my ($docuname,$docudom,$old,$new)=@_;
                   4701:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4702:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4703:                         &escape("$old").':'.&escape("$new"),$home);
                   4704:     if ($result eq 'ok') {
                   4705:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4706:             my $oldmeta = $old.'.meta';
                   4707:             my $newmeta = $new.'.meta';
                   4708:             my $metaresult = 
                   4709:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4710: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4711:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4712:             my $sqlresult = 
1.823     albertel 4713:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4714:                                         'portfolio_metadata',$group,
                   4715:                                         'delete');
1.798     raeburn  4716:         }
                   4717:     }
                   4718:     return $result;
1.531     albertel 4719: }
                   4720: 
1.14      www      4721: # ------------------------------------------------------------------------- Log
                   4722: 
                   4723: sub log {
                   4724:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4725:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4726: }
                   4727: 
                   4728: # ------------------------------------------------------------------ Course Log
1.352     www      4729: #
                   4730: # This routine flushes several buffers of non-mission-critical nature
                   4731: #
1.157     www      4732: 
                   4733: sub flushcourselogs {
1.352     www      4734:     &logthis('Flushing log buffers');
                   4735: #
                   4736: # course logs
                   4737: # This is a log of all transactions in a course, which can be used
                   4738: # for data mining purposes
                   4739: #
                   4740: # It also collects the courseid database, which lists last transaction
                   4741: # times and course titles for all courseids
                   4742: #
                   4743:     my %courseidbuffer=();
1.921     raeburn  4744:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4745:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4746: 		          &escape($courselogs{$crsid}),
                   4747: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4748: 	    delete $courselogs{$crsid};
                   4749:         } else {
                   4750:             &logthis('Failed to flush log buffer for '.$crsid);
                   4751:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4752:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4753:                         " exceeded maximum size, deleting.</font>");
                   4754:                delete $courselogs{$crsid};
                   4755:             }
1.352     www      4756:         }
1.920     raeburn  4757:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4758:             'description' => $coursedescrbuf{$crsid},
                   4759:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4760:             'type'        => $coursetypebuf{$crsid},
                   4761:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4762:         };
1.191     harris41 4763:     }
1.352     www      4764: #
                   4765: # Write course id database (reverse lookup) to homeserver of courses 
                   4766: # Is used in pickcourse
                   4767: #
1.840     albertel 4768:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4769:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4770:                                     $courseidbuffer{$crs_home},
                   4771:                                     $crs_home,'timeonly');
1.352     www      4772:     }
                   4773: #
                   4774: # File accesses
                   4775: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4776: #
1.449     matthew  4777:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4778:         if ($entry =~ /___count$/) {
                   4779:             my ($dom,$name);
1.807     albertel 4780:             ($dom,$name,undef)=
1.811     albertel 4781: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4782:             if (! defined($dom) || $dom eq '' || 
                   4783:                 ! defined($name) || $name eq '') {
1.620     albertel 4784:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4785: #
                   4786: # FIXME 11/29/2021
                   4787: # Typo in rev. 1.458 (2003/12/09)??
                   4788: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4789: #
                   4790: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4791: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4792: # in a nohist_accesscount.db file for the user rather than the course.
                   4793: #
                   4794: # That said there is a lot of noise in the data being stored.
                   4795: # So counts for prtspool/  and adm/ etc. are recorded.
                   4796: #
                   4797: # A review of which items ending '___count' are written to %accesshash should likely be
                   4798: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4799: #
                   4800: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4801: # accesses for things which are not published resources, regardless of course, and
                   4802: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4803: # anyone in the course for things which are not published resources.
                   4804: #
                   4805: # For an author, nohist_accesscount.db ends up having records for other items
                   4806: # mixed up with the legitimate access counts for the author's published resources.
                   4807: #
1.620     albertel 4808:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4809:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4810:             }
1.450     matthew  4811:             my $value = $accesshash{$entry};
                   4812:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4813:             my %temphash=($url => $value);
1.449     matthew  4814:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4815:             if ($result eq 'ok') {
                   4816:                 delete $accesshash{$entry};
                   4817:             }
                   4818:         } else {
1.811     albertel 4819:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4820:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4821:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4822:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4823:                 delete $accesshash{$entry};
                   4824:             }
1.185     www      4825:         }
1.191     harris41 4826:     }
1.352     www      4827: #
                   4828: # Roles
                   4829: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4830: #
1.800     albertel 4831:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4832:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4833: 	    split(/\:/,$entry);
                   4834:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4835:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4836:                 $rudom,$runame) eq 'ok') {
                   4837: 	    delete $userrolehash{$entry};
                   4838:         }
                   4839:     }
1.662     raeburn  4840: #
1.1172.2.90  raeburn  4841: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4842: #
                   4843:     my %domrolebuffer = ();
1.1000    raeburn  4844:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4845:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4846:         if ($domrolebuffer{$rudom}) {
                   4847:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4848:                       '='.&escape($domainrolehash{$entry});
                   4849:         } else {
                   4850:             $domrolebuffer{$rudom}.=&escape($entry).
                   4851:                       '='.&escape($domainrolehash{$entry});
                   4852:         }
                   4853:         delete $domainrolehash{$entry};
                   4854:     }
                   4855:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4856:         my %servers;
                   4857:         if (defined(&domain($dom,'primary'))) {
                   4858:             my $primary=&domain($dom,'primary');
                   4859:             my $hostname=&hostname($primary);
                   4860:             $servers{$primary} = $hostname;
                   4861:         } else {
                   4862:             %servers = &get_servers($dom,'library');
                   4863:         }
1.841     albertel 4864: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4865: 	    if (&reply('domroleput:'.$dom.':'.
                   4866: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4867: 	        last;
                   4868: 	    } else {
1.841     albertel 4869: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4870: 	    }
1.662     raeburn  4871:         }
                   4872:     }
1.186     www      4873:     $dumpcount++;
1.157     www      4874: }
                   4875: 
                   4876: sub courselog {
                   4877:     my $what=shift;
1.158     www      4878:     $what=time.':'.$what;
1.620     albertel 4879:     unless ($env{'request.course.id'}) { return ''; }
                   4880:     $coursedombuf{$env{'request.course.id'}}=
                   4881:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4882:     $coursenumbuf{$env{'request.course.id'}}=
                   4883:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4884:     $coursehombuf{$env{'request.course.id'}}=
                   4885:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4886:     $coursedescrbuf{$env{'request.course.id'}}=
                   4887:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4888:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4889:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4890:     $courseownerbuf{$env{'request.course.id'}}=
                   4891:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4892:     $coursetypebuf{$env{'request.course.id'}}=
                   4893:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4894:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4895: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4896:     } else {
1.620     albertel 4897: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4898:     }
1.620     albertel 4899:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4900: 	&flushcourselogs();
                   4901:     }
1.158     www      4902: }
                   4903: 
                   4904: sub courseacclog {
                   4905:     my $fnsymb=shift;
1.620     albertel 4906:     unless ($env{'request.course.id'}) { return ''; }
                   4907:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4908:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4909:         $what.=':POST';
1.583     matthew  4910:         # FIXME: Probably ought to escape things....
1.800     albertel 4911: 	foreach my $key (keys(%env)) {
                   4912:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4913:                 my $formitem = $1;
                   4914:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4915:                     $what.=':'.$formitem.'='.$env{$key};
                   4916:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4917:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4918:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4919:                     } else {
                   4920:                         $what.=':'.$formitem.'='.$env{$key};
                   4921:                     }
1.975     raeburn  4922:                 }
1.158     www      4923:             }
1.191     harris41 4924:         }
1.583     matthew  4925:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4926:         # FIXME: We should not be depending on a form parameter that someone
                   4927:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4928:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4929:             $what.= ':POST';
                   4930:             # FIXME: Probably ought to escape things....
                   4931:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4932:                                  'crsdiscuss') {
1.620     albertel 4933:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4934:             }
                   4935:         }
1.158     www      4936:     }
                   4937:     &courselog($what);
1.149     www      4938: }
                   4939: 
1.185     www      4940: sub countacc {
                   4941:     my $url=&declutter(shift);
1.458     matthew  4942:     return if (! defined($url) || $url eq '');
1.620     albertel 4943:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4944: #
                   4945: # Mark that this url was used in this course
                   4946: #
1.620     albertel 4947:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4948: #
                   4949: # Increase the access count for this resource in this child process
                   4950: #
1.281     www      4951:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4952:     $accesshash{$key}++;
1.185     www      4953: }
1.349     www      4954: 
1.361     www      4955: sub linklog {
                   4956:     my ($from,$to)=@_;
                   4957:     $from=&declutter($from);
                   4958:     $to=&declutter($to);
                   4959:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4960:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4961: }
1.1160    www      4962: 
                   4963: sub statslog {
                   4964:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4965:     if ($users<2) { return; }
                   4966:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4967:             'course'       => $env{'request.course.id'},
                   4968:             'sections'     => '"all"',
                   4969:             'num_students' => $users,
                   4970:             'part'         => $part,
                   4971:             'symb'         => $symb,
                   4972:             'mean_tries'   => $av_attempts,
                   4973:             'deg_of_diff'  => $degdiff});
                   4974:     foreach my $key (keys(%dynstore)) {
                   4975:         $accesshash{$key}=$dynstore{$key};
                   4976:     }
                   4977: }
1.361     www      4978:   
1.349     www      4979: sub userrolelog {
                   4980:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4981:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4982:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4983:        $userrolehash
                   4984:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4985:                     =$tend.':'.$tstart;
1.662     raeburn  4986:     }
1.1169    droeschl 4987:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4988:        $userrolehash
                   4989:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4990:                     =$tend.':'.$tstart;
                   4991:     }
1.1172.2.90  raeburn  4992:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4993:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4994:        $domainrolehash
                   4995:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4996:                     = $tend.':'.$tstart;
                   4997:     }
1.351     www      4998: }
                   4999: 
1.957     raeburn  5000: sub courserolelog {
                   5001:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5002:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5003:         my $cdom = $1;
                   5004:         my $cnum = $2;
                   5005:         my $sec = $3;
                   5006:         my $namespace = 'rolelog';
                   5007:         my %storehash = (
                   5008:                            role    => $trole,
                   5009:                            start   => $tstart,
                   5010:                            end     => $tend,
                   5011:                            selfenroll => $selfenroll,
                   5012:                            context    => $context,
                   5013:                         );
                   5014:         if ($trole eq 'gr') {
                   5015:             $namespace = 'groupslog';
                   5016:             $storehash{'group'} = $sec;
                   5017:         } else {
                   5018:             $storehash{'section'} = $sec;
                   5019:         }
                   5020:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5021:                    $domain,$cnum,$cdom);
                   5022:         if (($trole ne 'st') || ($sec ne '')) {
                   5023:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5024:         }
                   5025:     }
                   5026:     return;
                   5027: }
                   5028: 
1.1172.2.9  raeburn  5029: sub domainrolelog {
                   5030:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5031:     if ($area =~ m{^/($match_domain)/$}) {
                   5032:         my $cdom = $1;
                   5033:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5034:         my $namespace = 'rolelog';
                   5035:         my %storehash = (
                   5036:                            role    => $trole,
                   5037:                            start   => $tstart,
                   5038:                            end     => $tend,
                   5039:                            context => $context,
                   5040:                         );
                   5041:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5042:                    $domain,$domconfiguser,$cdom);
                   5043:     }
                   5044:     return;
                   5045: 
                   5046: }
                   5047: 
                   5048: sub coauthorrolelog {
                   5049:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5050:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5051:         my $audom = $1;
                   5052:         my $auname = $2;
                   5053:         my $namespace = 'rolelog';
                   5054:         my %storehash = (
                   5055:                            role    => $trole,
                   5056:                            start   => $tstart,
                   5057:                            end     => $tend,
                   5058:                            context => $context,
                   5059:                         );
                   5060:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5061:                    $domain,$auname,$audom);
                   5062:     }
                   5063:     return;
                   5064: }
                   5065: 
1.351     www      5066: sub get_course_adv_roles {
1.948     raeburn  5067:     my ($cid,$codes) = @_;
1.620     albertel 5068:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5069:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5070:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5071:     my %nothide=();
1.800     albertel 5072:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5073:         if ($user !~ /:/) {
                   5074: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5075:         } else {
                   5076:             $nothide{$user}=1;
                   5077:         }
1.470     www      5078:     }
1.1172.2.23  raeburn  5079:     my @possdoms = ($coursehash{'domain'});
                   5080:     if ($coursehash{'checkforpriv'}) {
                   5081:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5082:     }
1.351     www      5083:     my %returnhash=();
                   5084:     my %dumphash=
                   5085:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5086:     my $now=time;
1.997     raeburn  5087:     my %privileged;
1.1000    raeburn  5088:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5089: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5090:         if (($tstart) && ($tstart<0)) { next; }
                   5091:         if (($tend) && ($tend<$now)) { next; }
                   5092:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5093:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5094: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5095:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5096:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5097: 	if ($role eq 'cr') { next; }
1.948     raeburn  5098:         if ($codes) {
                   5099:             if ($section) { $role .= ':'.$section; }
                   5100:             if ($returnhash{$role}) {
                   5101:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5102:             } else {
                   5103:                 $returnhash{$role}=$username.':'.$domain;
                   5104:             }
1.351     www      5105:         } else {
1.988     raeburn  5106:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5107:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5108:             if ($returnhash{$key}) {
                   5109: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5110:             } else {
                   5111:                 $returnhash{$key}=$username.':'.$domain;
                   5112:             }
1.351     www      5113:         }
1.948     raeburn  5114:     }
1.400     www      5115:     return %returnhash;
                   5116: }
                   5117: 
                   5118: sub get_my_roles {
1.937     raeburn  5119:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5120:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5121:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5122:     my (%dumphash,%nothide);
1.1086    raeburn  5123:     if ($context eq 'userroles') {
1.1166    raeburn  5124:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5125:     } else {
1.1172.2.23  raeburn  5126:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5127:         if ($hidepriv) {
                   5128:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5129:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5130:                 if ($user !~ /:/) {
                   5131:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5132:                 } else {
                   5133:                     $nothide{$user} = 1;
                   5134:                 }
                   5135:             }
                   5136:         }
1.858     raeburn  5137:     }
1.400     www      5138:     my %returnhash=();
                   5139:     my $now=time;
1.999     raeburn  5140:     my %privileged;
1.800     albertel 5141:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5142:         my ($role,$tend,$tstart);
                   5143:         if ($context eq 'userroles') {
1.1149    raeburn  5144:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5145: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5146:         } else {
                   5147:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5148:         }
1.400     www      5149:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5150:         my $status = 'active';
1.939     raeburn  5151:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5152:             $status = 'previous';
                   5153:         } 
                   5154:         if (($tstart) && ($now<$tstart)) {
                   5155:             $status = 'future';
                   5156:         }
                   5157:         if (ref($types) eq 'ARRAY') {
                   5158:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5159:                 next;
                   5160:             } 
                   5161:         } else {
                   5162:             if ($status ne 'active') {
                   5163:                 next;
                   5164:             }
                   5165:         }
1.867     raeburn  5166:         my ($rolecode,$username,$domain,$section,$area);
                   5167:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5168:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5169:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5170:         } else {
                   5171:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5172:         }
1.832     raeburn  5173:         if (ref($roledoms) eq 'ARRAY') {
                   5174:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5175:                 next;
                   5176:             }
                   5177:         }
                   5178:         if (ref($roles) eq 'ARRAY') {
                   5179:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5180:                 if ($role =~ /^cr\//) {
                   5181:                     if (!grep(/^cr$/,@{$roles})) {
                   5182:                         next;
                   5183:                     }
1.1104    raeburn  5184:                 } elsif ($role =~ /^gr\//) {
                   5185:                     if (!grep(/^gr$/,@{$roles})) {
                   5186:                         next;
                   5187:                     }
1.922     raeburn  5188:                 } else {
                   5189:                     next;
                   5190:                 }
1.832     raeburn  5191:             }
1.867     raeburn  5192:         }
1.937     raeburn  5193:         if ($hidepriv) {
1.1172.2.23  raeburn  5194:             my @privroles = ('dc','su');
1.999     raeburn  5195:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5196:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5197:             } else {
1.1172.2.23  raeburn  5198:                 my $possdoms = [$domain];
                   5199:                 if (ref($roledoms) eq 'ARRAY') {
                   5200:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5201:                 }
1.1172.2.23  raeburn  5202:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5203:                     if (!$nothide{$username.':'.$domain}) {
                   5204:                         next;
                   5205:                     }
                   5206:                 }
1.937     raeburn  5207:             }
                   5208:         }
1.933     raeburn  5209:         if ($withsec) {
                   5210:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5211:                 $tstart.':'.$tend;
                   5212:         } else {
                   5213:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5214:         }
1.832     raeburn  5215:     }
1.373     www      5216:     return %returnhash;
1.399     www      5217: }
                   5218: 
1.1172.2.89  raeburn  5219: sub get_all_adhocroles {
                   5220:     my ($dom) = @_;
                   5221:     my @roles_by_num = ();
                   5222:     my %domdefaults = &get_domain_defaults($dom);
                   5223:     my (%description,%access_in_dom,%access_info);
                   5224:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5225:         my $count = 0;
                   5226:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5227:         my %ordered;
                   5228:         foreach my $role (sort(keys(%domcurrent))) {
                   5229:             my ($order,$desc,$access_in_dom);
                   5230:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5231:                 $order = $domcurrent{$role}{'order'};
                   5232:                 $desc = $domcurrent{$role}{'desc'};
                   5233:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5234:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5235:             }
                   5236:             if ($order eq '') {
                   5237:                 $order = $count;
                   5238:             }
                   5239:             $ordered{$order} = $role;
                   5240:             if ($desc ne '') {
                   5241:                 $description{$role} = $desc;
                   5242:             } else {
                   5243:                 $description{$role}= $role;
                   5244:             }
                   5245:             $count++;
                   5246:         }
                   5247:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5248:             push(@roles_by_num,$ordered{$item});
                   5249:         }
                   5250:     }
                   5251:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5252: }
                   5253: 
                   5254: sub get_my_adhocroles {
                   5255:     my ($cid,$checkreg) = @_;
                   5256:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5257:     if ($env{'request.course.id'} eq $cid) {
                   5258:         $cdom = $env{'course.'.$cid.'.domain'};
                   5259:         $cnum = $env{'course.'.$cid.'.num'};
                   5260:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5261:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5262:         $cdom = $1;
                   5263:         $cnum = $2;
                   5264:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5265:                                      $cdom,$cnum);
                   5266:     }
                   5267:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5268:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5269:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5270:         if ($rosterhash{$user} ne '') {
                   5271:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5272:             return ([],{}) if ($type eq 'auto');
                   5273:         }
                   5274:     }
                   5275:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5276:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5277:             my $then=$env{'user.login.time'};
                   5278:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5279:             if (!$update) {
                   5280:                 $update = $then;
                   5281:             }
                   5282:             my @liveroles;
                   5283:             foreach my $role ('dh','da') {
                   5284:                 if ($env{"user.role.$role./$cdom/"}) {
                   5285:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5286:                     my $limit = $update;
                   5287:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5288:                         $limit = $then;
                   5289:                     }
                   5290:                     my $activerole = 1;
                   5291:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5292:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5293:                     if ($activerole) {
                   5294:                         push(@liveroles,$role);
                   5295:                     }
                   5296:                 }
                   5297:             }
                   5298:             if (@liveroles) {
1.1172.2.89  raeburn  5299:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5300:                     my ($accessref,$accessinfo,%access_in_dom);
                   5301:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5302:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5303:                         if (@{$roles_by_num}) {
                   5304:                             my %settings;
                   5305:                             if ($env{'request.course.id'} eq $cid) {
                   5306:                                 foreach my $envkey (keys(%env)) {
                   5307:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5308:                                         $settings{$1} = $env{$envkey};
                   5309:                                     }
                   5310:                                 }
                   5311:                             } else {
                   5312:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5313:                             }
                   5314:                             my %setincrs;
                   5315:                             if ($settings{'internal.adhocaccess'}) {
                   5316:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5317:                             }
                   5318:                             my @statuses;
                   5319:                             if ($env{'environment.inststatus'}) {
                   5320:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5321:                             }
                   5322:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5323:                             if (ref($accessref) eq 'HASH') {
                   5324:                                 %access_in_dom = %{$accessref};
                   5325:                             }
                   5326:                             foreach my $role (@{$roles_by_num}) {
                   5327:                                 my ($curraccess,@okstatus,@personnel);
                   5328:                                 if ($setincrs{$role}) {
                   5329:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5330:                                     if ($curraccess eq 'status') {
                   5331:                                         @okstatus = split(/\&/,$rest);
                   5332:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5333:                                         @personnel = split(/\&/,$rest);
                   5334:                                     }
                   5335:                                 } else {
                   5336:                                     $curraccess = $access_in_dom{$role};
                   5337:                                     if (ref($accessinfo) eq 'HASH') {
                   5338:                                         if ($curraccess eq 'status') {
                   5339:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5340:                                                 @okstatus = @{$accessinfo->{$role}};
                   5341:                                             }
                   5342:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5343:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5344:                                                 @personnel = @{$accessinfo->{$role}};
                   5345:                                             }
                   5346:                                         }
                   5347:                                     }
                   5348:                                 }
                   5349:                                 if ($curraccess eq 'none') {
                   5350:                                     next;
                   5351:                                 } elsif ($curraccess eq 'all') {
                   5352:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5353:                                 } elsif ($curraccess eq 'dh') {
                   5354:                                     if (grep(/^dh$/,@liveroles)) {
                   5355:                                         push(@possroles,$role);
                   5356:                                     } else {
                   5357:                                         next;
                   5358:                                     }
                   5359:                                 } elsif ($curraccess eq 'da') {
                   5360:                                     if (grep(/^da$/,@liveroles)) {
                   5361:                                         push(@possroles,$role);
                   5362:                                     } else {
                   5363:                                         next;
                   5364:                                     }
1.1172.2.89  raeburn  5365:                                 } elsif ($curraccess eq 'status') {
                   5366:                                     if (@okstatus) {
                   5367:                                         if (!@statuses) {
                   5368:                                             if (grep(/^default$/,@okstatus)) {
                   5369:                                                 push(@possroles,$role);
                   5370:                                             }
                   5371:                                         } else {
                   5372:                                             foreach my $status (@okstatus) {
                   5373:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5374:                                                     push(@possroles,$role);
                   5375:                                                     last;
                   5376:                                                 }
                   5377:                                             }
                   5378:                                         }
                   5379:                                     }
                   5380:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5381:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5382:                                         if ($curraccess eq 'exc') {
                   5383:                                             push(@possroles,$role);
                   5384:                                         }
                   5385:                                     } elsif ($curraccess eq 'inc') {
                   5386:                                         push(@possroles,$role);
                   5387:                                     }
                   5388:                                 }
                   5389:                             }
                   5390:                         }
                   5391:                     }
                   5392:                 }
                   5393:             }
                   5394:         }
                   5395:     }
                   5396:     unless (ref($description) eq 'HASH') {
                   5397:         if (ref($roles_by_num) eq 'ARRAY') {
                   5398:             my %desc;
                   5399:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5400:             $description = \%desc;
                   5401:         } else {
                   5402:             $description = {};
                   5403:         }
                   5404:     }
                   5405:     return (\@possroles,$description);
                   5406: }
                   5407: 
1.399     www      5408: # ----------------------------------------------------- Frontpage Announcements
                   5409: #
                   5410: #
                   5411: 
                   5412: sub postannounce {
                   5413:     my ($server,$text)=@_;
1.844     albertel 5414:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5415:     unless ($text=~/\w/) { $text=''; }
                   5416:     return &reply('setannounce:'.&escape($text),$server);
                   5417: }
                   5418: 
                   5419: sub getannounce {
1.448     albertel 5420: 
1.1172.2.96  raeburn  5421:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5422: 	my $announcement='';
1.800     albertel 5423: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5424: 	close($fh);
1.399     www      5425: 	if ($announcement=~/\w/) { 
                   5426: 	    return 
                   5427:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5428:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5429: 	} else {
                   5430: 	    return '';
                   5431: 	}
                   5432:     } else {
                   5433: 	return '';
                   5434:     }
1.351     www      5435: }
1.353     www      5436: 
                   5437: # ---------------------------------------------------------- Course ID routines
                   5438: # Deal with domain's nohist_courseid.db files
                   5439: #
                   5440: 
                   5441: sub courseidput {
1.921     raeburn  5442:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5443:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5444:     my $outcome;
                   5445:     if ($caller eq 'timeonly') {
                   5446:         my $cids = '';
                   5447:         foreach my $item (keys(%$storehash)) {
                   5448:             $cids.=&escape($item).'&';
                   5449:         }
                   5450:         $cids=~s/\&$//;
                   5451:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5452:                           $coursehome);       
                   5453:     } else {
                   5454:         my $items = '';
                   5455:         foreach my $item (keys(%$storehash)) {
                   5456:             $items.= &escape($item).'='.
                   5457:                      &freeze_escape($$storehash{$item}).'&';
                   5458:         }
                   5459:         $items=~s/\&$//;
                   5460:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5461:                           $coursehome);
1.918     raeburn  5462:     }
                   5463:     if ($outcome eq 'unknown_cmd') {
                   5464:         my $what;
                   5465:         foreach my $cid (keys(%$storehash)) {
                   5466:             $what .= &escape($cid).'=';
1.921     raeburn  5467:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5468:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5469:             }
                   5470:             $what =~ s/\:$/&/;
                   5471:         }
                   5472:         $what =~ s/\&$//;  
                   5473:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5474:     } else {
                   5475:         return $outcome;
                   5476:     }
1.353     www      5477: }
                   5478: 
                   5479: sub courseiddump {
1.921     raeburn  5480:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5481:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5482:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5483:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5484:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5485:     my $as_hash = 1;
                   5486:     my %returnhash;
                   5487:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5488:     my %libserv = &all_library();
                   5489:     foreach my $tryserver (keys(%libserv)) {
                   5490:         if ( (  $hostidflag == 1 
                   5491: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5492: 	     || (!defined($hostidflag)) ) {
                   5493: 
1.918     raeburn  5494: 	    if (($domfilter eq '') ||
                   5495: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5496:                 my $rep;
                   5497:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5498:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5499:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5500:                                 &escape($descfilter), &escape($instcodefilter),
                   5501:                                 &escape($ownerfilter), &escape($coursefilter),
                   5502:                                 &escape($typefilter), &escape($regexp_ok),
                   5503:                                 $as_hash, &escape($selfenrollonly),
                   5504:                                 &escape($catfilter), $showhidden, $caller,
                   5505:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5506:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5507:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5508:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5509:                 } else {
                   5510:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5511:                              $sincefilter.':'.&escape($descfilter).':'.
                   5512:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5513:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5514:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5515:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5516:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5517:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5518:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5519:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5520:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5521:                 }
                   5522: 
1.918     raeburn  5523:                 my @pairs=split(/\&/,$rep);
                   5524:                 foreach my $item (@pairs) {
                   5525:                     my ($key,$value)=split(/\=/,$item,2);
                   5526:                     $key = &unescape($key);
                   5527:                     next if ($key =~ /^error: 2 /);
                   5528:                     my $result = &thaw_unescape($value);
                   5529:                     if (ref($result) eq 'HASH') {
                   5530:                         $returnhash{$key}=$result;
                   5531:                     } else {
1.921     raeburn  5532:                         my @responses = split(/:/,$value);
                   5533:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5534:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5535:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5536:                         }
1.1008    raeburn  5537:                     }
1.353     www      5538:                 }
                   5539:             }
                   5540:         }
                   5541:     }
                   5542:     return %returnhash;
                   5543: }
                   5544: 
1.1055    raeburn  5545: sub courselastaccess {
                   5546:     my ($cdom,$cnum,$hostidref) = @_;
                   5547:     my %returnhash;
                   5548:     if ($cdom && $cnum) {
                   5549:         my $chome = &homeserver($cnum,$cdom);
                   5550:         if ($chome ne 'no_host') {
                   5551:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5552:             &extract_lastaccess(\%returnhash,$rep);
                   5553:         }
                   5554:     } else {
                   5555:         if (!$cdom) { $cdom=''; }
                   5556:         my %libserv = &all_library();
                   5557:         foreach my $tryserver (keys(%libserv)) {
                   5558:             if (ref($hostidref) eq 'ARRAY') {
                   5559:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5560:             } 
                   5561:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5562:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5563:                 &extract_lastaccess(\%returnhash,$rep);
                   5564:             }
                   5565:         }
                   5566:     }
                   5567:     return %returnhash;
                   5568: }
                   5569: 
                   5570: sub extract_lastaccess {
                   5571:     my ($returnhash,$rep) = @_;
                   5572:     if (ref($returnhash) eq 'HASH') {
                   5573:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5574:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5575:                  $rep eq '') {
                   5576:             my @pairs=split(/\&/,$rep);
                   5577:             foreach my $item (@pairs) {
                   5578:                 my ($key,$value)=split(/\=/,$item,2);
                   5579:                 $key = &unescape($key);
                   5580:                 next if ($key =~ /^error: 2 /);
                   5581:                 $returnhash->{$key} = &thaw_unescape($value);
                   5582:             }
                   5583:         }
                   5584:     }
                   5585:     return;
                   5586: }
                   5587: 
1.658     raeburn  5588: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5589: 
                   5590: sub dcmailput {
1.685     raeburn  5591:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5592:     my $status = &Apache::lonnet::critical(
1.740     www      5593:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5594:        &escape($message),$server);
1.662     raeburn  5595:     return $status;
                   5596: }
                   5597: 
1.658     raeburn  5598: sub dcmaildump {
                   5599:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5600:     my %returnhash=();
1.846     albertel 5601: 
                   5602:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5603:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5604:                                                          &escape($enddate).':';
                   5605: 	my @esc_senders=map { &escape($_)} @$senders;
                   5606: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5607: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5608:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5609:             if (($key) && ($value)) {
                   5610:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5611:             }
                   5612:         }
                   5613:     }
                   5614:     return %returnhash;
                   5615: }
1.662     raeburn  5616: # ---------------------------------------------------------- Domain roles
                   5617: 
                   5618: sub get_domain_roles {
                   5619:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5620:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5621:         $startdate = '.';
                   5622:     }
1.1018    raeburn  5623:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5624:         $enddate = '.';
                   5625:     }
1.922     raeburn  5626:     my $rolelist;
                   5627:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5628:         $rolelist = join('&',@{$roles});
1.922     raeburn  5629:     }
1.662     raeburn  5630:     my %personnel = ();
1.841     albertel 5631: 
                   5632:     my %servers = &get_servers($dom,'library');
                   5633:     foreach my $tryserver (keys(%servers)) {
                   5634: 	%{$personnel{$tryserver}}=();
                   5635: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5636: 					    &escape($startdate).':'.
                   5637: 					    &escape($enddate).':'.
                   5638: 					    &escape($rolelist), $tryserver))) {
                   5639: 	    my ($key,$value) = split(/\=/,$line,2);
                   5640: 	    if (($key) && ($value)) {
                   5641: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5642: 	    }
                   5643: 	}
1.662     raeburn  5644:     }
                   5645:     return %personnel;
                   5646: }
1.658     raeburn  5647: 
1.1172.2.89  raeburn  5648: sub get_active_domroles {
                   5649:     my ($dom,$roles) = @_;
                   5650:     return () unless (ref($roles) eq 'ARRAY');
                   5651:     my $now = time;
                   5652:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5653:     my %domroles;
                   5654:     foreach my $server (keys(%dompersonnel)) {
                   5655:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5656:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5657:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5658:         }
                   5659:     }
                   5660:     return %domroles;
                   5661: }
                   5662: 
1.1057    www      5663: # ----------------------------------------------------------- Interval timing 
1.149     www      5664: 
1.1153    www      5665: {
                   5666: # Caches needed for speedup of navmaps
                   5667: # We don't want to cache this for very long at all (5 seconds at most)
                   5668: # 
                   5669: # The user for whom we cache
                   5670: my $cachedkey='';
                   5671: # The cached times for this user
                   5672: my %cachedtimes=();
                   5673: # When this was last done
1.1172.2.66  raeburn  5674: my $cachedtime='';
1.1153    www      5675: 
                   5676: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5677:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5678:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5679:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5680:22):         (!$ignorecache)) {
1.1154    raeburn  5681:         return;
                   5682:     }
                   5683:     $cachedtime=time;
                   5684:     $cachedkey=$uname.':'.$udom;
                   5685:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5686: }
                   5687: 
1.504     albertel 5688: sub get_first_access {
1.1172.2.146.  .1(raebu 5689:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5690:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5691:     if ($argsymb) { $symb=$argsymb; }
                   5692:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5693:     if ($argmap) { $map = $argmap; }
1.926     albertel 5694:     if ($type eq 'course') {
                   5695: 	$res='course';
                   5696:     } elsif ($type eq 'map') {
1.588     albertel 5697: 	$res=&symbread($map);
                   5698:     } else {
                   5699: 	$res=$symb;
                   5700:     }
1.1172.2.146.  .1(raebu 5701:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5702:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5703: }
                   5704: 
                   5705: sub set_first_access {
1.1162    raeburn  5706:     my ($type,$interval)=@_;
1.790     albertel 5707:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5708:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5709:     if ($type eq 'course') {
                   5710: 	$res='course';
                   5711:     } elsif ($type eq 'map') {
1.588     albertel 5712: 	$res=&symbread($map);
                   5713:     } else {
                   5714: 	$res=$symb;
                   5715:     }
1.1153    www      5716:     $cachedkey='';
1.1162    raeburn  5717:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5718:     if ($firstaccess) {
                   5719:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5720:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5721:                  "in $courseid");
                   5722:         return 'already_set';
                   5723:     } else {
1.1162    raeburn  5724:         my $start = time;
                   5725: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5726:                           $udom,$uname);
                   5727:         if ($putres eq 'ok') {
                   5728:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5729:                  $udom,$uname); 
                   5730:             &appenv(
                   5731:                      {
                   5732:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5733:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5734:                      }
                   5735:                   );
1.1172.2.97  raeburn  5736:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5737:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5738:             }
1.1172.2.102  raeburn  5739:         } elsif ($putres ne 'refused') {
                   5740:             &logthis("Result: $putres when attempting to set first access time ".
                   5741:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5742:         }
                   5743:         return $putres;
1.505     albertel 5744:     }
                   5745:     return 'already_set';
1.504     albertel 5746: }
1.1153    www      5747: }
1.1172.2.32  raeburn  5748: 
                   5749: sub checkout {
                   5750:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5751:     my $now=time;
                   5752:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5753:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5754:     my $infostr=&escape(
                   5755:                  'CHECKOUTTOKEN&'.
                   5756:                  $tuname.'&'.
                   5757:                  $tudom.'&'.
                   5758:                  $tcrsid.'&'.
                   5759:                  $symb.'&'.
1.1172.2.134  raeburn  5760:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5761:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5762:     if ($token=~/^error\:/) {
                   5763:         &logthis("<font color=\"blue\">WARNING: ".
                   5764:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5765:                  "</font>");
                   5766:         return '';
                   5767:     }
                   5768: 
                   5769:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5770:     $token=~tr/a-z/A-Z/;
                   5771: 
                   5772:     my %infohash=('resource.0.outtoken' => $token,
                   5773:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5774:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5775: 
                   5776:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5777:        return '';
                   5778:     } else {
                   5779:         &logthis("<font color=\"blue\">WARNING: ".
                   5780:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5781:                  "</font>");
                   5782:     }
                   5783: 
                   5784:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5785:                          &escape('Checkout '.$infostr.' - '.
                   5786:                                                  $token)) ne 'ok') {
                   5787:         return '';
                   5788:     } else {
                   5789:         &logthis("<font color=\"blue\">WARNING: ".
                   5790:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5791:                  "</font>");
                   5792:     }
                   5793:     return $token;
                   5794: }
                   5795: 
                   5796: # ------------------------------------------------------------ Check in an item
                   5797: 
                   5798: sub checkin {
                   5799:     my $token=shift;
                   5800:     my $now=time;
                   5801:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5802:     $lonhost=~tr/A-Z/a-z/;
                   5803:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5804:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5805:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5806:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5807:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5808: 
                   5809:     unless (($tuname) && ($tudom)) {
                   5810:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5811:         return '';
                   5812:     }
                   5813: 
                   5814:     unless (&allowed('mgr',$tcrsid)) {
                   5815:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5816:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5817:         return '';
                   5818:     }
                   5819: 
                   5820:     my %infohash=('resource.0.intoken' => $token,
                   5821:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5822:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5823: 
                   5824:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5825:        return '';
                   5826:     }
                   5827: 
                   5828:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5829:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5830:         return '';
                   5831:     }
                   5832: 
                   5833:     return ($symb,$tuname,$tudom,$tcrsid);
                   5834: }
                   5835: 
1.110     www      5836: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5837: 
                   5838: sub expirespread {
                   5839:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5840:     my $cid=$env{'request.course.id'}; 
1.110     www      5841:     if ($cid) {
                   5842:        my $now=time;
                   5843:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5844:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5845:                             $env{'course.'.$cid.'.num'}.
1.110     www      5846: 	        	    ':nohist_expirationdates:'.
                   5847:                             &escape($key).'='.$now,
1.620     albertel 5848:                             $env{'course.'.$cid.'.home'})
1.110     www      5849:     }
                   5850:     return 'ok';
1.14      www      5851: }
                   5852: 
1.109     www      5853: # ----------------------------------------------------- Devalidate Spreadsheets
                   5854: 
                   5855: sub devalidate {
1.325     www      5856:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5857:     my $cid=$env{'request.course.id'}; 
1.109     www      5858:     if ($cid) {
1.391     matthew  5859:         # delete the stored spreadsheets for
                   5860:         # - the student level sheet of this user in course's homespace
                   5861:         # - the assessment level sheet for this resource 
                   5862:         #   for this user in user's homespace
1.553     albertel 5863: 	# - current conditional state info
1.325     www      5864: 	my $key=$uname.':'.$udom.':';
1.109     www      5865:         my $status=
1.299     matthew  5866: 	    &del('nohist_calculatedsheets',
1.391     matthew  5867: 		 [$key.'studentcalc:'],
1.620     albertel 5868: 		 $env{'course.'.$cid.'.domain'},
                   5869: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5870: 		.' '.
                   5871: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5872: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5873:         unless ($status eq 'ok ok') {
                   5874:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5875:                     $uname.' at '.$udom.' for '.
1.109     www      5876: 		    $symb.': '.$status);
1.133     albertel 5877:         }
1.553     albertel 5878: 	&delenv('user.state.'.$cid);
1.109     www      5879:     }
                   5880: }
                   5881: 
1.265     albertel 5882: sub get_scalar {
                   5883:     my ($string,$end) = @_;
                   5884:     my $value;
                   5885:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5886: 	$value = $1;
                   5887:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5888: 	$value = $1;
                   5889:     }
                   5890:     return &unescape($value);
                   5891: }
                   5892: 
                   5893: sub array2str {
                   5894:   my (@array) = @_;
                   5895:   my $result=&arrayref2str(\@array);
                   5896:   $result=~s/^__ARRAY_REF__//;
                   5897:   $result=~s/__END_ARRAY_REF__$//;
                   5898:   return $result;
                   5899: }
                   5900: 
1.204     albertel 5901: sub arrayref2str {
                   5902:   my ($arrayref) = @_;
1.265     albertel 5903:   my $result='__ARRAY_REF__';
1.204     albertel 5904:   foreach my $elem (@$arrayref) {
1.265     albertel 5905:     if(ref($elem) eq 'ARRAY') {
                   5906:       $result.=&arrayref2str($elem).'&';
                   5907:     } elsif(ref($elem) eq 'HASH') {
                   5908:       $result.=&hashref2str($elem).'&';
                   5909:     } elsif(ref($elem)) {
                   5910:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5911:     } else {
                   5912:       $result.=&escape($elem).'&';
                   5913:     }
                   5914:   }
                   5915:   $result=~s/\&$//;
1.265     albertel 5916:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5917:   return $result;
                   5918: }
                   5919: 
1.168     albertel 5920: sub hash2str {
1.204     albertel 5921:   my (%hash) = @_;
                   5922:   my $result=&hashref2str(\%hash);
1.265     albertel 5923:   $result=~s/^__HASH_REF__//;
                   5924:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5925:   return $result;
                   5926: }
                   5927: 
                   5928: sub hashref2str {
                   5929:   my ($hashref)=@_;
1.265     albertel 5930:   my $result='__HASH_REF__';
1.800     albertel 5931:   foreach my $key (sort(keys(%$hashref))) {
                   5932:     if (ref($key) eq 'ARRAY') {
                   5933:       $result.=&arrayref2str($key).'=';
                   5934:     } elsif (ref($key) eq 'HASH') {
                   5935:       $result.=&hashref2str($key).'=';
                   5936:     } elsif (ref($key)) {
1.265     albertel 5937:       $result.='=';
1.800     albertel 5938:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5939:     } else {
1.1132    raeburn  5940: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5941:     }
                   5942: 
1.800     albertel 5943:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5944:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5945:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5946:       $result.=&hashref2str($hashref->{$key}).'&';
                   5947:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5948:        $result.='&';
1.800     albertel 5949:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5950:     } else {
1.800     albertel 5951:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5952:     }
                   5953:   }
1.168     albertel 5954:   $result=~s/\&$//;
1.265     albertel 5955:   $result .= '__END_HASH_REF__';
1.168     albertel 5956:   return $result;
                   5957: }
                   5958: 
                   5959: sub str2hash {
1.265     albertel 5960:     my ($string)=@_;
                   5961:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5962:     return %$hash;
                   5963: }
                   5964: 
                   5965: sub str2hashref {
1.168     albertel 5966:   my ($string) = @_;
1.265     albertel 5967: 
                   5968:   my %hash;
                   5969: 
                   5970:   if($string !~ /^__HASH_REF__/) {
                   5971:       if (! ($string eq '' || !defined($string))) {
                   5972: 	  $hash{'error'}='Not hash reference';
                   5973:       }
                   5974:       return (\%hash, $string);
                   5975:   }
                   5976: 
                   5977:   $string =~ s/^__HASH_REF__//;
                   5978: 
                   5979:   while($string !~ /^__END_HASH_REF__/) {
                   5980:       #key
                   5981:       my $key='';
                   5982:       if($string =~ /^__HASH_REF__/) {
                   5983:           ($key, $string)=&str2hashref($string);
                   5984:           if(defined($key->{'error'})) {
                   5985:               $hash{'error'}='Bad data';
                   5986:               return (\%hash, $string);
                   5987:           }
                   5988:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5989:           ($key, $string)=&str2arrayref($string);
                   5990:           if($key->[0] eq 'Array reference error') {
                   5991:               $hash{'error'}='Bad data';
                   5992:               return (\%hash, $string);
                   5993:           }
                   5994:       } else {
                   5995:           $string =~ s/^(.*?)=//;
1.267     albertel 5996: 	  $key=&unescape($1);
1.265     albertel 5997:       }
                   5998:       $string =~ s/^=//;
                   5999: 
                   6000:       #value
                   6001:       my $value='';
                   6002:       if($string =~ /^__HASH_REF__/) {
                   6003:           ($value, $string)=&str2hashref($string);
                   6004:           if(defined($value->{'error'})) {
                   6005:               $hash{'error'}='Bad data';
                   6006:               return (\%hash, $string);
                   6007:           }
                   6008:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6009:           ($value, $string)=&str2arrayref($string);
                   6010:           if($value->[0] eq 'Array reference error') {
                   6011:               $hash{'error'}='Bad data';
                   6012:               return (\%hash, $string);
                   6013:           }
                   6014:       } else {
                   6015: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6016:       }
                   6017:       $string =~ s/^&//;
                   6018: 
                   6019:       $hash{$key}=$value;
1.204     albertel 6020:   }
1.265     albertel 6021: 
                   6022:   $string =~ s/^__END_HASH_REF__//;
                   6023: 
                   6024:   return (\%hash, $string);
1.204     albertel 6025: }
                   6026: 
                   6027: sub str2array {
1.265     albertel 6028:     my ($string)=@_;
                   6029:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6030:     return @$array;
                   6031: }
                   6032: 
                   6033: sub str2arrayref {
1.204     albertel 6034:   my ($string) = @_;
1.265     albertel 6035:   my @array;
                   6036: 
                   6037:   if($string !~ /^__ARRAY_REF__/) {
                   6038:       if (! ($string eq '' || !defined($string))) {
                   6039: 	  $array[0]='Array reference error';
                   6040:       }
                   6041:       return (\@array, $string);
                   6042:   }
                   6043: 
                   6044:   $string =~ s/^__ARRAY_REF__//;
                   6045: 
                   6046:   while($string !~ /^__END_ARRAY_REF__/) {
                   6047:       my $value='';
                   6048:       if($string =~ /^__HASH_REF__/) {
                   6049:           ($value, $string)=&str2hashref($string);
                   6050:           if(defined($value->{'error'})) {
                   6051:               $array[0] ='Array reference error';
                   6052:               return (\@array, $string);
                   6053:           }
                   6054:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6055:           ($value, $string)=&str2arrayref($string);
                   6056:           if($value->[0] eq 'Array reference error') {
                   6057:               $array[0] ='Array reference error';
                   6058:               return (\@array, $string);
                   6059:           }
                   6060:       } else {
                   6061: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6062:       }
                   6063:       $string =~ s/^&//;
                   6064: 
                   6065:       push(@array, $value);
1.191     harris41 6066:   }
1.265     albertel 6067: 
                   6068:   $string =~ s/^__END_ARRAY_REF__//;
                   6069: 
                   6070:   return (\@array, $string);
1.168     albertel 6071: }
                   6072: 
1.167     albertel 6073: # -------------------------------------------------------------------Temp Store
                   6074: 
1.168     albertel 6075: sub tmpreset {
                   6076:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6077:   if (!$symb) {
                   6078:     $symb=&symbread();
1.620     albertel 6079:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6080:   }
                   6081:   $symb=escape($symb);
                   6082: 
1.620     albertel 6083:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6084:   $namespace=~s/\//\_/g;
                   6085:   $namespace=~s/\W//g;
                   6086: 
1.620     albertel 6087:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6088:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6089:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6090:       $stuname=&get_requestor_ip();
1.591     albertel 6091:   }
1.1117    foxr     6092:   my $path=LONCAPA::tempdir();
1.168     albertel 6093:   my %hash;
                   6094:   if (tie(%hash,'GDBM_File',
                   6095: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6096: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6097:     foreach my $key (keys(%hash)) {
1.180     albertel 6098:       if ($key=~ /:$symb/) {
1.168     albertel 6099: 	delete($hash{$key});
                   6100:       }
                   6101:     }
                   6102:   }
                   6103: }
                   6104: 
1.167     albertel 6105: sub tmpstore {
1.168     albertel 6106:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6107: 
                   6108:   if (!$symb) {
                   6109:     $symb=&symbread();
1.620     albertel 6110:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6111:   }
                   6112:   $symb=escape($symb);
                   6113: 
                   6114:   if (!$namespace) {
                   6115:     # I don't think we would ever want to store this for a course.
                   6116:     # it seems this will only be used if we don't have a course.
1.620     albertel 6117:     #$namespace=$env{'request.course.id'};
1.168     albertel 6118:     #if (!$namespace) {
1.620     albertel 6119:       $namespace=$env{'request.state'};
1.168     albertel 6120:     #}
                   6121:   }
                   6122:   $namespace=~s/\//\_/g;
                   6123:   $namespace=~s/\W//g;
1.620     albertel 6124:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6125:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6126:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6127:       $stuname=&get_requestor_ip();
1.591     albertel 6128:   }
1.168     albertel 6129:   my $now=time;
                   6130:   my %hash;
1.1117    foxr     6131:   my $path=LONCAPA::tempdir();
1.168     albertel 6132:   if (tie(%hash,'GDBM_File',
                   6133: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6134: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6135:     $hash{"version:$symb"}++;
                   6136:     my $version=$hash{"version:$symb"};
                   6137:     my $allkeys=''; 
                   6138:     foreach my $key (keys(%$storehash)) {
                   6139:       $allkeys.=$key.':';
1.591     albertel 6140:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6141:     }
                   6142:     $hash{"$version:$symb:timestamp"}=$now;
                   6143:     $allkeys.='timestamp';
                   6144:     $hash{"$version:keys:$symb"}=$allkeys;
                   6145:     if (untie(%hash)) {
                   6146:       return 'ok';
                   6147:     } else {
                   6148:       return "error:$!";
                   6149:     }
                   6150:   } else {
                   6151:     return "error:$!";
                   6152:   }
                   6153: }
1.167     albertel 6154: 
1.168     albertel 6155: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6156: 
1.168     albertel 6157: sub tmprestore {
                   6158:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6159: 
1.168     albertel 6160:   if (!$symb) {
                   6161:     $symb=&symbread();
1.620     albertel 6162:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6163:   }
                   6164:   $symb=escape($symb);
                   6165: 
1.620     albertel 6166:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6167: 
1.620     albertel 6168:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6169:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6170:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6171:       $stuname=&get_requestor_ip();
1.591     albertel 6172:   }
1.168     albertel 6173:   my %returnhash;
                   6174:   $namespace=~s/\//\_/g;
                   6175:   $namespace=~s/\W//g;
                   6176:   my %hash;
1.1117    foxr     6177:   my $path=LONCAPA::tempdir();
1.168     albertel 6178:   if (tie(%hash,'GDBM_File',
                   6179: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6180: 	  &GDBM_READER(),0640)) {
1.168     albertel 6181:     my $version=$hash{"version:$symb"};
                   6182:     $returnhash{'version'}=$version;
                   6183:     my $scope;
                   6184:     for ($scope=1;$scope<=$version;$scope++) {
                   6185:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6186:       my @keys=split(/:/,$vkeys);
                   6187:       my $key;
                   6188:       $returnhash{"$scope:keys"}=$vkeys;
                   6189:       foreach $key (@keys) {
1.591     albertel 6190: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6191: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6192:       }
                   6193:     }
1.168     albertel 6194:     if (!(untie(%hash))) {
                   6195:       return "error:$!";
                   6196:     }
                   6197:   } else {
                   6198:     return "error:$!";
                   6199:   }
                   6200:   return %returnhash;
1.167     albertel 6201: }
                   6202: 
1.9       www      6203: # ----------------------------------------------------------------------- Store
                   6204: 
                   6205: sub store {
1.1172.2.64  raeburn  6206:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6207:     my $home='';
                   6208: 
1.168     albertel 6209:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6210: 
1.213     www      6211:     $symb=&symbclean($symb);
1.122     albertel 6212:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6213: 
1.620     albertel 6214:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6215:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6216: 
                   6217:     &devalidate($symb,$stuname,$domain);
1.109     www      6218: 
                   6219:     $symb=escape($symb);
1.187     www      6220:     if (!$namespace) { 
1.620     albertel 6221:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6222:           return ''; 
                   6223:        } 
                   6224:     }
1.620     albertel 6225:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6226: 
1.1172.2.138  raeburn  6227:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6228:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6229: 
1.12      www      6230:     my $namevalue='';
1.800     albertel 6231:     foreach my $key (keys(%$storehash)) {
                   6232:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6233:     }
1.12      www      6234:     $namevalue=~s/\&$//;
1.187     www      6235:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6236:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6237: }
                   6238: 
1.47      www      6239: # -------------------------------------------------------------- Critical Store
                   6240: 
                   6241: sub cstore {
1.1172.2.64  raeburn  6242:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6243:     my $home='';
                   6244: 
1.168     albertel 6245:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6246: 
1.213     www      6247:     $symb=&symbclean($symb);
1.122     albertel 6248:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6249: 
1.620     albertel 6250:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6251:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6252: 
                   6253:     &devalidate($symb,$stuname,$domain);
1.109     www      6254: 
                   6255:     $symb=escape($symb);
1.187     www      6256:     if (!$namespace) { 
1.620     albertel 6257:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6258:           return ''; 
                   6259:        } 
                   6260:     }
1.620     albertel 6261:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6262: 
1.1172.2.138  raeburn  6263:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6264:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6265: 
1.47      www      6266:     my $namevalue='';
1.800     albertel 6267:     foreach my $key (keys(%$storehash)) {
                   6268:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6269:     }
1.47      www      6270:     $namevalue=~s/\&$//;
1.187     www      6271:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6272:     return critical
1.1172.2.64  raeburn  6273:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6274: }
                   6275: 
1.9       www      6276: # --------------------------------------------------------------------- Restore
                   6277: 
                   6278: sub restore {
1.124     www      6279:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6280:     my $home='';
                   6281: 
1.168     albertel 6282:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6283: 
1.122     albertel 6284:     if (!$symb) {
1.1172.2.26  raeburn  6285:         return if ($namespace eq 'courserequests');
                   6286:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6287:     } else {
1.1172.2.26  raeburn  6288:         unless ($namespace eq 'courserequests') {
                   6289:             $symb=&escape(&symbclean($symb));
                   6290:         }
1.122     albertel 6291:     }
1.188     www      6292:     if (!$namespace) { 
1.620     albertel 6293:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6294:           return ''; 
                   6295:        } 
                   6296:     }
1.620     albertel 6297:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6298:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6299:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6300:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6301: 
1.12      www      6302:     my %returnhash=();
1.800     albertel 6303:     foreach my $line (split(/\&/,$answer)) {
                   6304: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6305:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6306:     }
1.75      www      6307:     my $version;
                   6308:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6309:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6310:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6311:        }
1.75      www      6312:     }
1.13      www      6313:     return %returnhash;
1.34      www      6314: }
                   6315: 
                   6316: # ---------------------------------------------------------- Course Description
1.1118    foxr     6317: #
                   6318: #  
1.34      www      6319: 
                   6320: sub coursedescription {
1.731     albertel 6321:     my ($courseid,$args)=@_;
1.34      www      6322:     $courseid=~s/^\///;
1.49      www      6323:     $courseid=~s/\_/\//g;
1.34      www      6324:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6325:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6326:     my $normalid=$cdomain.'_'.$cnum;
                   6327:     # need to always cache even if we get errors otherwise we keep 
                   6328:     # trying and trying and trying to get the course description.
                   6329:     my %envhash=();
                   6330:     my %returnhash=();
1.731     albertel 6331:     
                   6332:     my $expiretime=600;
                   6333:     if ($env{'request.course.id'} eq $normalid) {
                   6334: 	$expiretime=120;
                   6335:     }
                   6336: 
                   6337:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6338:     if (!$args->{'freshen_cache'}
                   6339: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6340: 	foreach my $key (keys(%env)) {
                   6341: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6342: 	    my ($setting) = $1;
                   6343: 	    $returnhash{$setting} = $env{$key};
                   6344: 	}
                   6345: 	return %returnhash;
                   6346:     }
                   6347: 
1.1118    foxr     6348:     # get the data again
                   6349: 
1.731     albertel 6350:     if (!$args->{'one_time'}) {
                   6351: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6352:     }
1.811     albertel 6353: 
1.34      www      6354:     if ($chome ne 'no_host') {
1.302     albertel 6355:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6356:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6357: 	   my $username = $env{'user.name'}; # Defult username
                   6358: 	   if(defined $args->{'user'}) {
                   6359: 	       $username = $args->{'user'};
                   6360: 	   }
1.129     albertel 6361:            $returnhash{'home'}= $chome;
                   6362: 	   $returnhash{'domain'} = $cdomain;
                   6363: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6364:            if (!defined($returnhash{'type'})) {
                   6365:                $returnhash{'type'} = 'Course';
                   6366:            }
1.130     albertel 6367:            while (my ($name,$value) = each %returnhash) {
1.53      www      6368:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6369:            }
1.270     www      6370:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6371:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6372: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6373:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6374:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6375:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6376:        }
                   6377:     }
1.731     albertel 6378:     if (!$args->{'one_time'}) {
1.949     raeburn  6379: 	&appenv(\%envhash);
1.731     albertel 6380:     }
1.302     albertel 6381:     return %returnhash;
1.461     www      6382: }
                   6383: 
1.1080    raeburn  6384: sub update_released_required {
                   6385:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6386:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6387:         $cid = $env{'request.course.id'};
                   6388:         $cdom = $env{'course.'.$cid.'.domain'};
                   6389:         $cnum = $env{'course.'.$cid.'.num'};
                   6390:         $chome = $env{'course.'.$cid.'.home'};
                   6391:     }
                   6392:     if ($needsrelease) {
                   6393:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6394:         my $needsupdate;
                   6395:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6396:             $needsupdate = 1;
                   6397:         } else {
                   6398:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6399:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6400:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6401:                 $needsupdate = 1;
                   6402:             }
                   6403:         }
                   6404:         if ($needsupdate) {
                   6405:             my %needshash = (
                   6406:                              'internal.releaserequired' => $needsrelease,
                   6407:                             );
                   6408:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6409:             if ($putresult eq 'ok') {
                   6410:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6411:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6412:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6413:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6414:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6415:                 }
                   6416:             }
                   6417:         }
                   6418:     }
                   6419:     return;
                   6420: }
                   6421: 
1.461     www      6422: # -------------------------------------------------See if a user is privileged
                   6423: 
                   6424: sub privileged {
1.1172.2.23  raeburn  6425:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6426:     my $now = time;
1.1172.2.23  raeburn  6427:     my $roles;
                   6428:     if (ref($possroles) eq 'ARRAY') {
                   6429:         $roles = $possroles;
                   6430:     } else {
                   6431:         $roles = ['dc','su'];
                   6432:     }
                   6433:     if (ref($possdomains) eq 'ARRAY') {
                   6434:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6435:         foreach my $dom (@{$possdomains}) {
                   6436:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6437:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6438:                 foreach my $role (@{$roles}) {
                   6439:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6440:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6441:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6442:                             return 1 unless (($end && $end < $now) ||
                   6443:                                              ($start && $start > $now));
                   6444:                         }
                   6445:                     }
                   6446:                 }
                   6447:             }
                   6448:         }
                   6449:     } else {
                   6450:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6451:         my $now = time;
1.1170    droeschl 6452: 
1.1172.2.58  raeburn  6453:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6454:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6455:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6456:                 return 1 unless ($tend && $tend < $now)
                   6457:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6458:             }
1.1172.2.23  raeburn  6459:         }
                   6460:     }
1.461     www      6461:     return 0;
1.9       www      6462: }
1.1       albertel 6463: 
1.1172.2.23  raeburn  6464: sub privileged_by_domain {
                   6465:     my ($domains,$roles) = @_;
                   6466:     my %privileged = ();
                   6467:     my $cachetime = 60*60*24;
                   6468:     my $now = time;
                   6469:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6470:         return %privileged;
                   6471:     }
                   6472:     foreach my $dom (@{$domains}) {
                   6473:         next if (ref($privileged{$dom}) eq 'HASH');
                   6474:         my $needroles;
                   6475:         foreach my $role (@{$roles}) {
                   6476:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6477:             if (defined($cached)) {
                   6478:                 if (ref($result) eq 'HASH') {
                   6479:                     $privileged{$dom}{$role} = $result;
                   6480:                 }
                   6481:             } else {
                   6482:                 $needroles = 1;
                   6483:             }
                   6484:         }
                   6485:         if ($needroles) {
                   6486:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6487:             $privileged{$dom} = {};
                   6488:             foreach my $server (keys(%dompersonnel)) {
                   6489:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6490:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6491:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6492:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6493:                         next if ($end && $end < $now);
                   6494:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6495:                             $dompersonnel{$server}{$item};
                   6496:                     }
                   6497:                 }
                   6498:             }
                   6499:             if (ref($privileged{$dom}) eq 'HASH') {
                   6500:                 foreach my $role (@{$roles}) {
                   6501:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6502:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6503:                     } else {
                   6504:                         my %hash = ();
                   6505:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6506:                     }
                   6507:                 }
                   6508:             }
                   6509:         }
                   6510:     }
                   6511:     return %privileged;
                   6512: }
                   6513: 
1.103     harris41 6514: # -------------------------------------------------------- Get user privileges
1.11      www      6515: 
                   6516: sub rolesinit {
1.1169    droeschl 6517:     my ($domain, $username) = @_;
                   6518:     my %userroles = ('user.login.time' => time);
                   6519:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6520: 
                   6521:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6522:     # also, blocking can be triggered by an activating timer
                   6523:     # it's saved in the user's %env.
                   6524:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6525:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6526:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6527:         %timerintchk, %timerintenv);
                   6528: 
1.1162    raeburn  6529:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6530:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6531:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6532:     }
1.1169    droeschl 6533: 
1.1162    raeburn  6534:     foreach my $key (keys(%timerinterval)) {
                   6535:         my ($cid,$rest) = split(/\0/,$key);
                   6536:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6537:     }
1.1169    droeschl 6538: 
1.11      www      6539:     my %allroles=();
1.1162    raeburn  6540:     my %allgroups=();
1.11      www      6541: 
1.1172.2.58  raeburn  6542:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6543:         my $role = $rolesdump{$area};
                   6544:         $area =~ s/\_\w\w$//;
                   6545: 
                   6546:         my ($trole, $tend, $tstart, $group_privs);
                   6547: 
                   6548:         if ($role =~ /^cr/) {
                   6549:         # Custom role, defined by a user 
                   6550:         # e.g., user.role.cr/msu/smith/mynewrole
                   6551:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6552:                 $trole = $1;
                   6553:                 ($tend, $tstart) = split('_', $2);
                   6554:             } else {
                   6555:                 $trole = $role;
                   6556:             }
                   6557:         } elsif ($role =~ m|^gr/|) {
                   6558:         # Role of member in a group, defined within a course/community
                   6559:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6560:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6561:             next if $tstart eq '-1';
                   6562:             ($trole, $group_privs) = split(/\//, $trole);
                   6563:             $group_privs = &unescape($group_privs);
                   6564:         } else {
                   6565:         # Just a normal role, defined in roles.tab
                   6566:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6567:         }
                   6568: 
                   6569:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6570:                  $username);
                   6571:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6572: 
                   6573:         # role expired or not available yet?
                   6574:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6575:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6576: 
                   6577:         next if $area eq '' or $trole eq '';
                   6578: 
                   6579:         my $spec = "$trole.$area";
                   6580:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6581: 
                   6582:         if ($trole =~ /^cr\//) {
                   6583:         # Custom role, defined by a user
                   6584:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6585:         } elsif ($trole eq 'gr') {
                   6586:         # Role of a member in a group, defined within a course/community
                   6587:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6588:             next;
                   6589:         } else {
                   6590:         # Normal role, defined in roles.tab
                   6591:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6592:         }
                   6593: 
                   6594:         my $cid = $tdomain.'_'.$trest;
                   6595:         unless ($firstaccchk{$cid}) {
                   6596:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6597:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6598:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6599:                         $coursetimerstarts{$cid}{$item}; 
                   6600:                 }
                   6601:             }
                   6602:             $firstaccchk{$cid} = 1;
                   6603:         }
                   6604:         unless ($timerintchk{$cid}) {
                   6605:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6606:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6607:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6608:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6609:                 }
1.12      www      6610:             }
1.1169    droeschl 6611:             $timerintchk{$cid} = 1;
1.191     harris41 6612:         }
1.11      www      6613:     }
1.1169    droeschl 6614: 
1.1172.2.91  raeburn  6615:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6616:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6617:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6618:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6619: 
1.1162    raeburn  6620:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6621: }
                   6622: 
1.567     raeburn  6623: sub set_arearole {
1.1172.2.19  raeburn  6624:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6625:     unless ($nolog) {
1.567     raeburn  6626: # log the associated role with the area
1.1172.2.19  raeburn  6627:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6628:     }
1.743     albertel 6629:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6630: }
                   6631: 
                   6632: sub custom_roleprivs {
                   6633:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6634:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6635:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6636:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6637:         my ($rdummy,$roledef)=
                   6638:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6639:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6640:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6641:             if (defined($syspriv)) {
1.1043    raeburn  6642:                 if ($trest =~ /^$match_community$/) {
                   6643:                     $syspriv =~ s/bre\&S//; 
                   6644:                 }
1.567     raeburn  6645:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6646:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6647:             }
                   6648:             if ($tdomain ne '') {
                   6649:                 if (defined($dompriv)) {
                   6650:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6651:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6652:                 }
                   6653:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6654:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6655:                         my $rolename = $1;
                   6656:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6657:                     }
1.567     raeburn  6658:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6659:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6660:                 }
                   6661:             }
                   6662:         }
                   6663:     }
                   6664: }
                   6665: 
1.1172.2.89  raeburn  6666: sub course_adhocrole_privs {
                   6667:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6668:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6669:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6670:         my (%currprivs,%storeprivs);
                   6671:         foreach my $item (split(/:/,$coursepriv)) {
                   6672:             my ($priv,$restrict) = split(/\&/,$item);
                   6673:             $currprivs{$priv} = $restrict;
                   6674:         }
                   6675:         my (%possadd,%possremove,%full);
                   6676:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6677:             my ($priv,$restrict)=split(/\&/,$item);
                   6678:             $full{$priv} = $restrict;
                   6679:         }
                   6680:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6681:22):             next if ($item eq '');
                   6682:22):             my ($rule,$rest) = split(/=/,$item);
                   6683:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6684:22):             foreach my $priv (split(/:/,$rest)) {
                   6685:22):                 if ($priv ne '') {
                   6686:22):                     if ($rule eq 'off') {
                   6687:22):                         $possremove{$priv} = 1;
                   6688:22):                     } else {
                   6689:22):                         $possadd{$priv} = 1;
                   6690:22):                     }
                   6691:22):                 }
                   6692:22):             }
                   6693:22):         }
                   6694:22):         foreach my $priv (sort(keys(%full))) {
                   6695:22):             if (exists($currprivs{$priv})) {
                   6696:22):                 unless (exists($possremove{$priv})) {
                   6697:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6698:22):                 }
                   6699:22):             } elsif (exists($possadd{$priv})) {
                   6700:22):                 $storeprivs{$priv} = $full{$priv};
                   6701:22):             }
                   6702:22):         }
                   6703:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6704:22):     }
                   6705:22):     return $coursepriv;
1.1172.2.89  raeburn  6706: }
                   6707: 
1.678     raeburn  6708: sub group_roleprivs {
                   6709:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6710:     my $access = 1;
                   6711:     my $now = time;
                   6712:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6713:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6714:     if ($access) {
1.811     albertel 6715:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6716:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6717:     }
                   6718: }
1.567     raeburn  6719: 
                   6720: sub standard_roleprivs {
                   6721:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6722:     if (defined($pr{$trole.':s'})) {
                   6723:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6724:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6725:     }
                   6726:     if ($tdomain ne '') {
                   6727:         if (defined($pr{$trole.':d'})) {
                   6728:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6729:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6730:         }
                   6731:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6732:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6733:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6734:         }
                   6735:     }
                   6736: }
                   6737: 
                   6738: sub set_userprivs {
1.1064    raeburn  6739:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6740:     my $author=0;
                   6741:     my $adv=0;
1.1172.2.91  raeburn  6742:     my $rar=0;
1.678     raeburn  6743:     my %grouproles = ();
                   6744:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6745:         my @groupkeys; 
1.1000    raeburn  6746:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6747:             push(@groupkeys,$role);
                   6748:         }
                   6749:         if (ref($groups_roles) eq 'HASH') {
                   6750:             foreach my $key (keys(%{$groups_roles})) {
                   6751:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6752:                     push(@groupkeys,$key);
                   6753:                 }
                   6754:             }
                   6755:         }
                   6756:         if (@groupkeys > 0) {
                   6757:             foreach my $role (@groupkeys) {
                   6758:                 my ($trole,$area,$sec,$extendedarea);
                   6759:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6760:                     $trole = $1;
                   6761:                     $area = $2;
                   6762:                     $sec = $3;
                   6763:                     $extendedarea = $area.$sec;
                   6764:                     if (exists($$allgroups{$area})) {
                   6765:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6766:                             my $spec = $trole.'.'.$extendedarea;
                   6767:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6768:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6769:                         }
1.678     raeburn  6770:                     }
                   6771:                 }
                   6772:             }
                   6773:         }
                   6774:     }
1.800     albertel 6775:     foreach my $group (keys(%grouproles)) {
                   6776:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6777:     }
1.800     albertel 6778:     foreach my $role (keys(%{$allroles})) {
                   6779:         my %thesepriv;
1.941     raeburn  6780:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6781:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6782:             if ($item ne '') {
                   6783:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6784:                 if ($restrictions eq '') {
                   6785:                     $thesepriv{$privilege}='F';
                   6786:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6787:                     $thesepriv{$privilege}.=$restrictions;
                   6788:                 }
                   6789:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6790:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6791:             }
                   6792:         }
                   6793:         my $thesestr='';
1.1104    raeburn  6794:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6795: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6796: 	}
                   6797:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6798:     }
1.1172.2.91  raeburn  6799:     return ($author,$adv,$rar);
1.567     raeburn  6800: }
                   6801: 
1.994     raeburn  6802: sub role_status {
1.1104    raeburn  6803:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6804:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6805:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6806:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6807:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6808:             $$where = '/'.$two;
1.994     raeburn  6809:             $$trolecode=$$role.'.'.$$where;
                   6810:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6811:             $$tstatus='is';
1.1104    raeburn  6812:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6813:                 $$tstatus='future';
1.1034    raeburn  6814:                 if ($$tstart<$now) {
                   6815:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6816:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6817:                             my (%allroles,%allgroups,$group_privs,
                   6818:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6819:                             my %userroles = (
                   6820:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6821:                             );
1.1064    raeburn  6822:                             @rolecodes = ('cm'); 
1.1002    raeburn  6823:                             my $spec=$$role.'.'.$$where;
                   6824:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6825:                             if ($$role =~ /^cr\//) {
                   6826:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6827:                                 push(@rolecodes,'cr');
1.1002    raeburn  6828:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6829:                                 push(@rolecodes,$$role);
1.1002    raeburn  6830:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6831:                                                     $env{'user.name'});
1.1064    raeburn  6832:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6833:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6834:                                 $group_privs = &unescape($group_privs);
                   6835:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6836:                                 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  6837:                                 &get_groups_roles($tdomain,$trest,
                   6838:                                                   \%course_roles,\@rolecodes,
                   6839:                                                   \%groups_roles);
1.1002    raeburn  6840:                             } else {
1.1064    raeburn  6841:                                 push(@rolecodes,$$role);
1.1002    raeburn  6842:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6843:                             }
1.1172.2.91  raeburn  6844:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6845:                                                                    \%groups_roles);
1.1064    raeburn  6846:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6847:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6848:                         }
                   6849:                     }
1.1034    raeburn  6850:                     $$tstatus = 'is';
1.1002    raeburn  6851:                 }
1.994     raeburn  6852:             }
                   6853:             if ($$tend) {
1.1104    raeburn  6854:                 if ($$tend<$update) {
1.994     raeburn  6855:                     $$tstatus='expired';
                   6856:                 } elsif ($$tend<$now) {
                   6857:                     $$tstatus='will_not';
                   6858:                 }
                   6859:             }
                   6860:         }
                   6861:     }
                   6862: }
                   6863: 
1.1104    raeburn  6864: sub get_groups_roles {
                   6865:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6866:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6867:                   (ref($rolecodes) eq 'ARRAY') && 
                   6868:                   (ref($groups_roles) eq 'HASH')); 
                   6869:     if (keys(%{$cdom_courseroles}) > 0) {
                   6870:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6871:         if ($cdom ne '' && $cnum ne '') {
                   6872:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6873:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6874:                     my $crsrole = $1;
                   6875:                     my $crssec = $2;
                   6876:                     if ($crsrole =~ /^cr/) {
                   6877:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6878:                             push(@{$rolecodes},'cr');
                   6879:                         }
                   6880:                     } else {
                   6881:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6882:                             push(@{$rolecodes},$crsrole);
                   6883:                         }
                   6884:                     }
                   6885:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6886:                     if ($crssec ne '') {
                   6887:                         $rolekey .= "/$crssec";
                   6888:                     }
                   6889:                     $rolekey .= './';
                   6890:                     $groups_roles->{$rolekey} = $rolecodes;
                   6891:                 }
                   6892:             }
                   6893:         }
                   6894:     }
                   6895:     return;
                   6896: }
                   6897: 
                   6898: sub delete_env_groupprivs {
                   6899:     my ($where,$courseroles,$possroles) = @_;
                   6900:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6901:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6902:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6903:         %{$courseroles->{$udom}} =
                   6904:             &get_my_roles('','','userroles',['active'],
                   6905:                           $possroles,[$udom],1);
                   6906:     }
                   6907:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6908:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6909:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6910:             my $area = '/'.$cdom.'/'.$cnum;
                   6911:             my $privkey = "user.priv.$crsrole.$area";
                   6912:             if ($crssec ne '') {
                   6913:                 $privkey .= '/'.$crssec;
                   6914:             }
                   6915:             $privkey .= ".$area/$group";
                   6916:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6917:         }
                   6918:     }
                   6919:     return;
                   6920: }
                   6921: 
1.994     raeburn  6922: sub check_adhoc_privs {
1.1172.2.86  raeburn  6923:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6924:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6925:     if ($sec) {
                   6926:         $cckey .= '/'.$sec;
                   6927:     }
1.1172.2.9  raeburn  6928:     my $setprivs;
1.994     raeburn  6929:     if ($env{$cckey}) {
                   6930:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6931:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6932:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6933:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6934:             $setprivs = 1;
1.994     raeburn  6935:         }
                   6936:     } else {
1.1172.2.87  raeburn  6937:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6938:         $setprivs = 1;
1.994     raeburn  6939:     }
1.1172.2.9  raeburn  6940:     return $setprivs;
1.994     raeburn  6941: }
                   6942: 
                   6943: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6944: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6945:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6946:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6947:     if ($sec ne '') {
                   6948:         $area .= '/'.$sec;
                   6949:     }
1.994     raeburn  6950:     my $spec = $role.'.'.$area;
                   6951:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6952:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6953:     my %rolehash = ();
1.1172.2.89  raeburn  6954:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6955:         my $rolename = $1;
1.1172.2.84  raeburn  6956:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6957:         my %domdef = &get_domain_defaults($dcdom);
                   6958:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6959:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6960:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6961:             }
                   6962:         }
1.1172.2.84  raeburn  6963:     } else {
                   6964:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6965:     }
1.1172.2.91  raeburn  6966:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6967:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6968:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6969:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6970:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6971:         &appenv( {'request.role'        => $spec,
                   6972:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6973:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6974:                  }
                   6975:                );
                   6976:         my $tadv=0;
                   6977:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6978:         &appenv({'request.role.adv'    => $tadv});
                   6979:     }
1.994     raeburn  6980: }
                   6981: 
1.12      www      6982: # --------------------------------------------------------------- get interface
                   6983: 
                   6984: sub get {
1.131     albertel 6985:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6986:    my $items='';
1.800     albertel 6987:    foreach my $item (@$storearr) {
                   6988:        $items.=&escape($item).'&';
1.191     harris41 6989:    }
1.12      www      6990:    $items=~s/\&$//;
1.620     albertel 6991:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6992:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6993:    my $uhome=&homeserver($uname,$udomain);
                   6994: 
1.133     albertel 6995:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6996:    my @pairs=split(/\&/,$rep);
1.273     albertel 6997:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6998:      return @pairs;
                   6999:    }
1.15      www      7000:    my %returnhash=();
1.42      www      7001:    my $i=0;
1.800     albertel 7002:    foreach my $item (@$storearr) {
                   7003:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7004:       $i++;
1.191     harris41 7005:    }
1.15      www      7006:    return %returnhash;
1.27      www      7007: }
                   7008: 
                   7009: # --------------------------------------------------------------- del interface
                   7010: 
                   7011: sub del {
1.133     albertel 7012:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7013:    my $items='';
1.800     albertel 7014:    foreach my $item (@$storearr) {
                   7015:        $items.=&escape($item).'&';
1.191     harris41 7016:    }
1.984     neumanie 7017: 
1.27      www      7018:    $items=~s/\&$//;
1.620     albertel 7019:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7020:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7021:    my $uhome=&homeserver($uname,$udomain);
                   7022:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7023: }
                   7024: 
                   7025: # -------------------------------------------------------------- dump interface
                   7026: 
1.1172.2.22  raeburn  7027: sub unserialize {
                   7028:     my ($rep, $escapedkeys) = @_;
                   7029: 
                   7030:     return {} if $rep =~ /^error/;
                   7031: 
                   7032:     my %returnhash=();
                   7033:     foreach my $item (split(/\&/,$rep)) {
                   7034:         my ($key, $value) = split(/=/, $item, 2);
                   7035:         $key = unescape($key) unless $escapedkeys;
                   7036:         next if $key =~ /^error: 2 /;
                   7037:         $returnhash{$key} = &thaw_unescape($value);
                   7038:     }
                   7039:     return \%returnhash;
                   7040: }
                   7041: 
                   7042: # see Lond::dump_with_regexp
                   7043: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7044: sub dump {
1.1172.2.146.  .1(raebu 7045:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7046:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7047:     if (!$uname) { $uname=$env{'user.name'}; }
                   7048:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7049: 
1.1172.2.55  raeburn  7050:     if ($regexp) {
                   7051:         $regexp=&escape($regexp);
                   7052:     } else {
                   7053:         $regexp='.';
                   7054:     }
1.1172.2.22  raeburn  7055:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7056:         # user is hosted on this machine
1.1172.2.55  raeburn  7057:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7058:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7059:         return %{&unserialize($reply, $escapedkeys)};
                   7060:     }
1.1172.2.146.  .1(raebu 7061:22):     my $rep;
                   7062:22):     if ($encrypt) {
                   7063:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7064:22):     } else {
                   7065:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7066:22):     }
1.755     albertel 7067:     my @pairs=split(/\&/,$rep);
                   7068:     my %returnhash=();
1.1098    foxr     7069:     if (!($rep =~ /^error/ )) {
                   7070: 	foreach my $item (@pairs) {
                   7071: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7072:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7073: 	    next if ($key =~ /^error: 2 /);
                   7074: 	    $returnhash{$key}=&thaw_unescape($value);
                   7075: 	}
1.755     albertel 7076:     }
                   7077:     return %returnhash;
1.407     www      7078: }
                   7079: 
1.1098    foxr     7080: 
1.717     albertel 7081: # --------------------------------------------------------- dumpstore interface
                   7082: 
                   7083: sub dumpstore {
                   7084:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7085:    # same as dump but keys must be escaped. They may contain colon separated
                   7086:    # lists of values that may themself contain colons (e.g. symbs).
                   7087:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7088: }
                   7089: 
1.407     www      7090: # -------------------------------------------------------------- keys interface
                   7091: 
                   7092: sub getkeys {
                   7093:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7094:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7095:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7096:    my $uhome=&homeserver($uname,$udomain);
                   7097:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7098:    my @keyarray=();
1.800     albertel 7099:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7100:       next if ($key =~ /^error: 2 /);
1.800     albertel 7101:       push(@keyarray,&unescape($key));
1.407     www      7102:    }
                   7103:    return @keyarray;
1.318     matthew  7104: }
                   7105: 
1.319     matthew  7106: # --------------------------------------------------------------- currentdump
                   7107: sub currentdump {
1.328     matthew  7108:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7109:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7110:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7111:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7112:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7113:    my $rep;
                   7114: 
                   7115:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7116:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7117:                    $courseid)));
                   7118:    } else {
                   7119:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7120:    }
                   7121: 
1.318     matthew  7122:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7123:    #
1.318     matthew  7124:    my %returnhash=();
1.319     matthew  7125:    #
                   7126:    if ($rep eq "unknown_cmd") { 
                   7127:        # an old lond will not know currentdump
                   7128:        # Do a dump and make it look like a currentdump
1.822     albertel 7129:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7130:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7131:        my %hash = @tmp;
                   7132:        @tmp=();
1.424     matthew  7133:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7134:    } else {
                   7135:        my @pairs=split(/\&/,$rep);
1.800     albertel 7136:        foreach my $pair (@pairs) {
                   7137:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7138:            my ($symb,$param) = split(/:/,$key);
                   7139:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7140:                                                         &thaw_unescape($value);
1.319     matthew  7141:        }
1.191     harris41 7142:    }
1.12      www      7143:    return %returnhash;
1.424     matthew  7144: }
                   7145: 
                   7146: sub convert_dump_to_currentdump{
                   7147:     my %hash = %{shift()};
                   7148:     my %returnhash;
                   7149:     # Code ripped from lond, essentially.  The only difference
                   7150:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7151:     # we might run in to problems with parameter names =~ /^v\./
                   7152:     while (my ($key,$value) = each(%hash)) {
                   7153:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7154: 	$symb  = &unescape($symb);
                   7155: 	$param = &unescape($param);
1.424     matthew  7156:         next if ($v eq 'version' || $symb eq 'keys');
                   7157:         next if (exists($returnhash{$symb}) &&
                   7158:                  exists($returnhash{$symb}->{$param}) &&
                   7159:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7160:         $returnhash{$symb}->{$param}=$value;
                   7161:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7162:     }
                   7163:     #
                   7164:     # Remove all of the keys in the hashes which keep track of
                   7165:     # the version of the parameter.
                   7166:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7167:         # use a foreach because we are going to delete from the hash.
                   7168:         foreach my $key (keys(%$param_hash)) {
                   7169:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7170:         }
                   7171:     }
                   7172:     return \%returnhash;
1.12      www      7173: }
                   7174: 
1.627     albertel 7175: # ------------------------------------------------------ critical inc interface
                   7176: 
                   7177: sub cinc {
                   7178:     return &inc(@_,'critical');
                   7179: }
                   7180: 
1.449     matthew  7181: # --------------------------------------------------------------- inc interface
                   7182: 
                   7183: sub inc {
1.627     albertel 7184:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7185:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7186:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7187:     my $uhome=&homeserver($uname,$udomain);
                   7188:     my $items='';
                   7189:     if (! ref($store)) {
                   7190:         # got a single value, so use that instead
                   7191:         $items = &escape($store).'=&';
                   7192:     } elsif (ref($store) eq 'SCALAR') {
                   7193:         $items = &escape($$store).'=&';        
                   7194:     } elsif (ref($store) eq 'ARRAY') {
                   7195:         $items = join('=&',map {&escape($_);} @{$store});
                   7196:     } elsif (ref($store) eq 'HASH') {
                   7197:         while (my($key,$value) = each(%{$store})) {
                   7198:             $items.= &escape($key).'='.&escape($value).'&';
                   7199:         }
                   7200:     }
                   7201:     $items=~s/\&$//;
1.627     albertel 7202:     if ($critical) {
                   7203: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7204:     } else {
                   7205: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7206:     }
1.449     matthew  7207: }
                   7208: 
1.12      www      7209: # --------------------------------------------------------------- put interface
                   7210: 
                   7211: sub put {
1.1172.2.146.  .1(raebu 7212:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7214:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7215:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7216:    my $items='';
1.800     albertel 7217:    foreach my $item (keys(%$storehash)) {
                   7218:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7219:    }
1.12      www      7220:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7221:22):    if ($encrypt) {
                   7222:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7223:22):    } else {
                   7224:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7225:22):    }
1.47      www      7226: }
                   7227: 
1.631     albertel 7228: # ------------------------------------------------------------ newput interface
                   7229: 
                   7230: sub newput {
                   7231:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7233:    if (!$uname) { $uname=$env{'user.name'}; }
                   7234:    my $uhome=&homeserver($uname,$udomain);
                   7235:    my $items='';
                   7236:    foreach my $key (keys(%$storehash)) {
                   7237:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7238:    }
                   7239:    $items=~s/\&$//;
                   7240:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7241: }
                   7242: 
                   7243: # ---------------------------------------------------------  putstore interface
                   7244: 
1.524     raeburn  7245: sub putstore {
1.1172.2.59  raeburn  7246:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7247:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7248:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7249:    my $uhome=&homeserver($uname,$udomain);
                   7250:    my $items='';
1.715     albertel 7251:    foreach my $key (keys(%$storehash)) {
                   7252:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7253:    }
1.715     albertel 7254:    $items=~s/\&$//;
1.716     albertel 7255:    my $esc_symb=&escape($symb);
                   7256:    my $esc_v=&escape($version);
1.715     albertel 7257:    my $reply =
1.716     albertel 7258:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7259: 	      $uhome);
1.1172.2.59  raeburn  7260:    if (($tolog) && ($reply eq 'ok')) {
                   7261:        my $namevalue='';
                   7262:        foreach my $key (keys(%{$storehash})) {
                   7263:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7264:        }
1.1172.2.134  raeburn  7265:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7266:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7267:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7268:                      '&version='.$esc_v.
                   7269:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7270:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7271:    }
1.715     albertel 7272:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7273:        # gfall back to way things use to be done
1.715     albertel 7274:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7275: 			    $uname);
1.524     raeburn  7276:    }
1.715     albertel 7277:    return $reply;
                   7278: }
                   7279: 
                   7280: sub old_putstore {
1.716     albertel 7281:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7282:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7283:     if (!$uname) { $uname=$env{'user.name'}; }
                   7284:     my $uhome=&homeserver($uname,$udomain);
                   7285:     my %newstorehash;
1.800     albertel 7286:     foreach my $item (keys(%$storehash)) {
                   7287: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7288: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7289:     }
                   7290:     my $items='';
                   7291:     my %allitems = ();
1.800     albertel 7292:     foreach my $item (keys(%newstorehash)) {
                   7293: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7294: 	    my $key = $1.':keys:'.$2;
                   7295: 	    $allitems{$key} .= $3.':';
                   7296: 	}
1.800     albertel 7297: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7298:     }
1.800     albertel 7299:     foreach my $item (keys(%allitems)) {
                   7300: 	$allitems{$item} =~ s/\:$//;
                   7301: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7302:     }
                   7303:     $items=~s/\&$//;
                   7304:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7305: }
                   7306: 
1.47      www      7307: # ------------------------------------------------------ critical put interface
                   7308: 
                   7309: sub cput {
1.134     albertel 7310:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7312:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7313:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7314:    my $items='';
1.800     albertel 7315:    foreach my $item (keys(%$storehash)) {
                   7316:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7317:    }
1.47      www      7318:    $items=~s/\&$//;
1.134     albertel 7319:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7320: }
                   7321: 
                   7322: # -------------------------------------------------------------- eget interface
                   7323: 
                   7324: sub eget {
1.133     albertel 7325:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7326:    my $items='';
1.800     albertel 7327:    foreach my $item (@$storearr) {
                   7328:        $items.=&escape($item).'&';
1.191     harris41 7329:    }
1.12      www      7330:    $items=~s/\&$//;
1.620     albertel 7331:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7332:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7333:    my $uhome=&homeserver($uname,$udomain);
                   7334:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7335:    my @pairs=split(/\&/,$rep);
                   7336:    my %returnhash=();
1.42      www      7337:    my $i=0;
1.800     albertel 7338:    foreach my $item (@$storearr) {
                   7339:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7340:       $i++;
1.191     harris41 7341:    }
1.12      www      7342:    return %returnhash;
                   7343: }
                   7344: 
1.667     albertel 7345: # ------------------------------------------------------------ tmpput interface
                   7346: sub tmpput {
1.802     raeburn  7347:     my ($storehash,$server,$context)=@_;
1.667     albertel 7348:     my $items='';
1.800     albertel 7349:     foreach my $item (keys(%$storehash)) {
                   7350: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7351:     }
                   7352:     $items=~s/\&$//;
1.802     raeburn  7353:     if (defined($context)) {
                   7354:         $items .= ':'.&escape($context);
                   7355:     }
1.667     albertel 7356:     return &reply("tmpput:$items",$server);
                   7357: }
                   7358: 
                   7359: # ------------------------------------------------------------ tmpget interface
                   7360: sub tmpget {
1.688     albertel 7361:     my ($token,$server)=@_;
                   7362:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7363:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7364:     my %returnhash;
1.1172.2.85  raeburn  7365:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7366:         return %returnhash;
                   7367:     }
1.667     albertel 7368:     foreach my $item (split(/\&/,$rep)) {
                   7369: 	my ($key,$value)=split(/=/,$item);
                   7370: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7371:     }
                   7372:     return %returnhash;
                   7373: }
                   7374: 
1.1113    raeburn  7375: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7376: sub tmpdel {
                   7377:     my ($token,$server)=@_;
                   7378:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7379:     return &reply("tmpdel:$token",$server);
                   7380: }
                   7381: 
1.1172.2.13  raeburn  7382: # ------------------------------------------------------------ get_timebased_id
                   7383: 
                   7384: sub get_timebased_id {
                   7385:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7386:         $maxtries) = @_;
                   7387:     my ($newid,$error,$dellock);
                   7388:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7389:         return ('','ok','invalid call to get suffix');
                   7390:     }
                   7391: 
                   7392: # set defaults for any optional args for which values were not supplied
                   7393:     if ($who eq '') {
                   7394:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7395:     }
                   7396:     if (!$locktries) {
                   7397:         $locktries = 3;
                   7398:     }
                   7399:     if (!$maxtries) {
                   7400:         $maxtries = 10;
                   7401:     }
                   7402: 
                   7403:     if (($cdom eq '') || ($cnum eq '')) {
                   7404:         if ($env{'request.course.id'}) {
                   7405:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7406:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7407:         }
                   7408:         if (($cdom eq '') || ($cnum eq '')) {
                   7409:             return ('','ok','call to get suffix not in course context');
                   7410:         }
                   7411:     }
                   7412: 
                   7413: # construct locking item
                   7414:     my $lockhash = {
                   7415:                       $prefix."\0".'locked_'.$keyid => $who,
                   7416:                    };
                   7417:     my $tries = 0;
                   7418: 
                   7419: # attempt to get lock on nohist_$namespace file
                   7420:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7421:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7422:         $tries ++;
                   7423:         sleep 1;
                   7424:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7425:     }
                   7426: 
                   7427: # attempt to get unique identifier, based on current timestamp
                   7428:     if ($gotlock eq 'ok') {
                   7429:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7430:         my $id = time;
                   7431:         $newid = $id;
1.1172.2.56  raeburn  7432:         if ($idtype eq 'addcode') {
                   7433:             $newid .= &sixnum_code();
                   7434:         }
1.1172.2.13  raeburn  7435:         my $idtries = 0;
                   7436:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7437:             if ($idtype eq 'concat') {
                   7438:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7439:             } elsif ($idtype eq 'addcode') {
                   7440:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7441:             } else {
                   7442:                 $newid ++;
                   7443:             }
                   7444:             $idtries ++;
                   7445:         }
                   7446:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7447:             my %new_item =  (
                   7448:                               $prefix."\0".$newid => $who,
                   7449:                             );
                   7450:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7451:                                                  $cdom,$cnum);
                   7452:             if ($putresult ne 'ok') {
                   7453:                 undef($newid);
                   7454:                 $error = 'error saving new item: '.$putresult;
                   7455:             }
                   7456:         } else {
1.1172.2.56  raeburn  7457:              undef($newid);
1.1172.2.13  raeburn  7458:              $error = ('error: no unique suffix available for the new item ');
                   7459:         }
                   7460: #  remove lock
                   7461:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7462:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7463:     } else {
                   7464:         $error = "error: could not obtain lockfile\n";
                   7465:         $dellock = 'ok';
1.1172.2.58  raeburn  7466:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7467:             $dellock = 'nolock';
                   7468:         }
1.1172.2.13  raeburn  7469:     }
                   7470:     return ($newid,$dellock,$error);
                   7471: }
                   7472: 
1.1172.2.56  raeburn  7473: sub sixnum_code {
                   7474:     my $code;
                   7475:     for (0..6) {
                   7476:         $code .= int( rand(9) );
                   7477:     }
                   7478:     return $code;
                   7479: }
                   7480: 
1.765     albertel 7481: # -------------------------------------------------- portfolio access checking
                   7482: 
                   7483: sub portfolio_access {
1.1172.2.77  raeburn  7484:     my ($requrl,$clientip) = @_;
1.765     albertel 7485:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7486:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7487:     if ($result) {
                   7488:         my %setters;
                   7489:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7490:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7491:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7492:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7493:                 return 'B';
                   7494:             }
                   7495:         } else {
1.1172.2.142  raeburn  7496:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7497:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7498:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7499:                 return 'B';
                   7500:             }
                   7501:         }
                   7502:     }
1.765     albertel 7503:     if ($result eq 'ok') {
1.766     albertel 7504:        return 'F';
1.765     albertel 7505:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7506:        return 'A';
1.765     albertel 7507:     }
1.766     albertel 7508:     return '';
1.765     albertel 7509: }
                   7510: 
                   7511: sub get_portfolio_access {
1.1172.2.77  raeburn  7512:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7513: 
                   7514:     if (!ref($access_hash)) {
                   7515: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7516: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7517: 						   $file_name);
                   7518: 	$access_hash = $access_controls{$file_name};
                   7519:     }
                   7520: 
1.1172.2.77  raeburn  7521:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7522:     my $now = time;
                   7523:     if (ref($access_hash) eq 'HASH') {
                   7524:         foreach my $key (keys(%{$access_hash})) {
                   7525:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7526:             if ($start > $now) {
                   7527:                 next;
                   7528:             }
                   7529:             if ($end && $end<$now) {
                   7530:                 next;
                   7531:             }
                   7532:             if ($scope eq 'public') {
                   7533:                 $public = $key;
                   7534:                 last;
                   7535:             } elsif ($scope eq 'guest') {
                   7536:                 $guest = $key;
                   7537:             } elsif ($scope eq 'domains') {
                   7538:                 push(@domains,$key);
                   7539:             } elsif ($scope eq 'users') {
                   7540:                 push(@users,$key);
                   7541:             } elsif ($scope eq 'course') {
                   7542:                 push(@courses,$key);
                   7543:             } elsif ($scope eq 'group') {
                   7544:                 push(@groups,$key);
1.1172.2.77  raeburn  7545:             } elsif ($scope eq 'ip') {
                   7546:                 push(@ips,$key);
1.765     albertel 7547:             }
                   7548:         }
                   7549:         if ($public) {
                   7550:             return 'ok';
1.1172.2.77  raeburn  7551:         } elsif (@ips > 0) {
                   7552:             my $allowed;
                   7553:             foreach my $ipkey (@ips) {
                   7554:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7555:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7556:                         $allowed = 1;
                   7557:                         last;
                   7558:                     }
                   7559:                 }
                   7560:             }
                   7561:             if ($allowed) {
                   7562:                 return 'ok';
                   7563:             }
1.765     albertel 7564:         }
                   7565:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7566:             if ($guest) {
                   7567:                 return $guest;
                   7568:             }
                   7569:         } else {
                   7570:             if (@domains > 0) {
                   7571:                 foreach my $domkey (@domains) {
                   7572:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7573:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7574:                             return 'ok';
                   7575:                         }
                   7576:                     }
                   7577:                 }
                   7578:             }
                   7579:             if (@users > 0) {
                   7580:                 foreach my $userkey (@users) {
1.865     raeburn  7581:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7582:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7583:                             if (ref($item) eq 'HASH') {
                   7584:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7585:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7586:                                     return 'ok';
                   7587:                                 }
                   7588:                             }
                   7589:                         }
                   7590:                     } 
1.765     albertel 7591:                 }
                   7592:             }
                   7593:             my %roleshash;
                   7594:             my @courses_and_groups = @courses;
                   7595:             push(@courses_and_groups,@groups); 
                   7596:             if (@courses_and_groups > 0) {
                   7597:                 my (%allgroups,%allroles); 
                   7598:                 my ($start,$end,$role,$sec,$group);
                   7599:                 foreach my $envkey (%env) {
1.1060    raeburn  7600:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7601:                         my $cid = $2.'_'.$3; 
                   7602:                         if ($1 eq 'gr') {
                   7603:                             $group = $4;
                   7604:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7605:                         } else {
                   7606:                             if ($4 eq '') {
                   7607:                                 $sec = 'none';
                   7608:                             } else {
                   7609:                                 $sec = $4;
                   7610:                             }
                   7611:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7612:                         }
1.811     albertel 7613:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7614:                         my $cid = $2.'_'.$3;
                   7615:                         if ($4 eq '') {
                   7616:                             $sec = 'none';
                   7617:                         } else {
                   7618:                             $sec = $4;
                   7619:                         }
                   7620:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7621:                     }
                   7622:                 }
                   7623:                 if (keys(%allroles) == 0) {
                   7624:                     return;
                   7625:                 }
                   7626:                 foreach my $key (@courses_and_groups) {
                   7627:                     my %content = %{$$access_hash{$key}};
                   7628:                     my $cnum = $content{'number'};
                   7629:                     my $cdom = $content{'domain'};
                   7630:                     my $cid = $cdom.'_'.$cnum;
                   7631:                     if (!exists($allroles{$cid})) {
                   7632:                         next;
                   7633:                     }    
                   7634:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7635:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7636:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7637:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7638:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7639:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7640:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7641:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7642:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7643:                                         if (grep/^all$/,@sections) {
                   7644:                                             return 'ok';
                   7645:                                         } else {
                   7646:                                             if (grep/^$sec$/,@sections) {
                   7647:                                                 return 'ok';
                   7648:                                             }
                   7649:                                         }
                   7650:                                     }
                   7651:                                 }
                   7652:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7653:                                     if (grep/^none$/,@groups) {
                   7654:                                         return 'ok';
                   7655:                                     }
                   7656:                                 } else {
                   7657:                                     if (grep/^all$/,@groups) {
                   7658:                                         return 'ok';
                   7659:                                     } 
                   7660:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7661:                                         if (grep/^$group$/,@groups) {
                   7662:                                             return 'ok';
                   7663:                                         }
                   7664:                                     }
                   7665:                                 } 
                   7666:                             }
                   7667:                         }
                   7668:                     }
                   7669:                 }
                   7670:             }
                   7671:             if ($guest) {
                   7672:                 return $guest;
                   7673:             }
                   7674:         }
                   7675:     }
                   7676:     return;
                   7677: }
                   7678: 
                   7679: sub course_group_datechecker {
                   7680:     my ($dates,$now,$status) = @_;
                   7681:     my ($start,$end) = split(/\./,$dates);
                   7682:     if (!$start && !$end) {
                   7683:         return 'ok';
                   7684:     }
                   7685:     if (grep/^active$/,@{$status}) {
                   7686:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7687:             return 'ok';
                   7688:         }
                   7689:     }
                   7690:     if (grep/^previous$/,@{$status}) {
                   7691:         if ($end > $now ) {
                   7692:             return 'ok';
                   7693:         }
                   7694:     }
                   7695:     if (grep/^future$/,@{$status}) {
                   7696:         if ($start > $now) {
                   7697:             return 'ok';
                   7698:         }
                   7699:     }
                   7700:     return; 
                   7701: }
                   7702: 
                   7703: sub parse_portfolio_url {
                   7704:     my ($url) = @_;
                   7705: 
                   7706:     my ($type,$udom,$unum,$group,$file_name);
                   7707:     
1.823     albertel 7708:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7709: 	$type = 1;
                   7710:         $udom = $1;
                   7711:         $unum = $2;
                   7712:         $file_name = $3;
1.823     albertel 7713:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7714: 	$type = 2;
                   7715:         $udom = $1;
                   7716:         $unum = $2;
                   7717:         $group = $3;
                   7718:         $file_name = $3.'/'.$4;
                   7719:     }
                   7720:     if (wantarray) {
                   7721: 	return ($type,$udom,$unum,$file_name,$group);
                   7722:     }
                   7723:     return $type;
                   7724: }
                   7725: 
                   7726: sub is_portfolio_url {
                   7727:     my ($url) = @_;
                   7728:     return scalar(&parse_portfolio_url($url));
                   7729: }
                   7730: 
1.798     raeburn  7731: sub is_portfolio_file {
                   7732:     my ($file) = @_;
1.820     raeburn  7733:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7734:         return 1;
                   7735:     }
                   7736:     return;
                   7737: }
                   7738: 
1.976     raeburn  7739: sub usertools_access {
1.1084    raeburn  7740:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7741:     my ($access,%tools);
                   7742:     if ($context eq '') {
                   7743:         $context = 'tools';
                   7744:     }
                   7745:     if ($context eq 'requestcourses') {
                   7746:         %tools = (
                   7747:                       official   => 1,
                   7748:                       unofficial => 1,
1.1006    raeburn  7749:                       community  => 1,
1.1172.2.37  raeburn  7750:                       textbook   => 1,
1.985     raeburn  7751:                  );
1.1172.2.9  raeburn  7752:     } elsif ($context eq 'requestauthor') {
                   7753:         %tools = (
                   7754:                       requestauthor => 1,
                   7755:                  );
1.985     raeburn  7756:     } else {
                   7757:         %tools = (
                   7758:                       aboutme   => 1,
                   7759:                       blog      => 1,
1.1172.2.6  raeburn  7760:                       webdav    => 1,
1.985     raeburn  7761:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7762:22):                       timezone  => 1,
1.985     raeburn  7763:                  );
                   7764:     }
1.976     raeburn  7765:     return if (!defined($tools{$tool}));
                   7766: 
1.1172.2.35  raeburn  7767:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7768:         $udom = $env{'user.domain'};
                   7769:         $uname = $env{'user.name'};
                   7770:     }
                   7771: 
1.978     raeburn  7772:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7773:         if ($action ne 'reload') {
1.985     raeburn  7774:             if ($context eq 'requestcourses') {
                   7775:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7776:             } elsif ($context eq 'requestauthor') {
                   7777:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7778:             } else {
                   7779:                 return $env{'environment.availabletools.'.$tool};
                   7780:             }
                   7781:         }
1.976     raeburn  7782:     }
                   7783: 
1.1172.2.9  raeburn  7784:     my ($toolstatus,$inststatus,$envkey);
                   7785:     if ($context eq 'requestauthor') {
                   7786:         $envkey = $context;
                   7787:     } else {
                   7788:         $envkey = $context.'.'.$tool;
                   7789:     }
1.976     raeburn  7790: 
1.985     raeburn  7791:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7792:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7793:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7794:         $inststatus = $env{'environment.inststatus'};
                   7795:     } else {
1.1084    raeburn  7796:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7797:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7798:             $inststatus = $userenvref->{'inststatus'};
                   7799:         } else {
1.1172.2.9  raeburn  7800:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7801:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7802:             $inststatus = $userenv{'inststatus'};
                   7803:         }
1.976     raeburn  7804:     }
                   7805: 
                   7806:     if ($toolstatus ne '') {
                   7807:         if ($toolstatus) {
                   7808:             $access = 1;
                   7809:         } else {
                   7810:             $access = 0;
                   7811:         }
                   7812:         return $access;
                   7813:     }
                   7814: 
1.1084    raeburn  7815:     my ($is_adv,%domdef);
                   7816:     if (ref($is_advref) eq 'HASH') {
                   7817:         $is_adv = $is_advref->{'is_adv'};
                   7818:     } else {
                   7819:         $is_adv = &is_advanced_user($udom,$uname);
                   7820:     }
                   7821:     if (ref($domdefref) eq 'HASH') {
                   7822:         %domdef = %{$domdefref};
                   7823:     } else {
                   7824:         %domdef = &get_domain_defaults($udom);
                   7825:     }
1.976     raeburn  7826:     if (ref($domdef{$tool}) eq 'HASH') {
                   7827:         if ($is_adv) {
                   7828:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7829:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7830:                     $access = 1;
                   7831:                 } else {
                   7832:                     $access = 0;
                   7833:                 }
                   7834:                 return $access;
                   7835:             }
                   7836:         }
                   7837:         if ($inststatus ne '') {
                   7838:             my ($hasaccess,$hasnoaccess);
                   7839:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7840:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7841:                     if ($domdef{$tool}{$affiliation}) {
                   7842:                         $hasaccess = 1;
                   7843:                     } else {
                   7844:                         $hasnoaccess = 1;
                   7845:                     }
                   7846:                 }
                   7847:             }
                   7848:             if ($hasaccess || $hasnoaccess) {
                   7849:                 if ($hasaccess) {
                   7850:                     $access = 1;
                   7851:                 } elsif ($hasnoaccess) {
                   7852:                     $access = 0; 
                   7853:                 }
                   7854:                 return $access;
                   7855:             }
                   7856:         } else {
                   7857:             if ($domdef{$tool}{'default'} ne '') {
                   7858:                 if ($domdef{$tool}{'default'}) {
                   7859:                     $access = 1;
                   7860:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7861:                     $access = 0;
                   7862:                 }
                   7863:                 return $access;
                   7864:             }
                   7865:         }
                   7866:     } else {
1.1172.2.6  raeburn  7867:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7868:             $access = 1;
                   7869:         } else {
                   7870:             $access = 0;
                   7871:         }
1.976     raeburn  7872:         return $access;
                   7873:     }
                   7874: }
                   7875: 
1.1050    raeburn  7876: sub is_course_owner {
                   7877:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7878:     if (($udom eq '') || ($uname eq '')) {
                   7879:         $udom = $env{'user.domain'};
                   7880:         $uname = $env{'user.name'};
                   7881:     }
                   7882:     unless (($udom eq '') || ($uname eq '')) {
                   7883:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7884:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7885:                 return 1;
                   7886:             } else {
                   7887:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7888:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7889:                     return 1;
                   7890:                 }
                   7891:             }
                   7892:         }
                   7893:     }
                   7894:     return;
                   7895: }
                   7896: 
1.976     raeburn  7897: sub is_advanced_user {
                   7898:     my ($udom,$uname) = @_;
1.1085    raeburn  7899:     if ($udom ne '' && $uname ne '') {
                   7900:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7901:             if (wantarray) {
                   7902:                 return ($env{'user.adv'},$env{'user.author'});
                   7903:             } else {
                   7904:                 return $env{'user.adv'};
                   7905:             }
1.1085    raeburn  7906:         }
                   7907:     }
1.976     raeburn  7908:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7909:     my %allroles;
1.1128    raeburn  7910:     my ($is_adv,$is_author);
1.976     raeburn  7911:     foreach my $role (keys(%roleshash)) {
                   7912:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7913:         my $area = '/'.$tdomain.'/'.$trest;
                   7914:         if ($sec ne '') {
                   7915:             $area .= '/'.$sec;
                   7916:         }
                   7917:         if (($area ne '') && ($trole ne '')) {
                   7918:             my $spec=$trole.'.'.$area;
                   7919:             if ($trole =~ /^cr\//) {
                   7920:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7921:             } elsif ($trole ne 'gr') {
                   7922:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7923:             }
1.1128    raeburn  7924:             if ($trole eq 'au') {
                   7925:                 $is_author = 1;
                   7926:             }
1.976     raeburn  7927:         }
                   7928:     }
                   7929:     foreach my $role (keys(%allroles)) {
                   7930:         last if ($is_adv);
                   7931:         foreach my $item (split(/:/,$allroles{$role})) {
                   7932:             if ($item ne '') {
                   7933:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7934:                 if ($privilege eq 'adv') {
                   7935:                     $is_adv = 1;
                   7936:                     last;
                   7937:                 }
                   7938:             }
                   7939:         }
                   7940:     }
1.1128    raeburn  7941:     if (wantarray) {
                   7942:         return ($is_adv,$is_author);
                   7943:     }
1.976     raeburn  7944:     return $is_adv;
                   7945: }
1.798     raeburn  7946: 
1.1035    raeburn  7947: sub check_can_request {
1.1036    raeburn  7948:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7949:     my $canreq = 0;
                   7950:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7951:     my @options = ('approval','validate','autolimit');
                   7952:     my $optregex = join('|',@options);
                   7953:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7954:         foreach my $type (@{$types}) {
                   7955:             if (&usertools_access($env{'user.name'},
                   7956:                                   $env{'user.domain'},
                   7957:                                   $type,undef,'requestcourses')) {
                   7958:                 $canreq ++;
1.1036    raeburn  7959:                 if (ref($request_domains) eq 'HASH') {
                   7960:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7961:                 }
1.1035    raeburn  7962:                 if ($dom eq $env{'user.domain'}) {
                   7963:                     $can_request->{$type} = 1;
                   7964:                 }
                   7965:             }
                   7966:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7967:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7968:                 if (@curr > 0) {
1.1036    raeburn  7969:                     foreach my $item (@curr) {
                   7970:                         if (ref($request_domains) eq 'HASH') {
                   7971:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7972:                             if ($otherdom ne '') {
                   7973:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7974:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7975:                                         push(@{$request_domains->{$type}},$otherdom);
                   7976:                                     }
                   7977:                                 } else {
                   7978:                                     push(@{$request_domains->{$type}},$otherdom);
                   7979:                                 }
                   7980:                             }
                   7981:                         }
                   7982:                     }
                   7983:                     unless($dom eq $env{'user.domain'}) {
                   7984:                         $canreq ++;
1.1035    raeburn  7985:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7986:                             $can_request->{$type} = 1;
                   7987:                         }
                   7988:                     }
                   7989:                 }
                   7990:             }
                   7991:         }
                   7992:     }
                   7993:     return $canreq;
                   7994: }
                   7995: 
1.341     www      7996: # ---------------------------------------------- Custom access rule evaluation
                   7997: 
                   7998: sub customaccess {
                   7999:     my ($priv,$uri)=@_;
1.807     albertel 8000:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8001:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8002:     $udom = &LONCAPA::clean_domain($udom);
                   8003:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8004:     my $access=0;
1.800     albertel 8005:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8006: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8007: 	if ($type eq 'user') {
                   8008: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8009: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8010: 		if ($tdom) {
                   8011: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8012: 		}
1.896     albertel 8013: 		if ($tuname) {
                   8014: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8015: 		}
                   8016: 		$access=($effect eq 'allow');
                   8017: 		last;
                   8018: 	    }
                   8019: 	} else {
                   8020: 	    if ($role) {
                   8021: 		if ($role ne $urole) { next; }
                   8022: 	    }
                   8023: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8024: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8025: 		if ($tdom) {
                   8026: 		    if ($tdom ne $udom) { next; }
                   8027: 		}
                   8028: 		if ($tcrs) {
                   8029: 		    if ($tcrs ne $ucrs) { next; }
                   8030: 		}
                   8031: 		if ($tsec) {
                   8032: 		    if ($tsec ne $usec) { next; }
                   8033: 		}
                   8034: 		$access=($effect eq 'allow');
                   8035: 		last;
                   8036: 	    }
                   8037: 	    if ($realm eq '' && $role eq '') {
                   8038: 		$access=($effect eq 'allow');
                   8039: 	    }
1.402     bowersj2 8040: 	}
1.341     www      8041:     }
                   8042:     return $access;
                   8043: }
                   8044: 
1.103     harris41 8045: # ------------------------------------------------- Check for a user privilege
1.12      www      8046: 
                   8047: sub allowed {
1.1172.2.146.  .1(raebu 8048:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8049:     my $ver_orguri=$uri;
1.439     www      8050:     $uri=&deversion($uri);
1.152     www      8051:     my $orguri=$uri;
1.52      www      8052:     $uri=&declutter($uri);
1.809     raeburn  8053: 
1.810     raeburn  8054:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8055:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8056:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8057:             return $1;
                   8058:         } else {
                   8059:             return;
                   8060:         }
                   8061:     }
                   8062: 
1.620     albertel 8063:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8064: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8065:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8066: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8067: 	&& ($priv eq 'bre')) {
1.14      www      8068: 	return 'F';
1.159     www      8069:     }
                   8070: 
1.545     banghart 8071: # Free bre access to user's own portfolio contents
1.714     raeburn  8072:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8073:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8074: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8075:         my %setters;
1.1172.2.142  raeburn  8076:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8077:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8078:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8079:             return 'B';
                   8080:         } else {
                   8081:             return 'F';
                   8082:         }
1.545     banghart 8083:     }
                   8084: 
1.762     raeburn  8085: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8086:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8087:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8088:         if (exists($env{'request.course.id'})) {
                   8089:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8090:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8091:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8092:                 my $courseprivid=$env{'request.course.id'};
                   8093:                 $courseprivid=~s/\_/\//;
                   8094:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8095:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8096:                     return $1; 
1.762     raeburn  8097:                 } else {
                   8098:                     if ($env{'request.course.sec'}) {
                   8099:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8100:                     }
                   8101:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8102:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8103:                         return $2;
                   8104:                     }
1.714     raeburn  8105:                 }
                   8106:             }
                   8107:         }
                   8108:     }
                   8109: 
1.159     www      8110: # Free bre to public access
                   8111: 
                   8112:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8113:22):         my $copyright;
                   8114:22):         unless ($uri =~ /ext\.tool/) {
                   8115:22):             $copyright=&metadata($uri,'copyright');
                   8116:22):         }
1.620     albertel 8117: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8118:            return 'F'; 
                   8119:         }
1.238     www      8120:         if ($copyright eq 'priv') {
                   8121:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8122: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8123: 		return '';
                   8124:             }
                   8125:         }
                   8126:         if ($copyright eq 'domain') {
                   8127:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8128: 	    unless (($env{'user.domain'} eq $1) ||
                   8129:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8130: 		return '';
                   8131:             }
1.262     matthew  8132:         }
1.620     albertel 8133:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8134:             # Library role, so allow browsing of resources in this domain.
                   8135:             return 'F';
1.238     www      8136:         }
1.341     www      8137:         if ($copyright eq 'custom') {
                   8138: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8139:         }
1.14      www      8140:     }
1.264     matthew  8141:     # Domain coordinator is trying to create a course
1.620     albertel 8142:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8143:         # uri is the requested domain in this case.
                   8144:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8145:         # a role of dc for the domain in question.
1.620     albertel 8146:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8147:     }
1.29      www      8148: 
1.52      www      8149:     my $thisallowed='';
                   8150:     my $statecond=0;
                   8151:     my $courseprivid='';
                   8152: 
1.1039    raeburn  8153:     my $ownaccess;
1.1043    raeburn  8154:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8155:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8156:         if ($uri eq '') {
                   8157:             $ownaccess = 1;
                   8158:         } else {
                   8159:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8160:                 my $udom = $env{'user.domain'};
                   8161:                 my $uname = $env{'user.name'};
                   8162:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8163:                     $ownaccess = 1;
1.1040    raeburn  8164:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8165:                     unless ($uri =~ m{\.\./}) {
                   8166:                         $ownaccess = 1;
                   8167:                     }
                   8168:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8169:                     my $now = time;
                   8170:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8171:                         my $adom = $1;
                   8172:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8173:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8174:                                 my ($start,$end) = split(/\./,$env{$key});
                   8175:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8176:                                     $ownaccess = 1;
                   8177:                                     last;
                   8178:                                 }
                   8179:                             }
                   8180:                         }
                   8181:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8182:                         my $adom = $1;
                   8183:                         my $aname = $2;
1.1042    raeburn  8184:                         foreach my $role ('ca','aa') { 
                   8185:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8186:                                 my ($start,$end) =
1.1172.2.142  raeburn  8187:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8188:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8189:                                     $ownaccess = 1;
                   8190:                                     last;
                   8191:                                 }
1.1039    raeburn  8192:                             }
                   8193:                         }
                   8194:                     }
                   8195:                 }
                   8196:             }
                   8197:         }
                   8198:     }
                   8199: 
1.52      www      8200: # Course
                   8201: 
1.620     albertel 8202:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8203:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8204:             $thisallowed.=$1;
                   8205:         }
1.52      www      8206:     }
1.29      www      8207: 
1.52      www      8208: # Domain
                   8209: 
1.620     albertel 8210:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8211:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8212:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8213:             $thisallowed.=$1;
                   8214:         }
1.12      www      8215:     }
1.52      www      8216: 
1.1141    raeburn  8217: # User who is not author or co-author might still be able to edit
                   8218: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8219:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8220:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8221:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8222:             $thisallowed.=$1;
                   8223:         }
                   8224:     }
                   8225: 
1.52      www      8226: # Course: uri itself is a course
1.66      www      8227:     my $courseuri=$uri;
                   8228:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8229:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8230: 
1.620     albertel 8231:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8232:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8233:         if ($priv eq 'mip') {
                   8234:             my $rem = $1;
                   8235:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8236:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8237:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8238:                 if ($cdom ne '') {
                   8239:                     my %passwdconf = &get_passwdconf($cdom);
                   8240:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8241:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8242:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8243:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8244:                                 unless (@inststatuses) {
                   8245:                                     @inststatuses = ('default');
                   8246:                                 }
                   8247:                                 foreach my $status (@inststatuses) {
                   8248:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8249:                                         $thisallowed.=$rem;
                   8250:                                     }
                   8251:                                 }
                   8252:                             }
                   8253:                         }
                   8254:                     }
                   8255:                 }
                   8256:             }
                   8257:         } else {
                   8258:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8259:                 $thisallowed.=$1;
                   8260:             }
1.1039    raeburn  8261:         }
1.12      www      8262:     }
1.29      www      8263: 
1.665     albertel 8264: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8265: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8266:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8267: 	$thisallowed='';
1.671     raeburn  8268:         my ($match)=&is_on_map($uri);
                   8269:         if ($match) {
                   8270:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8271:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8272:                 my $value = $1;
1.1172.2.146.  .1(raebu 8273:22):                 my $deeplinkblock;
                   8274:22):                 unless ($nodeeplinkcheck) {
                   8275:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8276:22):                 }
                   8277:22):                 if ($deeplinkblock) {
                   8278:22):                     $thisallowed='D';
                   8279:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8280:                     $thisallowed.=$value;
1.1162    raeburn  8281:                 } else {
1.1172.2.126  raeburn  8282:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8283:                     if (@blockers > 0) {
                   8284:                         $thisallowed = 'B';
                   8285:                     } else {
                   8286:                         $thisallowed.=$value;
                   8287:                     }
1.1162    raeburn  8288:                 }
1.671     raeburn  8289:             }
                   8290:         } else {
1.705     albertel 8291:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8292:             if ($refuri) {
                   8293:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8294:                     $thisallowed='F';
1.671     raeburn  8295:                 } else {
                   8296:                     $refuri=&declutter($refuri);
                   8297:                     my ($match) = &is_on_map($refuri);
                   8298:                     if ($match) {
1.1172.2.146.  .1(raebu 8299:22):                         my $deeplinkblock;
                   8300:22):                         unless ($nodeeplinkcheck) {
                   8301:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8302:22):                         }
                   8303:22):                         if ($deeplinkblock) {
                   8304:22):                             $thisallowed='D';
                   8305:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8306:                             $thisallowed='F';
1.1172.2.65  raeburn  8307:                         } else {
1.1172.2.127  raeburn  8308:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8309:                             if (@blockers > 0) {
                   8310:                                 $thisallowed = 'B';
                   8311:                             } else {
                   8312:                                 $thisallowed='F';
                   8313:                             }
1.1162    raeburn  8314:                         }
1.671     raeburn  8315:                     }
1.669     raeburn  8316:                 }
1.671     raeburn  8317:             }
                   8318:         }
1.314     www      8319:     }
1.492     albertel 8320: 
1.766     albertel 8321:     if ($priv eq 'bre'
                   8322: 	&& $thisallowed ne 'F' 
                   8323: 	&& $thisallowed ne '2'
                   8324: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8325: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8326:     }
                   8327:     
1.52      www      8328: # Full access at system, domain or course-wide level? Exit.
1.29      www      8329:     if ($thisallowed=~/F/) {
                   8330: 	return 'F';
                   8331:     }
                   8332: 
1.52      www      8333: # If this is generating or modifying users, exit with special codes
1.29      www      8334: 
1.643     www      8335:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8336: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8337: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8338: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8339: 	    unless ($auname) { return $thisallowed; }
                   8340: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8341: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8342: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8343: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8344: 	}
1.52      www      8345: 	return $thisallowed;
                   8346:     }
                   8347: #
1.103     harris41 8348: # Gathered so far: system, domain and course wide privileges
1.52      www      8349: #
                   8350: # Course: See if uri or referer is an individual resource that is part of 
                   8351: # the course
                   8352: 
1.620     albertel 8353:     if ($env{'request.course.id'}) {
1.232     www      8354: 
1.1172.2.115  raeburn  8355: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8356: 
                   8357:         if ($priv eq 'mip') {
                   8358:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8359:                 return $thisallowed;
                   8360:             } else {
                   8361:                 return '';
                   8362:             }
                   8363:         }
                   8364: 
1.620     albertel 8365:        $courseprivid=$env{'request.course.id'};
                   8366:        if ($env{'request.course.sec'}) {
                   8367:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8368:        }
                   8369:        $courseprivid=~s/\_/\//;
                   8370:        my $checkreferer=1;
1.232     www      8371:        my ($match,$cond)=&is_on_map($uri);
                   8372:        if ($match) {
                   8373:            $statecond=$cond;
1.620     albertel 8374:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8375:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8376:                my $value = $1;
                   8377:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8378:22):                    my $deeplinkblock;
                   8379:22):                    unless ($nodeeplinkcheck) {
                   8380:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8381:22):                    }
                   8382:22):                    if ($deeplinkblock) {
                   8383:22):                        $thisallowed = 'D';
                   8384:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8385:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8386:                    } else {
1.1172.2.126  raeburn  8387:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8388:                        if (@blockers > 0) {
                   8389:                            $thisallowed = 'B';
                   8390:                        } else {
                   8391:                            $thisallowed.=$value;
                   8392:                        }
1.1162    raeburn  8393:                    }
                   8394:                } else {
                   8395:                    $thisallowed.=$value;
                   8396:                }
1.52      www      8397:                $checkreferer=0;
                   8398:            }
1.29      www      8399:        }
1.1172.2.126  raeburn  8400: 
1.148     www      8401:        if ($checkreferer) {
1.620     albertel 8402: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8403:             unless ($refuri) {
1.800     albertel 8404:                 foreach my $key (keys(%env)) {
                   8405: 		    if ($key=~/^httpref\..*\*/) {
                   8406: 			my $pattern=$key;
1.156     www      8407:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8408:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8409:                         $pattern=~s/\//\\\//g;
1.152     www      8410:                         if ($orguri=~/$pattern/) {
1.800     albertel 8411: 			    $refuri=$env{$key};
1.148     www      8412:                         }
                   8413:                     }
1.191     harris41 8414:                 }
1.148     www      8415:             }
1.232     www      8416: 
1.148     www      8417:          if ($refuri) { 
1.152     www      8418: 	  $refuri=&declutter($refuri);
1.232     www      8419:           my ($match,$cond)=&is_on_map($refuri);
                   8420:             if ($match) {
                   8421:               my $refstatecond=$cond;
1.620     albertel 8422:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8423:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8424:                   my $value = $1;
                   8425:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8426:22):                       my $deeplinkblock;
                   8427:22):                       unless ($nodeeplinkcheck) {
                   8428:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8429:22):                       }
                   8430:22):                       if ($deeplinkblock) {
                   8431:22):                           $thisallowed = 'D';
                   8432:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8433:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8434:                       } else {
1.1172.2.127  raeburn  8435:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8436:                           if (@blockers > 0) {
                   8437:                               $thisallowed = 'B';
                   8438:                           } else {
                   8439:                               $thisallowed.=$value;
                   8440:                           }
1.1162    raeburn  8441:                       }
                   8442:                   } else {
                   8443:                       $thisallowed.=$value;
                   8444:                   }
1.53      www      8445:                   $uri=$refuri;
                   8446:                   $statecond=$refstatecond;
1.52      www      8447:               }
                   8448:           }
1.148     www      8449:         }
1.29      www      8450:        }
1.52      www      8451:    }
1.29      www      8452: 
1.52      www      8453: #
1.103     harris41 8454: # Gathered now: all privileges that could apply, and condition number
1.52      www      8455: # 
                   8456: #
                   8457: # Full or no access?
                   8458: #
1.29      www      8459: 
1.52      www      8460:     if ($thisallowed=~/F/) {
                   8461: 	return 'F';
                   8462:     }
1.29      www      8463: 
1.52      www      8464:     unless ($thisallowed) {
                   8465:         return '';
                   8466:     }
1.29      www      8467: 
1.52      www      8468: # Restrictions exist, deal with them
                   8469: #
                   8470: #   C:according to course preferences
                   8471: #   R:according to resource settings
                   8472: #   L:unless locked
                   8473: #   X:according to user session state
                   8474: #
                   8475: 
                   8476: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8477: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8478: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8479: # courses, and 2 minutes for current course, in which user has st or ta role
                   8480: # which is neither expired nor a future role (unless current course).
1.52      www      8481: 
1.1172.2.142  raeburn  8482:     my ($needlockcheck,$now,$crsonly);
1.52      www      8483:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8484:         $now = time;
                   8485:         if ($priv eq 'bre') {
                   8486:             if ($uri ne '') {
                   8487:                 if ($orguri =~ m{^/+res/}) {
                   8488:                     if ($uri =~ m{^lib/templates/}) {
                   8489:                         if ($env{'request.course.id'}) {
                   8490:                             $crsonly = 1;
                   8491:                             $needlockcheck = 1;
                   8492:                         }
                   8493:                     } else {
                   8494:                         $needlockcheck = 1;
                   8495:                     }
                   8496:                 } elsif ($env{'request.course.id'}) {
                   8497:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8498:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8499:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8500:                         $crsonly = 1;
                   8501:                     }
                   8502:                     $needlockcheck = 1;
                   8503:                 }
                   8504:             }
                   8505:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8506:             $needlockcheck = 1;
                   8507:         }
                   8508:     }
                   8509:     if ($needlockcheck) {
                   8510:         foreach my $envkey (keys(%env)) {
1.54      www      8511:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8512:                my $courseid=$2;
                   8513:                my $roleid=$1.'.'.$2;
1.92      www      8514:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8515:                unless ($env{'request.role'} eq $roleid) {
                   8516:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8517:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8518:                }
1.54      www      8519:                my $expiretime=600;
1.620     albertel 8520:                if ($env{'request.role'} eq $roleid) {
1.54      www      8521: 		  $expiretime=120;
                   8522:                }
                   8523: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8524:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8525:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8526: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8527:                }
1.620     albertel 8528:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8529:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8530: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8531:                        &log($env{'user.domain'},$env{'user.name'},
                   8532:                             $env{'user.home'},
1.57      www      8533:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8534:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8535:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8536: 		       return '';
                   8537:                    }
                   8538:                }
1.620     albertel 8539:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8540:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8541: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8542:                        &log($env{'user.domain'},$env{'user.name'},
                   8543:                             $env{'user.home'},
1.57      www      8544:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8545:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8546:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8547: 		       return '';
                   8548:                    }
                   8549:                }
                   8550: 	   }
1.29      www      8551:        }
1.52      www      8552:     }
1.1172.2.126  raeburn  8553: 
1.52      www      8554: #
                   8555: # Rest of the restrictions depend on selected course
                   8556: #
                   8557: 
1.620     albertel 8558:     unless ($env{'request.course.id'}) {
1.766     albertel 8559: 	if ($thisallowed eq 'A') {
                   8560: 	    return 'A';
1.814     raeburn  8561:         } elsif ($thisallowed eq 'B') {
                   8562:             return 'B';
1.766     albertel 8563: 	} else {
                   8564: 	    return '1';
                   8565: 	}
1.52      www      8566:     }
1.29      www      8567: 
1.52      www      8568: #
                   8569: # Now user is definitely in a course
                   8570: #
1.53      www      8571: 
                   8572: 
                   8573: # Course preferences
                   8574: 
                   8575:    if ($thisallowed=~/C/) {
1.620     albertel 8576:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8577:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8578:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8579: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8580: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8581: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8582: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8583: 			$env{'request.course.id'});
                   8584: 	   }
1.237     www      8585:            return '';
                   8586:        }
                   8587: 
1.620     albertel 8588:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8589: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8590: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8591: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8592: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8593: 			$env{'request.course.id'});
                   8594: 	   }
1.54      www      8595:            return '';
                   8596:        }
1.53      www      8597:    }
                   8598: 
                   8599: # Resource preferences
                   8600: 
                   8601:    if ($thisallowed=~/R/) {
1.620     albertel 8602:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8603:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8604: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8605: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8606: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8607: 	   }
                   8608: 	   return '';
1.54      www      8609:        }
1.53      www      8610:    }
1.30      www      8611: 
1.1172.2.146.  .1(raebu 8612:22): # Restricted for deeplinked session?
                   8613:22): 
                   8614:22):     if ($env{'request.deeplink.login'}) {
                   8615:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8616:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8617:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8618:22):                 return '';
                   8619:22):             }
                   8620:22):         }
                   8621:22):     }
                   8622:22): 
1.246     www      8623: # Restricted by state or randomout?
1.30      www      8624: 
1.52      www      8625:    if ($thisallowed=~/X/) {
1.620     albertel 8626:       if ($env{'acc.randomout'}) {
1.579     albertel 8627: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8628:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8629:             return ''; 
                   8630:          }
1.247     www      8631:       }
                   8632:       if (&condval($statecond)) {
1.52      www      8633: 	 return '2';
                   8634:       } else {
                   8635:          return '';
                   8636:       }
                   8637:    }
1.30      www      8638: 
1.766     albertel 8639:     if ($thisallowed eq 'A') {
                   8640: 	return 'A';
1.814     raeburn  8641:     } elsif ($thisallowed eq 'B') {
                   8642:         return 'B';
1.1172.2.146.  .1(raebu 8643:22):     } elsif ($thisallowed eq 'D') {
                   8644:22):         return 'D';
1.766     albertel 8645:     }
1.52      www      8646:    return 'F';
1.232     www      8647: }
1.1162    raeburn  8648: 
1.1172.2.13  raeburn  8649: # ------------------------------------------- Check construction space access
                   8650: 
                   8651: sub constructaccess {
                   8652:     my ($url,$setpriv)=@_;
                   8653: 
                   8654: # We do not allow editing of previous versions of files
                   8655:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8656: 
                   8657: # Get username and domain from URL
                   8658:     my ($ownername,$ownerdomain,$ownerhome);
                   8659: 
                   8660:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8661:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8662: 
                   8663: # The URL does not really point to any authorspace, forget it
                   8664:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8665: 
                   8666: # Now we need to see if the user has access to the authorspace of
                   8667: # $ownername at $ownerdomain
                   8668: 
                   8669:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8670: # Real author for this?
                   8671:        $ownerhome = $env{'user.home'};
                   8672:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8673:           return ($ownername,$ownerdomain,$ownerhome);
                   8674:        }
                   8675:     } else {
                   8676: # Co-author for this?
                   8677:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8678:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8679:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8680:             return ($ownername,$ownerdomain,$ownerhome);
                   8681:         }
                   8682:     }
                   8683: 
                   8684: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8685: # we might as well leave
                   8686:    unless ($setpriv) { return ''; }
                   8687: 
                   8688: # Backdoor access?
                   8689:     my $allowed=&allowed('eco',$ownerdomain);
                   8690: # Nope
                   8691:     unless ($allowed) { return ''; }
                   8692: # Looks like we may have access, but could be locked by the owner of the construction space
                   8693:     if ($allowed eq 'U') {
                   8694:         my %blocked=&get('environment',['domcoord.author'],
                   8695:                          $ownerdomain,$ownername);
                   8696: # Is blocked by owner
                   8697:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8698:     }
                   8699:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8700: # Grant temporary access
                   8701:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8702:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8703:         if (!$update) { $update = $then; }
                   8704:         my $refresh=$env{'user.refresh.time'};
                   8705:         if (!$refresh) { $refresh = $update; }
                   8706:         my $now = time;
                   8707:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8708:                            $now,'ca','constructaccess');
                   8709:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8710:         return($ownername,$ownerdomain,$ownerhome);
                   8711:     }
                   8712: # No business here
                   8713:     return '';
                   8714: }
                   8715: 
1.1172.2.66  raeburn  8716: # ----------------------------------------------------------- Content Blocking
                   8717: 
                   8718: {
                   8719: # Caches for faster Course Contents display where content blocking
                   8720: # is in operation (i.e., interval param set) for timed quiz.
                   8721: #
                   8722: # User for whom data are being temporarily cached.
                   8723: my $cacheduser='';
1.1172.2.126  raeburn  8724: # Course for which data are being temporarily cached.
                   8725: my $cachedcid='';
1.1172.2.66  raeburn  8726: # Cached blockers for this user (a hash of blocking items).
                   8727: my %cachedblockers=();
                   8728: # When the data were last cached.
                   8729: my $cachedlast='';
                   8730: 
                   8731: sub load_all_blockers {
1.1172.2.128  raeburn  8732:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8733:     if (($uname ne '') && ($udom ne '')) {
                   8734:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8735:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8736:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8737:             return;
                   8738:         }
                   8739:     }
                   8740:     $cachedlast=time;
                   8741:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8742:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8743:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8744:     return;
1.1172.2.66  raeburn  8745: }
                   8746: 
1.1162    raeburn  8747: sub get_comm_blocks {
                   8748:     my ($cdom,$cnum) = @_;
                   8749:     if ($cdom eq '' || $cnum eq '') {
                   8750:         return unless ($env{'request.course.id'});
                   8751:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8752:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8753:     }
                   8754:     my %commblocks;
                   8755:     my $hashid=$cdom.'_'.$cnum;
                   8756:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8757:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8758:         %commblocks = %{$blocksref};
                   8759:     } else {
                   8760:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8761:         my $cachetime = 600;
                   8762:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8763:     }
                   8764:     return %commblocks;
                   8765: }
                   8766: 
1.1172.2.66  raeburn  8767: sub get_commblock_resources {
                   8768:     my ($blocks) = @_;
                   8769:     my %blockers = ();
                   8770:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8771:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8772:     if ($env{'request.course.sec'}) {
                   8773:         $courseurl .= '/'.$env{'request.course.sec'};
                   8774:     }
                   8775:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8776:     my %commblocks;
                   8777:     if (ref($blocks) eq 'HASH') {
                   8778:         %commblocks = %{$blocks};
                   8779:     } else {
                   8780:         %commblocks = &get_comm_blocks();
                   8781:     }
1.1172.2.66  raeburn  8782:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8783:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8784:     return %blockers unless (ref($navmap));
                   8785:     my $now = time;
1.1162    raeburn  8786:     foreach my $block (keys(%commblocks)) {
                   8787:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8788:             my ($start,$end) = ($1,$2);
                   8789:             if ($start <= $now && $end >= $now) {
                   8790:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8791:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8792:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8793:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8794:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8795:                             }
                   8796:                         }
                   8797:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8798:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8799:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8800:                             }
                   8801:                         }
                   8802:                     }
                   8803:                 }
                   8804:             }
                   8805:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8806:             my $item = $1;
                   8807:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8808:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8809:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8810:                     my $type = 'map';
                   8811:                     if ($item eq 'course') {
                   8812:                         $type = 'course';
                   8813:                         @interval=&EXT("resource.0.interval");
                   8814:                     } else {
                   8815:                         if ($item =~ /___\d+___/) {
                   8816:                             $type = 'resource';
                   8817:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8818:                         } else {
1.1172.2.142  raeburn  8819:                             $mapname = &deversion($item);
                   8820:                             if (ref($navmap)) {
                   8821:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8822:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8823:                             }
                   8824:                         }
1.1172.2.66  raeburn  8825:                     }
1.1172.2.146.  .1(raebu 8826:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8827:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8828:                         my $first_access;
                   8829:                         if ($type eq 'resource') {
                   8830:                             $first_access=&get_first_access($interval[1],$item);
                   8831:                         } elsif ($type eq 'map') {
                   8832:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8833:                         } else {
                   8834:                             $first_access=&get_first_access($interval[1]);
                   8835:                         }
                   8836:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8837:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8838:                             if ($timesup > $now) {
                   8839:                                 my $activeblock;
1.1172.2.142  raeburn  8840:                                 if ($type eq 'resource') {
                   8841:                                     if (ref($navmap)) {
                   8842:                                         my $res = $navmap->getBySymb($item);
                   8843:                                         if ($res->answerable()) {
                   8844:                                             $activeblock = 1;
                   8845:                                         }
                   8846:                                     }
                   8847:                                 } elsif ($type eq 'map') {
                   8848:                                     my $mapsymb = &symbread($mapname,1);
                   8849:                                     if (($mapsymb) && (ref($navmap))) {
                   8850:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8851:                                         if (ref($mapres)) {
                   8852:                                             my $first = $mapres->map_start();
                   8853:                                             my $finish = $mapres->map_finish();
                   8854:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8855:                                             if (ref($it)) {
                   8856:                                                 my $res;
                   8857:                                                 while ($res = $it->next(undef,1)) {
                   8858:                                                     next unless (ref($res));
                   8859:                                                     my $symb = $res->symb();
                   8860:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8861:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8862:                                                     if ($interval[1] eq 'map') {
                   8863:                                                         if ($res->answerable()) {
                   8864:                                                             $activeblock = 1;
                   8865:                                                             last;
                   8866:                                                         }
                   8867:                                                     }
                   8868:                                                 }
                   8869:                                             }
                   8870:                                         }
1.1172.2.66  raeburn  8871:                                     }
                   8872:                                 }
                   8873:                                 if ($activeblock) {
                   8874:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8875:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8876:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8877:                                          }
                   8878:                                     }
                   8879:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8880:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8881:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8882:                                         }
1.1162    raeburn  8883:                                     }
                   8884:                                 }
                   8885:                             }
                   8886:                         }
                   8887:                     }
                   8888:                 }
                   8889:             }
                   8890:         }
                   8891:     }
1.1172.2.66  raeburn  8892:     return %blockers;
1.1162    raeburn  8893: }
                   8894: 
1.1172.2.66  raeburn  8895: sub has_comm_blocking {
1.1172.2.128  raeburn  8896:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8897:     my @blockers;
                   8898:     return unless ($env{'request.course.id'});
                   8899:     return unless ($priv eq 'bre');
                   8900:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8901:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8902:     if ($env{'request.course.sec'}) {
                   8903:         $courseurl .= '/'.$env{'request.course.sec'};
                   8904:     }
                   8905:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8906:     my %blockinfo;
                   8907:     if (ref($blocks) eq 'HASH') {
                   8908:         %blockinfo = &get_commblock_resources($blocks);
                   8909:     } else {
                   8910:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8911:         %blockinfo = %cachedblockers;
                   8912:     }
                   8913:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8914:     my (%possibles,@symbs);
                   8915:     if (!$symb) {
1.1172.2.128  raeburn  8916:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8917:     }
1.1172.2.66  raeburn  8918:     if ($symb) {
                   8919:         @symbs = ($symb);
                   8920:     } elsif (keys(%possibles)) {
                   8921:         @symbs = keys(%possibles);
                   8922:     }
                   8923:     my $noblock;
                   8924:     foreach my $symb (@symbs) {
                   8925:         last if ($noblock);
                   8926:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8927:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8928:             if ($block =~ /^firstaccess____(.+)$/) {
                   8929:                 my $item = $1;
1.1172.2.126  raeburn  8930:                 unless ($blocked) {
                   8931:                     if (($item eq $map) || ($item eq $symb)) {
                   8932:                         $noblock = 1;
                   8933:                         last;
                   8934:                     }
1.1172.2.66  raeburn  8935:                 }
1.1162    raeburn  8936:             }
1.1172.2.128  raeburn  8937:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8938:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8939:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8940:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8941:                             push(@blockers,$block);
                   8942:                         }
                   8943:                     }
                   8944:                 }
1.1172.2.128  raeburn  8945:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8946:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8947:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8948:                             push(@blockers,$block);
                   8949:                         }
1.1172.2.66  raeburn  8950:                     }
                   8951:                 }
1.1162    raeburn  8952:             }
                   8953:         }
                   8954:     }
1.1172.2.126  raeburn  8955:     unless ($noblock) {
                   8956:         return @blockers;
                   8957:     }
                   8958:     return;
1.1172.2.66  raeburn  8959: }
1.1162    raeburn  8960: }
                   8961: 
1.1172.2.146.  .1(raebu 8962:22): sub deeplink_check {
                   8963:22):     my ($priv,$symb,$uri) = @_;
                   8964:22):     return unless ($env{'request.course.id'});
                   8965:22):     return unless ($priv eq 'bre');
                   8966:22):     return if ($env{'request.state'} eq 'construct');
                   8967:22):     return if ($env{'request.role.adv'});
                   8968:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8969:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8970:22):     my (%possibles,@symbs);
                   8971:22):     if (!$symb) {
                   8972:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8973:22):     }
                   8974:22):     if ($symb) {
                   8975:22):         @symbs = ($symb);
                   8976:22):     } elsif (keys(%possibles)) {
                   8977:22):         @symbs = keys(%possibles);
                   8978:22):     }
                   8979:22): 
                   8980:22):     my ($deeplink_symb,$allow);
                   8981:22):     if ($env{'request.deeplink.login'}) {
                   8982:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8983:22):     }
                   8984:22):     foreach my $symb (@symbs) {
                   8985:22):         last if ($allow);
                   8986:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8987:22):         if ($deeplink eq '') {
                   8988:22):             $allow = 1;
                   8989:22):         } else {
                   8990:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8991:22):             if ($state ne 'only') {
                   8992:22):                 $allow = 1;
                   8993:22):             } else {
                   8994:22):                 my $check_deeplink_entry;
                   8995:22):                 if ($protect ne 'none') {
                   8996:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8997:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8998:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8999:22):                             $check_deeplink_entry = 1
                   9000:22):                         }
                   9001:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9002:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9003:22):                             $check_deeplink_entry = 1;
                   9004:22):                         }
                   9005:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9006:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9007:22):                             $check_deeplink_entry = 1;
                   9008:22):                         }
                   9009:22):                     }
                   9010:22):                 }
                   9011:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9012:22):                     if ($scope eq 'res') {
                   9013:22):                         if ($symb eq $deeplink_symb) {
                   9014:22):                             $allow = 1;
                   9015:22):                         }
                   9016:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9017:22):                         my ($map_from_symb,$map_from_login);
                   9018:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9019:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9020:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9021:22):                         } else {
                   9022:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9023:22):                         }
                   9024:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9025:22):                             if ($map_from_symb eq $map_from_login) {
                   9026:22):                                 $allow = 1;
                   9027:22):                             } elsif ($scope eq 'rec') {
                   9028:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9029:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9030:22):                                     $allow = 1;
                   9031:22):                                 }
                   9032:22):                             }
                   9033:22):                         }
                   9034:22):                     }
                   9035:22):                 }
                   9036:22):             }
                   9037:22):         }
                   9038:22):     }
                   9039:22):     return if ($allow);
                   9040:22):     return 1;
                   9041:22): }
                   9042:22): 
1.1172.2.66  raeburn  9043: # -------------------------------- Deversion and split uri into path an filename
                   9044: 
1.1133    foxr     9045: #
1.1172.2.66  raeburn  9046: #   Removes the version from a URI and
1.1133    foxr     9047: #   splits it in to its filename and path to the filename.
                   9048: #   Seems like File::Basename could have done this more clearly.
                   9049: #   Parameters:
                   9050: #      $uri   - input URI
                   9051: #   Returns:
                   9052: #     Two element list consisting of 
                   9053: #     $pathname  - the URI up to and excluding the trailing /
                   9054: #     $filename  - The part of the URI following the last /
                   9055: #  NOTE:
                   9056: #    Another realization of this is simply:
                   9057: #    use File::Basename;
                   9058: #    ...
                   9059: #    $uri = shift;
                   9060: #    $filename = basename($uri);
                   9061: #    $path     = dirname($uri);
                   9062: #    return ($filename, $path);
                   9063: #
                   9064: #     The implementation below is probably faster however.
                   9065: #
1.710     albertel 9066: sub split_uri_for_cond {
                   9067:     my $uri=&deversion(&declutter(shift));
                   9068:     my @uriparts=split(/\//,$uri);
                   9069:     my $filename=pop(@uriparts);
                   9070:     my $pathname=join('/',@uriparts);
                   9071:     return ($pathname,$filename);
                   9072: }
1.232     www      9073: # --------------------------------------------------- Is a resource on the map?
                   9074: 
                   9075: sub is_on_map {
1.710     albertel 9076:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9077:     #Trying to find the conditional for the file
1.620     albertel 9078:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9079: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9080:     if ($match) {
1.289     bowersj2 9081: 	return (1,$1);
                   9082:     } else {
1.434     www      9083: 	return (0,0);
1.289     bowersj2 9084:     }
1.12      www      9085: }
                   9086: 
1.427     www      9087: # --------------------------------------------------------- Get symb from alias
                   9088: 
                   9089: sub get_symb_from_alias {
                   9090:     my $symb=shift;
                   9091:     my ($map,$resid,$url)=&decode_symb($symb);
                   9092: # Already is a symb
                   9093:     if ($url) { return $symb; }
                   9094: # Must be an alias
                   9095:     my $aliassymb='';
                   9096:     my %bighash;
1.620     albertel 9097:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9098:                             &GDBM_READER(),0640)) {
                   9099:         my $rid=$bighash{'mapalias_'.$symb};
                   9100: 	if ($rid) {
                   9101: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9102: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9103: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9104: 	}
                   9105:         untie %bighash;
                   9106:     }
                   9107:     return $aliassymb;
                   9108: }
                   9109: 
1.12      www      9110: # ----------------------------------------------------------------- Define Role
                   9111: 
                   9112: sub definerole {
                   9113:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9114:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9115:     foreach my $role (split(':',$sysrole)) {
                   9116: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9117:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9118:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9119: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9120:                return "refused:s:$crole&$cqual"; 
                   9121:             }
                   9122:         }
1.191     harris41 9123:     }
1.800     albertel 9124:     foreach my $role (split(':',$domrole)) {
                   9125: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9126:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9127:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9128: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9129:                return "refused:d:$crole&$cqual"; 
                   9130:             }
                   9131:         }
1.191     harris41 9132:     }
1.800     albertel 9133:     foreach my $role (split(':',$courole)) {
                   9134: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9135:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9136:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9137: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9138:                return "refused:c:$crole&$cqual"; 
                   9139:             }
                   9140:         }
1.191     harris41 9141:     }
1.1172.2.84  raeburn  9142:     my $uhome;
                   9143:     if (($uname ne '') && ($udom ne '')) {
                   9144:         $uhome = &homeserver($uname,$udom);
                   9145:         return $uhome if ($uhome eq 'no_host');
                   9146:     } else {
                   9147:         $uname = $env{'user.name'};
                   9148:         $udom = $env{'user.domain'};
                   9149:         $uhome = $env{'user.home'};
                   9150:     }
1.620     albertel 9151:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9152:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9153:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9154:     return reply($command,$uhome);
1.12      www      9155:   } else {
                   9156:     return 'refused';
                   9157:   }
1.105     harris41 9158: }
                   9159: 
                   9160: # ---------------- Make a metadata query against the network of library servers
                   9161: 
                   9162: sub metadata_query {
1.1172.2.33  raeburn  9163:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9164:     my %rhash;
1.845     albertel 9165:     my %libserv = &all_library();
1.244     matthew  9166:     my @server_list = (defined($server_array) ? @$server_array
                   9167:                                               : keys(%libserv) );
                   9168:     for my $server (@server_list) {
1.1172.2.33  raeburn  9169:         my $domains = '';
                   9170:         if (ref($domains_hash) eq 'HASH') {
                   9171:             $domains = $domains_hash->{$server};    
                   9172:         }
1.118     harris41 9173: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9174: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9175: 	    $rhash{$server}=$reply;
                   9176: 	}
                   9177: 	else {
                   9178: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9179: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9180: 			     $server);
                   9181: 	    $rhash{$server}=$reply;
                   9182: 	}
1.112     harris41 9183:     }
1.118     harris41 9184:     return \%rhash;
1.240     www      9185: }
                   9186: 
                   9187: # ----------------------------------------- Send log queries and wait for reply
                   9188: 
                   9189: sub log_query {
                   9190:     my ($uname,$udom,$query,%filters)=@_;
                   9191:     my $uhome=&homeserver($uname,$udom);
                   9192:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9193:     my $uhost=&hostname($uhome);
1.800     albertel 9194:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9195:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9196:                        $uhome);
1.479     albertel 9197:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9198:     return get_query_reply($queryid);
                   9199: }
                   9200: 
1.818     raeburn  9201: # -------------------------- Update MySQL table for portfolio file
                   9202: 
                   9203: sub update_portfolio_table {
1.821     raeburn  9204:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9205:     if ($group ne '') {
                   9206:         $file_name =~s /^\Q$group\E//;
                   9207:     }
1.818     raeburn  9208:     my $homeserver = &homeserver($uname,$udom);
                   9209:     my $queryid=
1.821     raeburn  9210:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9211:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9212:     my $reply = &get_query_reply($queryid);
                   9213:     return $reply;
                   9214: }
                   9215: 
1.899     raeburn  9216: # -------------------------- Update MySQL allusers table
                   9217: 
                   9218: sub update_allusers_table {
                   9219:     my ($uname,$udom,$names) = @_;
                   9220:     my $homeserver = &homeserver($uname,$udom);
                   9221:     my $queryid=
                   9222:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9223:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9224:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9225:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9226:                'generation='.&escape($names->{'generation'}).'%%'.
                   9227:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9228:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9229:     return;
1.899     raeburn  9230: }
                   9231: 
1.508     raeburn  9232: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9233: 
                   9234: sub fetch_enrollment_query {
1.511     raeburn  9235:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9236:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9237:     my $maxtries = 1;
1.508     raeburn  9238:     if ($context eq 'automated') {
                   9239:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9240:         $sleep = 2;
                   9241:         $loopmax = 100;
1.547     raeburn  9242:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9243:     } else {
                   9244:         $homeserver = &homeserver($cnum,$dom);
                   9245:     }
1.838     albertel 9246:     my $host=&hostname($homeserver);
1.506     raeburn  9247:     my $cmd = '';
1.1000    raeburn  9248:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9249:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9250:     }
                   9251:     $cmd =~ s/%%$//;
                   9252:     $cmd = &escape($cmd);
                   9253:     my $query = 'fetchenrollment';
1.620     albertel 9254:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9255:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9256:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9257:         return 'error: '.$queryid;
                   9258:     }
1.1172.2.93  raeburn  9259:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9260:     my $tries = 1;
                   9261:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9262:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9263:         $tries ++;
                   9264:     }
1.526     raeburn  9265:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9266:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9267:     } else {
1.901     albertel 9268:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9269:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9270:             foreach my $line (@responses) {
                   9271:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9272:                 $$replyref{$key} = $value;
                   9273:             }
                   9274:         } else {
1.1117    foxr     9275:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9276:             foreach my $line (@responses) {
                   9277:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9278:                 $$replyref{$key} = $value;
                   9279:                 if ($value > 0) {
1.800     albertel 9280:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9281:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9282:                         my $destname = $pathname.'/'.$filename;
                   9283:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9284:                         if ($xml_classlist =~ /^error/) {
                   9285:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9286:                         } else {
1.1172.2.96  raeburn  9287:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9288:                                 print FILE &unescape($xml_classlist);
                   9289:                                 close(FILE);
1.526     raeburn  9290:                             } else {
                   9291:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9292:                             }
                   9293:                         }
                   9294:                     }
                   9295:                 }
                   9296:             }
                   9297:         }
                   9298:         return 'ok';
                   9299:     }
                   9300:     return 'error';
                   9301: }
                   9302: 
1.242     www      9303: sub get_query_reply {
1.1172.2.79  raeburn  9304:     my ($queryid,$sleep,$loopmax) = @_;
                   9305:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9306:         $sleep = 0.2;
                   9307:     }
                   9308:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9309:         $loopmax = 100;
                   9310:     }
1.1117    foxr     9311:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9312:     my $reply='';
1.1172.2.79  raeburn  9313:     for (1..$loopmax) {
                   9314: 	sleep($sleep);
1.240     www      9315:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9316: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9317: 		$reply = join('',<$fh>);
                   9318: 		close($fh);
1.240     www      9319: 	   } else { return 'error: reply_file_error'; }
1.242     www      9320:            return &unescape($reply);
                   9321: 	}
1.240     www      9322:     }
1.242     www      9323:     return 'timeout:'.$queryid;
1.240     www      9324: }
                   9325: 
                   9326: sub courselog_query {
1.241     www      9327: #
                   9328: # possible filters:
                   9329: # url: url or symb
                   9330: # username
                   9331: # domain
                   9332: # action: view, submit, grade
                   9333: # start: timestamp
                   9334: # end: timestamp
                   9335: #
1.240     www      9336:     my (%filters)=@_;
1.620     albertel 9337:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9338:     if ($filters{'url'}) {
                   9339: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9340:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9341:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9342:     }
1.620     albertel 9343:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9344:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9345:     return &log_query($cname,$cdom,'courselog',%filters);
                   9346: }
                   9347: 
                   9348: sub userlog_query {
1.858     raeburn  9349: #
                   9350: # possible filters:
                   9351: # action: log check role
                   9352: # start: timestamp
                   9353: # end: timestamp
                   9354: #
1.240     www      9355:     my ($uname,$udom,%filters)=@_;
                   9356:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9357: }
                   9358: 
1.506     raeburn  9359: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9360: 
                   9361: sub auto_run {
1.508     raeburn  9362:     my ($cnum,$cdom) = @_;
1.876     raeburn  9363:     my $response = 0;
                   9364:     my $settings;
                   9365:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9366:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9367:         $settings = $domconfig{'autoenroll'};
                   9368:         if ($settings->{'run'} eq '1') {
                   9369:             $response = 1;
                   9370:         }
                   9371:     } else {
1.934     raeburn  9372:         my $homeserver;
                   9373:         if (&is_course($cdom,$cnum)) {
                   9374:             $homeserver = &homeserver($cnum,$cdom);
                   9375:         } else {
                   9376:             $homeserver = &domain($cdom,'primary');
                   9377:         }
                   9378:         if ($homeserver ne 'no_host') {
                   9379:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9380:         }
1.876     raeburn  9381:     }
1.506     raeburn  9382:     return $response;
                   9383: }
1.776     albertel 9384: 
1.506     raeburn  9385: sub auto_get_sections {
1.508     raeburn  9386:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9387:     my $homeserver;
                   9388:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9389:         $homeserver = &homeserver($cnum,$cdom);
                   9390:     }
                   9391:     if (!defined($homeserver)) { 
                   9392:         if ($cdom =~ /^$match_domain$/) {
                   9393:             $homeserver = &domain($cdom,'primary');
                   9394:         }
                   9395:     }
                   9396:     my @secs;
                   9397:     if (defined($homeserver)) {
                   9398:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9399:         unless ($response eq 'refused') {
                   9400:             @secs = split(/:/,$response);
                   9401:         }
1.506     raeburn  9402:     }
                   9403:     return @secs;
                   9404: }
1.776     albertel 9405: 
1.506     raeburn  9406: sub auto_new_course {
1.1099    raeburn  9407:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9408:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9409:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9410:     return $response;
                   9411: }
1.776     albertel 9412: 
1.506     raeburn  9413: sub auto_validate_courseID {
1.508     raeburn  9414:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9415:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9416:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9417:     return $response;
                   9418: }
1.776     albertel 9419: 
1.1007    raeburn  9420: sub auto_validate_instcode {
1.1020    raeburn  9421:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9422:     my ($homeserver,$response);
                   9423:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9424:         $homeserver = &homeserver($cnum,$cdom);
                   9425:     }
                   9426:     if (!defined($homeserver)) {
                   9427:         if ($cdom =~ /^$match_domain$/) {
                   9428:             $homeserver = &domain($cdom,'primary');
                   9429:         }
                   9430:     }
1.1065    raeburn  9431:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9432:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9433:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9434:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9435: }
                   9436: 
1.1172.2.141  raeburn  9437: sub auto_validate_inst_crosslist {
                   9438:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9439:     my ($homeserver,$response);
                   9440:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9441:         $homeserver = &homeserver($cnum,$cdom);
                   9442:     }
                   9443:     if (!defined($homeserver)) {
                   9444:         if ($cdom =~ /^$match_domain$/) {
                   9445:             $homeserver = &domain($cdom,'primary');
                   9446:         }
                   9447:     }
                   9448:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9449:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9450:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9451:                          &escape($coowner),$homeserver);
                   9452:     }
                   9453:     return $response;
                   9454: }
                   9455: 
1.506     raeburn  9456: sub auto_create_password {
1.873     raeburn  9457:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9458:     my ($homeserver,$response);
1.506     raeburn  9459:     my $create_passwd = 0;
                   9460:     my $authchk = '';
1.873     raeburn  9461:     if ($udom =~ /^$match_domain$/) {
                   9462:         $homeserver = &domain($udom,'primary');
                   9463:     }
                   9464:     if ($homeserver eq '') {
                   9465:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9466:             $homeserver = &homeserver($cnum,$cdom);
                   9467:         }
                   9468:     }
                   9469:     if ($homeserver eq '') {
                   9470:         $authchk = 'nodomain';
1.506     raeburn  9471:     } else {
1.873     raeburn  9472:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9473:         if ($response eq 'refused') {
                   9474:             $authchk = 'refused';
                   9475:         } else {
1.901     albertel 9476:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9477:         }
1.506     raeburn  9478:     }
                   9479:     return ($authparam,$create_passwd,$authchk);
                   9480: }
                   9481: 
1.706     raeburn  9482: sub auto_photo_permission {
                   9483:     my ($cnum,$cdom,$students) = @_;
                   9484:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9485:     my ($outcome,$perm_reqd,$conditions) = 
                   9486: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9487:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9488: 	return (undef,undef);
                   9489:     }
1.706     raeburn  9490:     return ($outcome,$perm_reqd,$conditions);
                   9491: }
                   9492: 
                   9493: sub auto_checkphotos {
                   9494:     my ($uname,$udom,$pid) = @_;
                   9495:     my $homeserver = &homeserver($uname,$udom);
                   9496:     my ($result,$resulttype);
                   9497:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9498: 				   &escape($uname).':'.&escape($pid),
                   9499: 				   $homeserver));
1.709     albertel 9500:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9501: 	return (undef,undef);
                   9502:     }
1.706     raeburn  9503:     if ($outcome) {
                   9504:         ($result,$resulttype) = split(/:/,$outcome);
                   9505:     } 
                   9506:     return ($result,$resulttype);
                   9507: }
                   9508: 
                   9509: sub auto_photochoice {
                   9510:     my ($cnum,$cdom) = @_;
                   9511:     my $homeserver = &homeserver($cnum,$cdom);
                   9512:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9513: 						       &escape($cdom),
                   9514: 						       $homeserver)));
1.709     albertel 9515:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9516: 	return (undef,undef);
                   9517:     }
1.706     raeburn  9518:     return ($update,$comment);
                   9519: }
                   9520: 
                   9521: sub auto_photoupdate {
                   9522:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9523:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9524:     my $host=&hostname($homeserver);
1.706     raeburn  9525:     my $cmd = '';
                   9526:     my $maxtries = 1;
1.800     albertel 9527:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9528:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9529:     }
                   9530:     $cmd =~ s/%%$//;
                   9531:     $cmd = &escape($cmd);
                   9532:     my $query = 'institutionalphotos';
                   9533:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9534:     unless ($queryid=~/^\Q$host\E\_/) {
                   9535:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9536:         return 'error: '.$queryid;
                   9537:     }
                   9538:     my $reply = &get_query_reply($queryid);
                   9539:     my $tries = 1;
                   9540:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9541:         $reply = &get_query_reply($queryid);
                   9542:         $tries ++;
                   9543:     }
                   9544:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9545:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9546:     } else {
                   9547:         my @responses = split(/:/,$reply);
                   9548:         my $outcome = shift(@responses); 
                   9549:         foreach my $item (@responses) {
                   9550:             my ($key,$value) = split(/=/,$item);
                   9551:             $$photo{$key} = $value;
                   9552:         }
                   9553:         return $outcome;
                   9554:     }
                   9555:     return 'error';
                   9556: }
                   9557: 
1.521     raeburn  9558: sub auto_instcode_format {
1.793     albertel 9559:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9560: 	$cat_order) = @_;
1.521     raeburn  9561:     my $courses = '';
1.772     raeburn  9562:     my @homeservers;
1.521     raeburn  9563:     if ($caller eq 'global') {
1.841     albertel 9564: 	my %servers = &get_servers($codedom,'library');
                   9565: 	foreach my $tryserver (keys(%servers)) {
                   9566: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9567: 		push(@homeservers,$tryserver);
                   9568: 	    }
1.584     raeburn  9569:         }
1.1022    raeburn  9570:     } elsif ($caller eq 'requests') {
                   9571:         if ($codedom =~ /^$match_domain$/) {
                   9572:             my $chome = &domain($codedom,'primary');
                   9573:             unless ($chome eq 'no_host') {
                   9574:                 push(@homeservers,$chome);
                   9575:             }
                   9576:         }
1.521     raeburn  9577:     } else {
1.772     raeburn  9578:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9579:     }
1.793     albertel 9580:     foreach my $code (keys(%{$instcodes})) {
                   9581:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9582:     }
                   9583:     chop($courses);
1.772     raeburn  9584:     my $ok_response = 0;
                   9585:     my $response;
                   9586:     while (@homeservers > 0 && $ok_response == 0) {
                   9587:         my $server = shift(@homeservers); 
                   9588:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9589:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9590:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9591: 		split(/:/,$response);
1.772     raeburn  9592:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9593:             push(@{$codetitles},&str2array($codetitles_str));
                   9594:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9595:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9596:             $ok_response = 1;
                   9597:         }
                   9598:     }
                   9599:     if ($ok_response) {
1.521     raeburn  9600:         return 'ok';
1.772     raeburn  9601:     } else {
                   9602:         return $response;
1.521     raeburn  9603:     }
                   9604: }
                   9605: 
1.792     raeburn  9606: sub auto_instcode_defaults {
                   9607:     my ($domain,$returnhash,$code_order) = @_;
                   9608:     my @homeservers;
1.841     albertel 9609: 
                   9610:     my %servers = &get_servers($domain,'library');
                   9611:     foreach my $tryserver (keys(%servers)) {
                   9612: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9613: 	    push(@homeservers,$tryserver);
                   9614: 	}
1.792     raeburn  9615:     }
1.841     albertel 9616: 
1.792     raeburn  9617:     my $response;
1.841     albertel 9618:     foreach my $server (@homeservers) {
1.792     raeburn  9619:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9620:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9621: 	
                   9622: 	foreach my $pair (split(/\&/,$response)) {
                   9623: 	    my ($name,$value)=split(/\=/,$pair);
                   9624: 	    if ($name eq 'code_order') {
                   9625: 		@{$code_order} = split(/\&/,&unescape($value));
                   9626: 	    } else {
                   9627: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9628: 	    }
                   9629: 	}
                   9630: 	return 'ok';
1.792     raeburn  9631:     }
1.841     albertel 9632: 
                   9633:     return $response;
1.1003    raeburn  9634: }
                   9635: 
                   9636: sub auto_possible_instcodes {
1.1007    raeburn  9637:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9638:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9639:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9640:         return;
                   9641:     }
1.1003    raeburn  9642:     my (@homeservers,$uhome);
                   9643:     if (defined(&domain($domain,'primary'))) {
                   9644:         $uhome=&domain($domain,'primary');
                   9645:         push(@homeservers,&domain($domain,'primary'));
                   9646:     } else {
                   9647:         my %servers = &get_servers($domain,'library');
                   9648:         foreach my $tryserver (keys(%servers)) {
                   9649:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9650:                 push(@homeservers,$tryserver);
                   9651:             }
                   9652:         }
                   9653:     }
                   9654:     my $response;
                   9655:     foreach my $server (@homeservers) {
                   9656:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9657:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9658:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9659:             split(':',$response);
                   9660:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9661:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9662:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9663:             my ($name,$value)=split('=',$item);
                   9664:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9665:         }
                   9666:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9667:             my ($name,$value)=split('=',$item);
                   9668:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9669:         }
                   9670:         return 'ok';
                   9671:     }
                   9672:     return $response;
                   9673: }
1.792     raeburn  9674: 
1.1010    raeburn  9675: sub auto_courserequest_checks {
                   9676:     my ($dom) = @_;
1.1020    raeburn  9677:     my ($homeserver,%validations);
                   9678:     if ($dom =~ /^$match_domain$/) {
                   9679:         $homeserver = &domain($dom,'primary');
                   9680:     }
                   9681:     unless ($homeserver eq 'no_host') {
                   9682:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9683:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9684:             my @items = split(/&/,$response);
                   9685:             foreach my $item (@items) {
                   9686:                 my ($key,$value) = split('=',$item);
                   9687:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9688:             }
                   9689:         }
                   9690:     }
1.1010    raeburn  9691:     return %validations; 
                   9692: }
                   9693: 
1.1020    raeburn  9694: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9695:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9696:     my ($homeserver,$response);
                   9697:     if ($dom =~ /^$match_domain$/) {
                   9698:         $homeserver = &domain($dom,'primary');
                   9699:     }
1.1172.2.43  raeburn  9700:     unless ($homeserver eq 'no_host') {
                   9701:         my $customdata;
                   9702:         if (ref($custominfo) eq 'HASH') {
                   9703:             $customdata = &freeze_escape($custominfo);
                   9704:         }
1.1020    raeburn  9705:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9706:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9707:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9708:                                     $customdata,$homeserver));
1.1020    raeburn  9709:     }
                   9710:     return $response;
                   9711: }
                   9712: 
1.777     albertel 9713: sub auto_validate_class_sec {
1.918     raeburn  9714:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9715:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9716:     my $ownerlist;
                   9717:     if (ref($owners) eq 'ARRAY') {
                   9718:         $ownerlist = join(',',@{$owners});
                   9719:     } else {
                   9720:         $ownerlist = $owners;
                   9721:     }
1.773     raeburn  9722:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9723:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9724:     return $response;
                   9725: }
                   9726: 
1.1172.2.141  raeburn  9727: sub auto_instsec_reformat {
                   9728:     my ($cdom,$action,$instsecref) = @_;
                   9729:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9730:     my @homeservers;
                   9731:     if (defined(&domain($cdom,'primary'))) {
                   9732:         push(@homeservers,&domain($cdom,'primary'));
                   9733:     } else {
                   9734:         my %servers = &get_servers($cdom,'library');
                   9735:         foreach my $tryserver (keys(%servers)) {
                   9736:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9737:                 push(@homeservers,$tryserver);
                   9738:             }
                   9739:         }
                   9740:     }
                   9741:     my $response;
                   9742:     my %reformatted = %{$instsecref};
                   9743:     foreach my $server (@homeservers) {
                   9744:         if (ref($instsecref) eq 'HASH') {
                   9745:             my $info = &freeze_escape($instsecref);
                   9746:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9747:                                 $action.':'.$info,$server);
                   9748:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9749:             my @items = split(/&/,$response);
                   9750:             foreach my $item (@items) {
                   9751:                 my ($key,$value) = split(/=/,$item);
                   9752:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9753:             }
                   9754:         }
                   9755:     }
                   9756:     return %reformatted;
                   9757: }
                   9758: 
1.1172.2.94  raeburn  9759: sub auto_validate_instclasses {
                   9760:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9761:     my ($homeserver,%validations);
                   9762:     $homeserver = &homeserver($cnum,$cdom);
                   9763:     unless ($homeserver eq 'no_host') {
                   9764:         my $ownerlist;
                   9765:         if (ref($owners) eq 'ARRAY') {
                   9766:             $ownerlist = join(',',@{$owners});
                   9767:         } else {
                   9768:             $ownerlist = $owners;
                   9769:         }
                   9770:         if (ref($classesref) eq 'HASH') {
                   9771:             my $classes = &freeze_escape($classesref);
                   9772:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9773:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9774:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9775:                 my @items = split(/&/,$response);
                   9776:                 foreach my $item (@items) {
                   9777:                     my ($key,$value) = split('=',$item);
                   9778:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9779:                 }
                   9780:             }
                   9781:         }
                   9782:     }
                   9783:     return %validations;
                   9784: }
                   9785: 
1.1172.2.38  raeburn  9786: sub auto_crsreq_update {
                   9787:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9788:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9789:     my ($homeserver,%crsreqresponse);
                   9790:     if ($cdom =~ /^$match_domain$/) {
                   9791:         $homeserver = &domain($cdom,'primary');
                   9792:     }
                   9793:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9794:         my $info;
                   9795:         if (ref($inbound) eq 'HASH') {
                   9796:             $info = &freeze_escape($inbound);
                   9797:         }
                   9798:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9799:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9800:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9801:                             &escape($title).':'.&escape($code).':'.
                   9802:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9803:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9804:             my @items = split(/&/,$response);
                   9805:             foreach my $item (@items) {
                   9806:                 my ($key,$value) = split('=',$item);
                   9807:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9808:             }
                   9809:         }
                   9810:     }
                   9811:     return \%crsreqresponse;
                   9812: }
                   9813: 
1.1172.2.78  raeburn  9814: sub auto_export_grades {
                   9815:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9816:     my ($homeserver,%exportresponse);
                   9817:     if ($cdom =~ /^$match_domain$/) {
                   9818:         $homeserver = &domain($cdom,'primary');
                   9819:     }
                   9820:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9821:         my $info;
                   9822:         if (ref($inforef) eq 'HASH') {
                   9823:             $info = &freeze_escape($inforef);
                   9824:         }
                   9825:         if (ref($gradesref) eq 'HASH') {
                   9826:             my $grades = &freeze_escape($gradesref);
                   9827:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9828:                                 $info.':'.$grades,$homeserver);
                   9829:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9830:                 my @items = split(/&/,$response);
                   9831:                 foreach my $item (@items) {
                   9832:                     my ($key,$value) = split('=',$item);
                   9833:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9834:                 }
                   9835:             }
                   9836:         }
                   9837:     }
                   9838:     return \%exportresponse;
                   9839: }
                   9840: 
1.1172.2.68  raeburn  9841: sub check_instcode_cloning {
                   9842:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9843:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9844:         return;
                   9845:     }
                   9846:     my $canclone;
                   9847:     if (@{$code_order} > 0) {
                   9848:         my $instcoderegexp ='^';
                   9849:         my @clonecodes = split(/\&/,$cloner);
                   9850:         foreach my $item (@{$code_order}) {
                   9851:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9852:                 foreach my $pair (@clonecodes) {
                   9853:                     my ($key,$val) = split(/\=/,$pair,2);
                   9854:                     $val = &unescape($val);
                   9855:                     if ($key eq $item) {
                   9856:                         $instcoderegexp .= '('.$val.')';
                   9857:                         last;
                   9858:                     }
                   9859:                 }
                   9860:             } else {
                   9861:                 $instcoderegexp .= $codedefaults->{$item};
                   9862:             }
                   9863:         }
                   9864:         $instcoderegexp .= '$';
                   9865:         my (@from,@to);
                   9866:         eval {
                   9867:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9868:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9869:         };
                   9870:         if ((@from > 0) && (@to > 0)) {
                   9871:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9872:             if (!@diffs) {
                   9873:                 $canclone = 1;
                   9874:             }
                   9875:         }
                   9876:     }
                   9877:     return $canclone;
                   9878: }
                   9879: 
                   9880: sub default_instcode_cloning {
                   9881:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9882:     my (%codedefaults,@code_order,$canclone);
                   9883:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9884:         %codedefaults = %{$codedefaultsref};
                   9885:         @code_order = @{$codeorderref};
                   9886:     } elsif ($clonedom) {
                   9887:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9888:     }
                   9889:     if (($domdefclone) && (@code_order)) {
                   9890:         my @clonecodes = split(/\+/,$domdefclone);
                   9891:         my $instcoderegexp ='^';
                   9892:         foreach my $item (@code_order) {
                   9893:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9894:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9895:             } else {
                   9896:                 $instcoderegexp .= $codedefaults{$item};
                   9897:             }
                   9898:         }
                   9899:         $instcoderegexp .= '$';
                   9900:         my (@from,@to);
                   9901:         eval {
                   9902:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9903:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9904:         };
                   9905:         if ((@from > 0) && (@to > 0)) {
                   9906:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9907:             if (!@diffs) {
                   9908:                 $canclone = 1;
                   9909:             }
                   9910:         }
                   9911:     }
                   9912:     return $canclone;
                   9913: }
                   9914: 
1.679     raeburn  9915: # ------------------------------------------------------- Course Group routines
                   9916: 
                   9917: sub get_coursegroups {
1.809     raeburn  9918:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9919:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9920: }
                   9921: 
1.679     raeburn  9922: sub modify_coursegroup {
                   9923:     my ($cdom,$cnum,$groupsettings) = @_;
                   9924:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9925: }
                   9926: 
1.809     raeburn  9927: sub toggle_coursegroup_status {
                   9928:     my ($cdom,$cnum,$group,$action) = @_;
                   9929:     my ($from_namespace,$to_namespace);
                   9930:     if ($action eq 'delete') {
                   9931:         $from_namespace = 'coursegroups';
                   9932:         $to_namespace = 'deleted_groups';
                   9933:     } else {
                   9934:         $from_namespace = 'deleted_groups';
                   9935:         $to_namespace = 'coursegroups';
                   9936:     }
                   9937:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9938:     if (my $tmp = &error(%curr_group)) {
                   9939:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9940:         return ('read error',$tmp);
                   9941:     } else {
                   9942:         my %savedsettings = %curr_group; 
1.809     raeburn  9943:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9944:         my $deloutcome;
                   9945:         if ($result eq 'ok') {
1.809     raeburn  9946:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9947:         } else {
                   9948:             return ('write error',$result);
                   9949:         }
                   9950:         if ($deloutcome eq 'ok') {
                   9951:             return 'ok';
                   9952:         } else {
                   9953:             return ('delete error',$deloutcome);
                   9954:         }
                   9955:     }
                   9956: }
                   9957: 
1.679     raeburn  9958: sub modify_group_roles {
1.957     raeburn  9959:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9960:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9961:     my $role = 'gr/'.&escape($userprivs);
                   9962:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9963:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9964:     if ($result eq 'ok') {
                   9965:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9966:     }
1.679     raeburn  9967:     return $result;
                   9968: }
                   9969: 
                   9970: sub modify_coursegroup_membership {
                   9971:     my ($cdom,$cnum,$membership) = @_;
                   9972:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9973:     return $result;
                   9974: }
                   9975: 
1.682     raeburn  9976: sub get_active_groups {
                   9977:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9978:     my $now = time;
                   9979:     my %groups = ();
                   9980:     foreach my $key (keys(%env)) {
1.811     albertel 9981:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9982:             my ($start,$end) = split(/\./,$env{$key});
                   9983:             if (($end!=0) && ($end<$now)) { next; }
                   9984:             if (($start!=0) && ($start>$now)) { next; }
                   9985:             if ($1 eq $cdom && $2 eq $cnum) {
                   9986:                 $groups{$3} = $env{$key} ;
                   9987:             }
                   9988:         }
                   9989:     }
                   9990:     return %groups;
                   9991: }
                   9992: 
1.683     raeburn  9993: sub get_group_membership {
                   9994:     my ($cdom,$cnum,$group) = @_;
                   9995:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9996: }
                   9997: 
                   9998: sub get_users_groups {
                   9999:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10000:     my @usersgroups;
1.683     raeburn  10001:     my $cachetime=1800;
                   10002: 
                   10003:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10004:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10005:     if (defined($cached)) {
1.734     albertel 10006:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10007:     } else {  
                   10008:         $grouplist = '';
1.816     raeburn  10009:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10010:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10011:         my $access_end = $env{'course.'.$courseid.
                   10012:                               '.default_enrollment_end_date'};
                   10013:         my $now = time;
                   10014:         foreach my $key (keys(%roleshash)) {
                   10015:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10016:                 my $group = $1;
                   10017:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10018:                     my $start = $2;
                   10019:                     my $end = $1;
                   10020:                     if ($start == -1) { next; } # deleted from group
                   10021:                     if (($start!=0) && ($start>$now)) { next; }
                   10022:                     if (($end!=0) && ($end<$now)) {
                   10023:                         if ($access_end && $access_end < $now) {
                   10024:                             if ($access_end - $end < 86400) {
                   10025:                                 push(@usersgroups,$group);
1.733     raeburn  10026:                             }
                   10027:                         }
1.817     raeburn  10028:                         next;
1.733     raeburn  10029:                     }
1.817     raeburn  10030:                     push(@usersgroups,$group);
1.683     raeburn  10031:                 }
                   10032:             }
                   10033:         }
1.817     raeburn  10034:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10035:         $grouplist = join(':',@usersgroups);
                   10036:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10037:     }
1.733     raeburn  10038:     return @usersgroups;
1.683     raeburn  10039: }
                   10040: 
                   10041: sub devalidate_getgroups_cache {
                   10042:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10043:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10044: 
1.683     raeburn  10045:     my $hashid="$udom:$uname:$courseid";
                   10046:     &devalidate_cache_new('getgroups',$hashid);
                   10047: }
                   10048: 
1.12      www      10049: # ------------------------------------------------------------------ Plain Text
                   10050: 
                   10051: sub plaintext {
1.988     raeburn  10052:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10053:     if ($short =~ m{^cr/}) {
1.758     albertel 10054: 	return (split('/',$short))[-1];
                   10055:     }
1.742     raeburn  10056:     if (!defined($cid)) {
                   10057:         $cid = $env{'request.course.id'};
                   10058:     }
                   10059:     my %rolenames = (
1.1008    raeburn  10060:                       Course    => 'std',
                   10061:                       Community => 'alt1',
1.742     raeburn  10062:                     );
1.1037    raeburn  10063:     if ($cid ne '') {
                   10064:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10065:             unless ($forcedefault) {
                   10066:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10067:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10068:                 return &Apache::lonlocal::mt($roletext);
                   10069:             }
                   10070:         }
                   10071:     }
                   10072:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10073:         (defined($rolenames{$type})) && 
                   10074:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10075:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10076:     } elsif ($cid ne '') {
                   10077:         my $crstype = $env{'course.'.$cid.'.type'};
                   10078:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10079:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10080:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10081:         }
1.742     raeburn  10082:     }
1.1037    raeburn  10083:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10084: }
                   10085: 
                   10086: # ----------------------------------------------------------------- Assign Role
                   10087: 
                   10088: sub assignrole {
1.957     raeburn  10089:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10090:         $context)=@_;
1.21      www      10091:     my $mrole;
                   10092:     if ($role =~ /^cr\//) {
1.393     www      10093:         my $cwosec=$url;
1.811     albertel 10094:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10095: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10096:            my $refused = 1;
                   10097:            if ($context eq 'requestcourses') {
                   10098:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10099:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10100:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10101:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10102:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10103:                            if ($crsenv{'internal.courseowner'} eq
                   10104:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10105:                                $refused = '';
                   10106:                            }
                   10107:                        }
                   10108:                    }
                   10109:                }
                   10110:            }
                   10111:            if ($refused) {
                   10112:                &logthis('Refused custom assignrole: '.
                   10113:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10114:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10115:                return 'refused';
                   10116:            }
1.104     www      10117:         }
1.21      www      10118:         $mrole='cr';
1.678     raeburn  10119:     } elsif ($role =~ /^gr\//) {
                   10120:         my $cwogrp=$url;
1.811     albertel 10121:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10122:         unless (&allowed('mdg',$cwogrp)) {
                   10123:             &logthis('Refused group assignrole: '.
                   10124:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10125:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10126:             return 'refused';
                   10127:         }
                   10128:         $mrole='gr';
1.21      www      10129:     } else {
1.82      www      10130:         my $cwosec=$url;
1.811     albertel 10131:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10132:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10133:             my $refused;
                   10134:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10135:                 if (!(&allowed('c'.$role,$url))) {
                   10136:                     $refused = 1;
                   10137:                 }
                   10138:             } else {
                   10139:                 $refused = 1;
                   10140:             }
1.947     raeburn  10141:             if ($refused) {
1.1045    raeburn  10142:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10143:                 if (!$selfenroll && $context eq 'course') {
                   10144:                     my %crsenv;
                   10145:                     if ($role eq 'cc' || $role eq 'co') {
                   10146:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10147:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10148:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10149:                                 if ($crsenv{'internal.courseowner'} eq 
                   10150:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10151:                                     $refused = '';
                   10152:                                 }
                   10153:                             }
                   10154:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10155:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10156:                                 if ($crsenv{'internal.courseowner'} eq 
                   10157:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10158:                                     $refused = '';
                   10159:                                 }
                   10160:                             }
                   10161:                         }
                   10162:                     }
                   10163:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10164:                     $refused = '';
1.1017    raeburn  10165:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10166:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10167:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10168:                         my $wrongcc;
                   10169:                         if ($cnum =~ /^$match_community$/) {
                   10170:                             $wrongcc = 1 if ($role eq 'cc');
                   10171:                         } else {
                   10172:                             $wrongcc = 1 if ($role eq 'co');
                   10173:                         }
                   10174:                         unless ($wrongcc) {
                   10175:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10176:                             if ($crsenv{'internal.courseowner'} eq 
                   10177:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10178:                                 $refused = '';
                   10179:                             }
1.1017    raeburn  10180:                         }
                   10181:                     }
1.1172.2.9  raeburn  10182:                 } elsif ($context eq 'requestauthor') {
                   10183:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10184:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10185:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10186:                             $refused = '';
                   10187:                         } else {
                   10188:                             my %domdefaults = &get_domain_defaults($udom);
                   10189:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10190:                                 my $checkbystatus;
                   10191:                                 if ($env{'user.adv'}) {
                   10192:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10193:                                     if ($disposition eq 'automatic') {
                   10194:                                         $refused = '';
                   10195:                                     } elsif ($disposition eq '') {
                   10196:                                         $checkbystatus = 1;
                   10197:                                     }
                   10198:                                 } else {
                   10199:                                     $checkbystatus = 1;
                   10200:                                 }
                   10201:                                 if ($checkbystatus) {
                   10202:                                     if ($env{'environment.inststatus'}) {
                   10203:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10204:                                         foreach my $type (@inststatuses) {
                   10205:                                             if (($type ne '') &&
                   10206:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10207:                                                 $refused = '';
                   10208:                                             }
                   10209:                                         }
                   10210:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10211:                                         $refused = '';
                   10212:                                     }
                   10213:                                 }
                   10214:                             }
                   10215:                         }
                   10216:                     }
1.1017    raeburn  10217:                 }
                   10218:                 if ($refused) {
1.947     raeburn  10219:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10220:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10221: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10222:                     return 'refused';
                   10223:                 }
1.932     raeburn  10224:             }
1.1131    raeburn  10225:         } elsif ($role eq 'au') {
                   10226:             if ($url ne '/'.$udom.'/') {
                   10227:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10228:                          ' to assign author role for '.$uname.':'.$udom.
                   10229:                          ' in domain: '.$url.' refused (wrong domain).');
                   10230:                 return 'refused';
                   10231:             }
1.104     www      10232:         }
1.21      www      10233:         $mrole=$role;
                   10234:     }
1.620     albertel 10235:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10236:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10237:     if ($end) { $command.='_'.$end; }
1.21      www      10238:     if ($start) {
                   10239: 	if ($end) { 
1.81      www      10240:            $command.='_'.$start; 
1.21      www      10241:         } else {
1.81      www      10242:            $command.='_0_'.$start;
1.21      www      10243:         }
                   10244:     }
1.739     raeburn  10245:     my $origstart = $start;
                   10246:     my $origend = $end;
1.957     raeburn  10247:     my $delflag;
1.357     www      10248: # actually delete
                   10249:     if ($deleteflag) {
1.373     www      10250: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10251: # modify command to delete the role
1.620     albertel 10252:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10253:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10254: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10255: # set start and finish to negative values for userrolelog
                   10256:            $start=-1;
                   10257:            $end=-1;
1.957     raeburn  10258:            $delflag = 1;
1.357     www      10259:         }
                   10260:     }
                   10261: # send command
1.349     www      10262:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10263: # log new user role if status is ok
1.349     www      10264:     if ($answer eq 'ok') {
1.663     raeburn  10265: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10266:         if (($role eq 'cc') || ($role eq 'in') ||
                   10267:             ($role eq 'ep') || ($role eq 'ad') ||
                   10268:             ($role eq 'ta') || ($role eq 'st') ||
                   10269:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10270:             ($role eq 'co')) {
1.1172.2.13  raeburn  10271: # for course roles, perform group memberships changes triggered by role change.
                   10272:             unless ($role =~ /^gr/) {
                   10273:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10274:                                                  $origstart,$selfenroll,$context);
                   10275:             }
1.1172.2.9  raeburn  10276:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10277:                            $selfenroll,$context);
                   10278:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10279:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10280:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10281:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10282:                            $context);
                   10283:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10284:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10285:                              $context);
                   10286:         }
1.1053    raeburn  10287:         if ($role eq 'cc') {
                   10288:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10289:         }
1.349     www      10290:     }
                   10291:     return $answer;
1.169     harris41 10292: }
                   10293: 
1.1053    raeburn  10294: sub autoupdate_coowners {
                   10295:     my ($url,$end,$start,$uname,$udom) = @_;
                   10296:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10297:     if (($cdom ne '') && ($cnum ne '')) {
                   10298:         my $now = time;
                   10299:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10300:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10301:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10302:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10303:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10304:             if ($instcode ne '') {
1.1056    raeburn  10305:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10306:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10307:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10308:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10309:                         unless ($result eq 'valid') {
                   10310:                             if ($xlists ne '') {
                   10311:                                 foreach my $xlist (split(',',$xlists)) {
                   10312:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10313:                                     $result =
                   10314:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10315:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10316:                                     last if ($result eq 'valid');
                   10317:                                 }
                   10318:                             }
                   10319:                         }
1.1056    raeburn  10320:                         if ($result eq 'valid') {
                   10321:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10322:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10323:                                     push(@newcoowners,$coowner);
                   10324:                                 }
                   10325:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10326:                                     push(@newcoowners,$uname.':'.$udom);
                   10327:                                 }
                   10328:                                 @newcoowners = sort(@newcoowners);
                   10329:                             } else {
                   10330:                                 push(@newcoowners,$uname.':'.$udom);
                   10331:                             }
1.1172.2.141  raeburn  10332:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10333:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10334:                                 unless ($coowner eq $uname.':'.$udom) {
                   10335:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10336:                                 }
                   10337:                             }
1.1172.2.141  raeburn  10338:                             unless (@newcoowners > 0) {
                   10339:                                 $delcoowners = 1;
                   10340:                                 $coowners = '';
                   10341:                             }
1.1053    raeburn  10342:                         }
                   10343:                         if (@newcoowners || $delcoowners) {
                   10344:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10345:                                             $delcoowners,@newcoowners);
                   10346:                         }
                   10347:                     }
                   10348:                 }
                   10349:             }
                   10350:         }
                   10351:     }
                   10352: }
                   10353: 
                   10354: sub store_coowners {
                   10355:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10356:     my $cid = $cdom.'_'.$cnum;
                   10357:     my ($coowners,$delresult,$putresult);
                   10358:     if (@newcoowners) {
                   10359:         $coowners = join(',',@newcoowners);
                   10360:         my %coownershash = (
                   10361:                             'internal.co-owners' => $coowners,
                   10362:                            );
                   10363:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10364:         if ($putresult eq 'ok') {
                   10365:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10366:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10367:             }
                   10368:         }
                   10369:     }
                   10370:     if ($delcoowners) {
                   10371:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10372:         if ($delresult eq 'ok') {
                   10373:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10374:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10375:             }
                   10376:         }
                   10377:     }
                   10378:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10379:         my %crsinfo =
                   10380:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10381:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10382:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10383:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10384:         }
                   10385:     }
                   10386: }
                   10387: 
1.169     harris41 10388: # -------------------------------------------------- Modify user authentication
1.197     www      10389: # Overrides without validation
                   10390: 
1.169     harris41 10391: sub modifyuserauth {
                   10392:     my ($udom,$uname,$umode,$upass)=@_;
                   10393:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10394:     my $allowed;
                   10395:     if (&allowed('mau',$udom)) {
                   10396:         $allowed = 1;
                   10397:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10398:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10399:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10400:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10401:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10402:         if (($cdom ne '') && ($cnum ne '')) {
                   10403:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10404:             if ($is_owner) {
                   10405:                 $allowed = 1;
                   10406:             }
                   10407:         }
                   10408:     }
                   10409:     unless ($allowed) { return 'refused'; }
1.197     www      10410:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10411:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10412:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10413:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10414: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10415:     my $ip = &get_requestor_ip();
1.620     albertel 10416:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10417:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10418:          '(Remote '.$ip.'): '.$reply);
1.197     www      10419:     &log($udom,,$uname,$uhome,
1.620     albertel 10420:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10421:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10422:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10423:     unless ($reply eq 'ok') {
1.197     www      10424:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10425: 	return 'error: '.$reply;
                   10426:     }   
1.170     harris41 10427:     return 'ok';
1.80      www      10428: }
                   10429: 
1.81      www      10430: # --------------------------------------------------------------- Modify a user
1.80      www      10431: 
1.81      www      10432: sub modifyuser {
1.206     matthew  10433:     my ($udom,    $uname, $uid,
                   10434:         $umode,   $upass, $first,
                   10435:         $middle,  $last,  $gene,
1.1058    raeburn  10436:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10437:     $udom= &LONCAPA::clean_domain($udom);
                   10438:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10439:     my $showcandelete = 'none';
                   10440:     if (ref($candelete) eq 'ARRAY') {
                   10441:         if (@{$candelete} > 0) {
                   10442:             $showcandelete = join(', ',@{$candelete});
                   10443:         }
                   10444:     }
1.81      www      10445:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10446:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10447: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10448:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10449:                                      ' desiredhome not specified'). 
1.620     albertel 10450:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10451:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10452:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10453:     my $newuser;
                   10454:     if ($uhome eq 'no_host') {
                   10455:         $newuser = 1;
                   10456:     }
1.80      www      10457: # ----------------------------------------------------------------- Create User
1.406     albertel 10458:     if (($uhome eq 'no_host') && 
                   10459: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10460:         my $unhome='';
1.844     albertel 10461:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10462:             $unhome = $desiredhome;
1.620     albertel 10463: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10464: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10465:         } else { # load balancing routine for determining $unhome
1.81      www      10466:             my $loadm=10000000;
1.841     albertel 10467: 	    my %servers = &get_servers($udom,'library');
                   10468: 	    foreach my $tryserver (keys(%servers)) {
                   10469: 		my $answer=reply('load',$tryserver);
                   10470: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10471: 		    $loadm=$answer;
                   10472: 		    $unhome=$tryserver;
                   10473: 		}
1.80      www      10474: 	    }
                   10475:         }
                   10476:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10477: 	    return 'error: unable to find a home server for '.$uname.
                   10478:                    ' in domain '.$udom;
1.80      www      10479:         }
                   10480:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10481:                          &escape($upass),$unhome);
                   10482: 	unless ($reply eq 'ok') {
                   10483:             return 'error: '.$reply;
                   10484:         }   
1.230     stredwic 10485:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10486:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10487: 	    return 'error: unable verify users home machine.';
1.80      www      10488:         }
1.209     matthew  10489:     }   # End of creation of new user
1.80      www      10490: # ---------------------------------------------------------------------- Add ID
                   10491:     if ($uid) {
                   10492:        $uid=~tr/A-Z/a-z/;
                   10493:        my %uidhash=&idrget($udom,$uname);
1.196     www      10494:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10495:          && (!$forceid)) {
1.80      www      10496: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10497: 	      return 'error: user id "'.$uid.'" does not match '.
                   10498:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10499:           }
                   10500:        } else {
                   10501: 	  &idput($udom,($uname => $uid));
                   10502:        }
                   10503:     }
                   10504: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10505:     my @tmp=&get('environment',
1.899     raeburn  10506: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10507:                     'permanentemail','inststatus'],
1.134     albertel 10508: 		   $udom,$uname);
1.1075    raeburn  10509:     my (%names,%oldnames);
1.313     matthew  10510:     if ($tmp[0] =~ m/^error:.*/) { 
                   10511:         %names=(); 
                   10512:     } else {
                   10513:         %names = @tmp;
1.1075    raeburn  10514:         %oldnames = %names;
1.313     matthew  10515:     }
1.388     www      10516: #
1.1058    raeburn  10517: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10518: # of users did not contain them), do not overwrite existing values
                   10519: # unless field is in $candelete array ref.  
                   10520: #
                   10521: 
                   10522:     my @fields = ('firstname','middlename','lastname','generation',
                   10523:                   'permanentemail','id');
                   10524:     my %newvalues;
                   10525:     if (ref($candelete) eq 'ARRAY') {
                   10526:         foreach my $field (@fields) {
                   10527:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10528:                 if ($field eq 'firstname') {
                   10529:                     $names{$field} = $first;
                   10530:                 } elsif ($field eq 'middlename') {
                   10531:                     $names{$field} = $middle;
                   10532:                 } elsif ($field eq 'lastname') {
                   10533:                     $names{$field} = $last;
                   10534:                 } elsif ($field eq 'generation') { 
                   10535:                     $names{$field} = $gene;
                   10536:                 } elsif ($field eq 'permanentemail') {
                   10537:                     $names{$field} = $email;
                   10538:                 } elsif ($field eq 'id') {
                   10539:                     $names{$field}  = $uid;
                   10540:                 }
                   10541:             }
                   10542:         }
                   10543:     }
1.388     www      10544:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10545:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10546:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10547:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10548:     if ($email) {
                   10549:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10550:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10551:     }
1.899     raeburn  10552:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10553:     if (defined($inststatus)) {
                   10554:         $names{'inststatus'} = '';
                   10555:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10556:         if (ref($usertypes) eq 'HASH') {
                   10557:             my @okstatuses; 
                   10558:             foreach my $item (split(/:/,$inststatus)) {
                   10559:                 if (defined($usertypes->{$item})) {
                   10560:                     push(@okstatuses,$item);  
                   10561:                 }
                   10562:             }
                   10563:             if (@okstatuses) {
                   10564:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10565:             }
                   10566:         }
                   10567:     }
1.1075    raeburn  10568:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10569:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10570:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10571:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10572:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10573:     } else {
                   10574:         $logmsg .= ' during self creation';
                   10575:     }
1.1075    raeburn  10576:     my $changed;
                   10577:     if ($newuser) {
                   10578:         $changed = 1;
                   10579:     } else {
                   10580:         foreach my $field (@fields) {
                   10581:             if ($names{$field} ne $oldnames{$field}) {
                   10582:                 $changed = 1;
                   10583:                 last;
                   10584:             }
                   10585:         }
                   10586:     }
                   10587:     unless ($changed) {
                   10588:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10589:         &logthis($logmsg);
                   10590:         return 'ok';
                   10591:     }
                   10592:     my $reply = &put('environment', \%names, $udom,$uname);
                   10593:     if ($reply ne 'ok') { 
                   10594:         return 'error: '.$reply;
                   10595:     }
1.1087    raeburn  10596:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10597:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10598:     }
1.1075    raeburn  10599:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10600:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10601:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10602:     &logthis($logmsg);
1.134     albertel 10603:     return 'ok';
1.80      www      10604: }
                   10605: 
1.81      www      10606: # -------------------------------------------------------------- Modify student
1.80      www      10607: 
1.81      www      10608: sub modifystudent {
                   10609:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10610:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10611:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10612:     if (!$cid) {
1.620     albertel 10613: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10614: 	    return 'not_in_class';
                   10615: 	}
1.80      www      10616:     }
                   10617: # --------------------------------------------------------------- Make the user
1.81      www      10618:     my $reply=&modifyuser
1.209     matthew  10619: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10620:          $desiredhome,$email,$inststatus);
1.80      www      10621:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10622:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10623:     # student's environment
1.297     matthew  10624:     $uid = undef if (!$forceid);
1.455     albertel 10625:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10626: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10627:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10628:     return $reply;
                   10629: }
                   10630: 
                   10631: sub modify_student_enrollment {
1.1172.2.23  raeburn  10632:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10633:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10634:     my ($cdom,$cnum,$chome);
                   10635:     if (!$cid) {
1.620     albertel 10636: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10637: 	    return 'not_in_class';
                   10638: 	}
1.620     albertel 10639: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10640: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10641:     } else {
                   10642: 	($cdom,$cnum)=split(/_/,$cid);
                   10643:     }
1.620     albertel 10644:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10645:     if (!$chome) {
1.457     raeburn  10646: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10647:     }
1.455     albertel 10648:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10649:     # Make sure the user exists
1.81      www      10650:     my $uhome=&homeserver($uname,$udom);
                   10651:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10652: 	return 'error: no such user';
                   10653:     }
1.297     matthew  10654:     # Get student data if we were not given enough information
                   10655:     if (!defined($first)  || $first  eq '' || 
                   10656:         !defined($last)   || $last   eq '' || 
                   10657:         !defined($uid)    || $uid    eq '' || 
                   10658:         !defined($middle) || $middle eq '' || 
                   10659:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10660:         # They did not supply us with enough data to enroll the student, so
                   10661:         # we need to pick up more information.
1.297     matthew  10662:         my %tmp = &get('environment',
1.294     matthew  10663:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10664:                        ,$udom,$uname);
                   10665: 
1.800     albertel 10666:         #foreach my $key (keys(%tmp)) {
                   10667:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10668:         #}
1.294     matthew  10669:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10670:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10671:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10672:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10673:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10674:     }
1.556     albertel 10675:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10676:     my $user = "$uname:$udom";
                   10677:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10678:     my $reply=cput('classlist',
1.1148    raeburn  10679: 		   {$user => 
1.1172.2.76  raeburn  10680: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10681: 		   $cdom,$cnum);
1.1148    raeburn  10682:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10683:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10684:     } else { 
1.81      www      10685: 	return 'error: '.$reply;
                   10686:     }
1.297     matthew  10687:     # Add student role to user
1.83      www      10688:     my $uurl='/'.$cid;
1.81      www      10689:     $uurl=~s/\_/\//g;
                   10690:     if ($usec) {
                   10691: 	$uurl.='/'.$usec;
                   10692:     }
1.1148    raeburn  10693:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10694:                              $selfenroll,$context);
                   10695:     if ($result ne 'ok') {
                   10696:         if ($old_entry{$user} ne '') {
                   10697:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10698:         } else {
                   10699:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10700:         }
                   10701:     }
                   10702:     return $result; 
1.21      www      10703: }
                   10704: 
1.556     albertel 10705: sub format_name {
                   10706:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10707:     my $name;
                   10708:     if ($first ne 'lastname') {
                   10709: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10710:     } else {
                   10711: 	if ($lastname=~/\S/) {
                   10712: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10713: 	    $name=~s/\s+,/,/;
                   10714: 	} else {
                   10715: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10716: 	}
                   10717:     }
                   10718:     $name=~s/^\s+//;
                   10719:     $name=~s/\s+$//;
                   10720:     $name=~s/\s+/ /g;
                   10721:     return $name;
                   10722: }
                   10723: 
1.84      www      10724: # ------------------------------------------------- Write to course preferences
                   10725: 
                   10726: sub writecoursepref {
                   10727:     my ($courseid,%prefs)=@_;
                   10728:     $courseid=~s/^\///;
                   10729:     $courseid=~s/\_/\//g;
                   10730:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10731:     my $chome=homeserver($cnum,$cdomain);
                   10732:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10733: 	return 'error: no such course';
                   10734:     }
                   10735:     my $cstring='';
1.800     albertel 10736:     foreach my $pref (keys(%prefs)) {
                   10737: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10738:     }
1.84      www      10739:     $cstring=~s/\&$//;
                   10740:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10741: }
                   10742: 
                   10743: # ---------------------------------------------------------- Make/modify course
                   10744: 
                   10745: sub createcourse {
1.741     raeburn  10746:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10747:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10748:     $url=&declutter($url);
                   10749:     my $cid='';
1.1028    raeburn  10750:     if ($context eq 'requestcourses') {
                   10751:         my $can_create = 0;
                   10752:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10753:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10754:22):             my $reload;
                   10755:22):             if (($callercontext eq 'auto') &&
                   10756:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10757:22):                 $reload = 'reload';
                   10758:22):             }
                   10759:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10760:                                   $context)) {
                   10761:                 $can_create = 1;
                   10762:             }
                   10763:         } else {
                   10764:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10765:                                            $category);
                   10766:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10767:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10768:                 if (@curr > 0) {
                   10769:                     my @options = qw(approval validate autolimit);
                   10770:                     my $optregex = join('|',@options);
                   10771:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10772:                         $can_create = 1;
                   10773:                     }
                   10774:                 }
                   10775:             }
                   10776:         }
                   10777:         if ($can_create) {
                   10778:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10779:                 unless (&allowed('ccc',$udom)) {
                   10780:                     return 'refused'; 
                   10781:                 }
1.1017    raeburn  10782:             }
                   10783:         } else {
                   10784:             return 'refused';
                   10785:         }
1.1028    raeburn  10786:     } elsif (!&allowed('ccc',$udom)) {
                   10787:         return 'refused';
1.84      www      10788:     }
1.1011    raeburn  10789: # --------------------------------------------------------------- Get Unique ID
                   10790:     my $uname;
                   10791:     if ($cnum =~ /^$match_courseid$/) {
                   10792:         my $chome=&homeserver($cnum,$udom,'true');
                   10793:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10794:             $uname = $cnum;
                   10795:         } else {
1.1038    raeburn  10796:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10797:         }
                   10798:     } else {
1.1038    raeburn  10799:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10800:     }
                   10801:     return $uname if ($uname =~ /^error/);
                   10802: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10803:     if (!defined($course_server)) {
                   10804:         if (defined(&domain($udom,'primary'))) {
                   10805:             $course_server = &domain($udom,'primary');
                   10806:         } else {
                   10807:             $course_server = $env{'user.home'}; 
                   10808:         }
                   10809:     }
                   10810:     my %host_servers =
                   10811:         &Apache::lonnet::get_servers($udom,'library');
                   10812:     unless ($host_servers{$course_server}) {
                   10813:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10814:     }
1.84      www      10815: # ------------------------------------------------------------- Make the course
                   10816:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10817:                       $course_server);
1.84      www      10818:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10819:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10820:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10821: 	return 'error: no such course';
                   10822:     }
1.271     www      10823: # ----------------------------------------------------------------- Course made
1.516     raeburn  10824: # log existence
1.1029    raeburn  10825:     my $now = time;
1.918     raeburn  10826:     my $newcourse = {
                   10827:                     $udom.'_'.$uname => {
1.921     raeburn  10828:                                      description => $description,
                   10829:                                      inst_code   => $inst_code,
                   10830:                                      owner       => $course_owner,
                   10831:                                      type        => $crstype,
1.1029    raeburn  10832:                                      creator     => $env{'user.name'}.':'.
                   10833:                                                     $env{'user.domain'},
                   10834:                                      created     => $now,
                   10835:                                      context     => $context,
1.918     raeburn  10836:                                                 },
                   10837:                     };
1.921     raeburn  10838:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10839: # set toplevel url
1.271     www      10840:     my $topurl=$url;
                   10841:     unless ($nonstandard) {
                   10842: # ------------------------------------------ For standard courses, make top url
                   10843:         my $mapurl=&clutter($url);
1.278     www      10844:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10845:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10846: <map>
                   10847: <resource id="1" type="start"></resource>
                   10848: <resource id="2" src="$mapurl"></resource>
                   10849: <resource id="3" type="finish"></resource>
                   10850: <link index="1" from="1" to="2"></link>
                   10851: <link index="2" from="2" to="3"></link>
                   10852: </map>
                   10853: ENDINITMAP
                   10854:         $topurl=&declutter(
1.638     albertel 10855:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10856:                           );
                   10857:     }
                   10858: # ----------------------------------------------------------- Write preferences
1.84      www      10859:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10860:                      ('description'              => $description,
                   10861:                       'url'                      => $topurl,
                   10862:                       'internal.creator'         => $env{'user.name'}.':'.
                   10863:                                                     $env{'user.domain'},
                   10864:                       'internal.created'         => $now,
                   10865:                       'internal.creationcontext' => $context)
                   10866:                     );
1.84      www      10867:     return '/'.$udom.'/'.$uname;
                   10868: }
                   10869: 
1.1011    raeburn  10870: # ------------------------------------------------------------------- Create ID
                   10871: sub generate_coursenum {
1.1038    raeburn  10872:     my ($udom,$crstype) = @_;
1.1011    raeburn  10873:     my $domdesc = &domain($udom);
                   10874:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10875:     my $first;
                   10876:     if ($crstype eq 'Community') {
                   10877:         $first = '0';
                   10878:     } else {
                   10879:         $first = int(1+rand(9)); 
                   10880:     } 
                   10881:     my $uname=$first.
1.1011    raeburn  10882:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10883:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10884:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10885: # ----------------------------------------------- Make sure that does not exist
                   10886:     my $uhome=&homeserver($uname,$udom,'true');
                   10887:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10888:         if ($crstype eq 'Community') {
                   10889:             $first = '0';
                   10890:         } else {
                   10891:             $first = int(1+rand(9));
                   10892:         }
                   10893:         $uname=$first.
1.1011    raeburn  10894:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10895:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10896:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10897:         $uhome=&homeserver($uname,$udom,'true');
                   10898:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10899:             return 'error: unable to generate unique course-ID';
                   10900:         }
                   10901:     }
                   10902:     return $uname;
                   10903: }
                   10904: 
1.813     albertel 10905: sub is_course {
1.1167    droeschl 10906:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10907:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10908:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10909:     my $uhome=&homeserver($cnum,$cdom);
                   10910:     my $iscourse;
                   10911:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10912:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10913:     } else {
                   10914:         my $hashid = $cdom.':'.$cnum;
                   10915:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10916:         unless (defined($cached)) {
                   10917:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10918:                                         $cnum,undef,undef,'.');
                   10919:             $iscourse = 0;
                   10920:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10921:                 $iscourse = 1;
                   10922:             }
                   10923:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10924:         }
                   10925:     }
                   10926:     return unless($iscourse);
1.1167    droeschl 10927:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10928: }
                   10929: 
1.1015    raeburn  10930: sub store_userdata {
                   10931:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10932:     my $result;
1.1016    raeburn  10933:     if ($datakey ne '') {
1.1013    raeburn  10934:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10935:             if ($udom eq '' || $uname eq '') {
                   10936:                 $udom = $env{'user.domain'};
                   10937:                 $uname = $env{'user.name'};
                   10938:             }
                   10939:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10940:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10941:                 $result = 'error: no_host';
                   10942:             } else {
1.1172.2.138  raeburn  10943:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10944:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10945: 
                   10946:                 my $namevalue='';
                   10947:                 foreach my $key (keys(%{$storehash})) {
                   10948:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10949:                 }
                   10950:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10951:                 unless ($namespace eq 'courserequests') {
                   10952:                     $datakey = &escape($datakey);
                   10953:                 }
1.1105    raeburn  10954:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10955:                                   $namevalue,$uhome);
1.1013    raeburn  10956:             }
                   10957:         } else {
                   10958:             $result = 'error: data to store was not a hash reference'; 
                   10959:         }
                   10960:     } else {
                   10961:         $result= 'error: invalid requestkey'; 
                   10962:     }
                   10963:     return $result;
                   10964: }
                   10965: 
1.21      www      10966: # ---------------------------------------------------------- Assign Custom Role
                   10967: 
                   10968: sub assigncustomrole {
1.957     raeburn  10969:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10970:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10971:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10972: }
                   10973: 
                   10974: # ----------------------------------------------------------------- Revoke Role
                   10975: 
                   10976: sub revokerole {
1.957     raeburn  10977:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10978:     my $now=time;
1.965     raeburn  10979:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10980: }
                   10981: 
                   10982: # ---------------------------------------------------------- Revoke Custom Role
                   10983: 
                   10984: sub revokecustomrole {
1.957     raeburn  10985:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10986:     my $now=time;
1.357     www      10987:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10988:            $deleteflag,$selfenroll,$context);
1.17      www      10989: }
                   10990: 
1.533     banghart 10991: # ------------------------------------------------------------ Disk usage
1.535     albertel 10992: sub diskusage {
1.955     raeburn  10993:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10994:     $directorypath =~ s/\/$//;
                   10995:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10996:                        .&escape($getpropath).':'.&escape($uname).':'
                   10997:                        .&escape($udom),homeserver($uname,$udom));
                   10998:     if ($listing eq 'unknown_cmd') {
                   10999:         if ($getpropath) {
                   11000:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11001:         }
                   11002:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11003:     }
1.514     albertel 11004:     return $listing;
1.512     banghart 11005: }
                   11006: 
1.566     banghart 11007: sub is_locked {
1.1096    raeburn  11008:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11009:     my @check;
                   11010:     my $is_locked;
1.1093    raeburn  11011:     push (@check,$file_name);
1.613     albertel 11012:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11013: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11014:     my ($tmp)=keys(%locked);
                   11015:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11016:     
1.566     banghart 11017:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11018:         $is_locked = 'false';
                   11019:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11020:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11021:                $is_locked = 'true';
1.1096    raeburn  11022:                if (ref($which) eq 'ARRAY') {
                   11023:                    push(@{$which},$entry);
                   11024:                } else {
                   11025:                    last;
                   11026:                }
1.745     raeburn  11027:            }
                   11028:        }
1.566     banghart 11029:     } else {
                   11030:         $is_locked = 'false';
                   11031:     }
1.1093    raeburn  11032:     return $is_locked;
1.566     banghart 11033: }
                   11034: 
1.759     albertel 11035: sub declutter_portfile {
                   11036:     my ($file) = @_;
1.833     albertel 11037:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11038:     return $file;
                   11039: }
                   11040: 
1.559     banghart 11041: # ------------------------------------------------------------- Mark as Read Only
                   11042: 
                   11043: sub mark_as_readonly {
                   11044:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11045:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11046:     my ($tmp)=keys(%current_permissions);
                   11047:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11048:     foreach my $file (@{$files}) {
1.759     albertel 11049: 	$file = &declutter_portfile($file);
1.561     banghart 11050:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11051:     }
1.613     albertel 11052:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11053:     return;
                   11054: }
                   11055: 
1.572     banghart 11056: # ------------------------------------------------------------Save Selected Files
                   11057: 
                   11058: sub save_selected_files {
                   11059:     my ($user, $path, @files) = @_;
                   11060:     my $filename = $user."savedfiles";
1.573     banghart 11061:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11062:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11063:     foreach my $file (@files) {
1.620     albertel 11064:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11065:     }
                   11066:     foreach my $file (@other_files) {
1.574     banghart 11067:         print (OUT $file."\n");
1.572     banghart 11068:     }
1.574     banghart 11069:     close (OUT);
1.572     banghart 11070:     return 'ok';
                   11071: }
                   11072: 
1.574     banghart 11073: sub clear_selected_files {
                   11074:     my ($user) = @_;
                   11075:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11076:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11077:     print (OUT undef);
                   11078:     close (OUT);
                   11079:     return ("ok");    
                   11080: }
                   11081: 
1.572     banghart 11082: sub files_in_path {
                   11083:     my ($user, $path) = @_;
                   11084:     my $filename = $user."savedfiles";
                   11085:     my %return_files;
1.1172.2.96  raeburn  11086:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11087:     while (my $line_in = <IN>) {
1.574     banghart 11088:         chomp ($line_in);
                   11089:         my @paths_and_file = split (m!/!, $line_in);
                   11090:         my $file_part = pop (@paths_and_file);
                   11091:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11092:         $path_part.='/';
                   11093:         my $path_and_file = $path_part.$file_part;
                   11094:         if ($path_part eq $path) {
                   11095:             $return_files{$file_part}= 'selected';
                   11096:         }
                   11097:     }
1.574     banghart 11098:     close (IN);
                   11099:     return (\%return_files);
1.572     banghart 11100: }
                   11101: 
                   11102: # called in portfolio select mode, to show files selected NOT in current directory
                   11103: sub files_not_in_path {
                   11104:     my ($user, $path) = @_;
                   11105:     my $filename = $user."savedfiles";
                   11106:     my @return_files;
                   11107:     my $path_part;
1.1172.2.96  raeburn  11108:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11109:     while (my $line = <IN>) {
1.572     banghart 11110:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11111:         my @paths_and_file = split(m|/|, $line);
                   11112:         my $file_part = pop(@paths_and_file);
                   11113:         chomp($file_part);
                   11114:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11115:         $path_part .= '/';
                   11116:         my $path_and_file = $path_part.$file_part;
                   11117:         if ($path_part ne $path) {
1.800     albertel 11118:             push(@return_files, ($path_and_file));
1.572     banghart 11119:         }
                   11120:     }
1.800     albertel 11121:     close(OUT);
1.574     banghart 11122:     return (@return_files);
1.572     banghart 11123: }
                   11124: 
1.745     raeburn  11125: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11126: 
1.745     raeburn  11127: sub get_portfile_permissions {
                   11128:     my ($domain,$user) = @_;
1.613     albertel 11129:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11130:     my ($tmp)=keys(%current_permissions);
                   11131:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11132:     return \%current_permissions;
                   11133: }
                   11134: 
                   11135: #---------------------------------------------Get portfolio file access controls
                   11136: 
1.749     raeburn  11137: sub get_access_controls {
1.745     raeburn  11138:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11139:     my %access;
                   11140:     my $real_file = $file;
                   11141:     $file =~ s/\.meta$//;
1.745     raeburn  11142:     if (defined($file)) {
1.749     raeburn  11143:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11144:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11145:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11146:             }
                   11147:         }
1.745     raeburn  11148:     } else {
1.749     raeburn  11149:         foreach my $key (keys(%{$current_permissions})) {
                   11150:             if ($key =~ /\0accesscontrol$/) {
                   11151:                 if (defined($group)) {
                   11152:                     if ($key !~ m-^\Q$group\E/-) {
                   11153:                         next;
                   11154:                     }
                   11155:                 }
                   11156:                 my ($fullpath) = split(/\0/,$key);
                   11157:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11158:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11159:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11160:                     }
                   11161:                 }
                   11162:             }
                   11163:         }
                   11164:     }
                   11165:     return %access;
                   11166: }
                   11167: 
                   11168: sub modify_access_controls {
                   11169:     my ($file_name,$changes,$domain,$user)=@_;
                   11170:     my ($outcome,$deloutcome);
                   11171:     my %store_permissions;
                   11172:     my %new_values;
                   11173:     my %new_control;
                   11174:     my %translation;
                   11175:     my @deletions = ();
                   11176:     my $now = time;
                   11177:     if (exists($$changes{'activate'})) {
                   11178:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11179:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11180:             my $numnew = scalar(@newitems);
                   11181:             for (my $i=0; $i<$numnew; $i++) {
                   11182:                 my $newkey = $newitems[$i];
                   11183:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11184:                 if ($newkey =~ /^\d+:/) { 
                   11185:                     $newkey =~ s/^(\d+)/$newid/;
                   11186:                     $translation{$1} = $newid;
                   11187:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11188:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11189:                     $translation{$1} = $newid;
                   11190:                 }
1.749     raeburn  11191:                 $new_values{$file_name."\0".$newkey} = 
                   11192:                                           $$changes{'activate'}{$newitems[$i]};
                   11193:                 $new_control{$newkey} = $now;
                   11194:             }
                   11195:         }
                   11196:     }
                   11197:     my %todelete;
                   11198:     my %changed_items;
                   11199:     foreach my $action ('delete','update') {
                   11200:         if (exists($$changes{$action})) {
                   11201:             if (ref($$changes{$action}) eq 'HASH') {
                   11202:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11203:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11204:                     if ($action eq 'delete') { 
                   11205:                         $todelete{$itemnum} = 1;
                   11206:                     } else {
                   11207:                         $changed_items{$itemnum} = $key;
                   11208:                     }
                   11209:                 }
1.745     raeburn  11210:             }
                   11211:         }
1.749     raeburn  11212:     }
                   11213:     # get lock on access controls for file.
                   11214:     my $lockhash = {
                   11215:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11216:                                                        ':'.$env{'user.domain'},
                   11217:                    }; 
                   11218:     my $tries = 0;
                   11219:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11220:    
1.1172.2.79  raeburn  11221:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11222:         $tries ++;
1.1172.2.79  raeburn  11223:         sleep(0.1);
1.749     raeburn  11224:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11225:     }
                   11226:     if ($gotlock eq 'ok') {
                   11227:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11228:         my ($tmp)=keys(%curr_permissions);
                   11229:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11230:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11231:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11232:             if (ref($curr_controls) eq 'HASH') {
                   11233:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11234:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11235:                     if (defined($todelete{$itemnum})) {
                   11236:                         push(@deletions,$file_name."\0".$control_item);
                   11237:                     } else {
                   11238:                         if (defined($changed_items{$itemnum})) {
                   11239:                             $new_control{$changed_items{$itemnum}} = $now;
                   11240:                             push(@deletions,$file_name."\0".$control_item);
                   11241:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11242:                         } else {
                   11243:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11244:                         }
                   11245:                     }
1.745     raeburn  11246:                 }
                   11247:             }
                   11248:         }
1.970     raeburn  11249:         my ($group);
                   11250:         if (&is_course($domain,$user)) {
                   11251:             ($group,my $file) = split(/\//,$file_name,2);
                   11252:         }
1.749     raeburn  11253:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11254:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11255:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11256:         #  remove lock
                   11257:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11258:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11259:         my $sqlresult =
1.970     raeburn  11260:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11261:                                     $group);
1.749     raeburn  11262:     } else {
                   11263:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11264:     }
1.749     raeburn  11265:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11266: }
                   11267: 
1.827     raeburn  11268: sub make_public_indefinitely {
                   11269:     my ($requrl) = @_;
                   11270:     my $now = time;
                   11271:     my $action = 'activate';
                   11272:     my $aclnum = 0;
                   11273:     if (&is_portfolio_url($requrl)) {
                   11274:         my (undef,$udom,$unum,$file_name,$group) =
                   11275:             &parse_portfolio_url($requrl);
                   11276:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11277:         my %access_controls = &get_access_controls($current_perms,
                   11278:                                                    $group,$file_name);
                   11279:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11280:             my ($num,$scope,$end,$start) = 
                   11281:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11282:             if ($scope eq 'public') {
                   11283:                 if ($start <= $now && $end == 0) {
                   11284:                     $action = 'none';
                   11285:                 } else {
                   11286:                     $action = 'update';
                   11287:                     $aclnum = $num;
                   11288:                 }
                   11289:                 last;
                   11290:             }
                   11291:         }
                   11292:         if ($action eq 'none') {
                   11293:              return 'ok';
                   11294:         } else {
                   11295:             my %changes;
                   11296:             my $newend = 0;
                   11297:             my $newstart = $now;
                   11298:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11299:             $changes{$action}{$newkey} = {
                   11300:                 type => 'public',
                   11301:                 time => {
                   11302:                     start => $newstart,
                   11303:                     end   => $newend,
                   11304:                 },
                   11305:             };
                   11306:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11307:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11308:             return $outcome;
                   11309:         }
                   11310:     } else {
                   11311:         return 'invalid';
                   11312:     }
                   11313: }
                   11314: 
1.745     raeburn  11315: #------------------------------------------------------Get Marked as Read Only
                   11316: 
                   11317: sub get_marked_as_readonly {
                   11318:     my ($domain,$user,$what,$group) = @_;
                   11319:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11320:     my @readonly_files;
1.629     banghart 11321:     my $cmp1=$what;
                   11322:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11323:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11324:         if (defined($group)) {
                   11325:             if ($file_name !~ m-^\Q$group\E/-) {
                   11326:                 next;
                   11327:             }
                   11328:         }
1.561     banghart 11329:         if (ref($value) eq "ARRAY"){
                   11330:             foreach my $stored_what (@{$value}) {
1.629     banghart 11331:                 my $cmp2=$stored_what;
1.759     albertel 11332:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11333:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11334:                 }
1.629     banghart 11335:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11336:                     push(@readonly_files, $file_name);
1.745     raeburn  11337:                     last;
1.563     banghart 11338:                 } elsif (!defined($what)) {
                   11339:                     push(@readonly_files, $file_name);
1.745     raeburn  11340:                     last;
1.561     banghart 11341:                 }
                   11342:             }
1.745     raeburn  11343:         }
1.561     banghart 11344:     }
                   11345:     return @readonly_files;
                   11346: }
1.577     banghart 11347: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11348: 
1.577     banghart 11349: sub get_marked_as_readonly_hash {
1.745     raeburn  11350:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11351:     my %readonly_files;
1.745     raeburn  11352:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11353:         if (defined($group)) {
                   11354:             if ($file_name !~ m-^\Q$group\E/-) {
                   11355:                 next;
                   11356:             }
                   11357:         }
1.577     banghart 11358:         if (ref($value) eq "ARRAY"){
                   11359:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11360:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11361:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11362:                         if ($lock_descriptor eq 'graded') {
                   11363:                             $readonly_files{$file_name} = 'graded';
                   11364:                         } elsif ($lock_descriptor eq 'handback') {
                   11365:                             $readonly_files{$file_name} = 'handback';
                   11366:                         } else {
                   11367:                             if (!exists($readonly_files{$file_name})) {
                   11368:                                 $readonly_files{$file_name} = 'locked';
                   11369:                             }
                   11370:                         }
1.745     raeburn  11371:                     }
1.750     banghart 11372:                 } 
1.577     banghart 11373:             }
                   11374:         } 
                   11375:     }
                   11376:     return %readonly_files;
                   11377: }
1.559     banghart 11378: # ------------------------------------------------------------ Unmark as Read Only
                   11379: 
                   11380: sub unmark_as_readonly {
1.629     banghart 11381:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11382:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11383:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11384:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11385:     my $symb_crs = $what;
                   11386:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11387:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11388:     my ($tmp)=keys(%current_permissions);
                   11389:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11390:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11391:     foreach my $file (@readonly_files) {
1.759     albertel 11392: 	my $clean_file = &declutter_portfile($file);
                   11393: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11394: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11395:         my @new_locks;
                   11396:         my @del_keys;
                   11397:         if (ref($current_locks) eq "ARRAY"){
                   11398:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11399:                 my $compare=$locker;
1.749     raeburn  11400:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11401:                     $compare=join('',@{$locker});
1.746     raeburn  11402:                     if ($compare ne $symb_crs) {
                   11403:                         push(@new_locks, $locker);
                   11404:                     }
1.563     banghart 11405:                 }
                   11406:             }
1.650     albertel 11407:             if (scalar(@new_locks) > 0) {
1.563     banghart 11408:                 $current_permissions{$file} = \@new_locks;
                   11409:             } else {
                   11410:                 push(@del_keys, $file);
1.613     albertel 11411:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11412:                 delete($current_permissions{$file});
1.563     banghart 11413:             }
                   11414:         }
1.561     banghart 11415:     }
1.613     albertel 11416:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11417:     return;
                   11418: }
1.512     banghart 11419: 
1.17      www      11420: # ------------------------------------------------------------ Directory lister
                   11421: 
                   11422: sub dirlist {
1.955     raeburn  11423:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11424:     $uri=~s/^\///;
                   11425:     $uri=~s/\/$//;
1.253     stredwic 11426:     my ($udom, $uname);
1.955     raeburn  11427:     if ($getuserdir) {
1.253     stredwic 11428:         $udom = $userdomain;
                   11429:         $uname = $username;
1.955     raeburn  11430:     } else {
                   11431:         (undef,$udom,$uname)=split(/\//,$uri);
                   11432:         if(defined($userdomain)) {
                   11433:             $udom = $userdomain;
                   11434:         }
                   11435:         if(defined($username)) {
                   11436:             $uname = $username;
                   11437:         }
1.253     stredwic 11438:     }
1.955     raeburn  11439:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11440: 
1.955     raeburn  11441:     $dirRoot = $perlvar{'lonDocRoot'};
                   11442:     if (defined($getpropath)) {
                   11443:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11444:         $dirRoot =~ s/\/$//;
1.955     raeburn  11445:     } elsif (defined($getuserdir)) {
                   11446:         my $subdir=$uname.'__';
                   11447:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11448:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11449:                    ."/$udom/$subdir/$uname";
                   11450:     } elsif (defined($alternateRoot)) {
                   11451:         $dirRoot = $alternateRoot;
1.751     banghart 11452:     }
1.253     stredwic 11453: 
                   11454:     if($udom) {
                   11455:         if($uname) {
1.1135    raeburn  11456:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11457:             if ($uhome eq 'no_host') {
                   11458:                 return ([],'no_host');
                   11459:             }
1.955     raeburn  11460:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11461:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11462:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11463:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11464:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11465:             } else {
                   11466:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11467:             }
1.605     matthew  11468:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11469:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11470:                 @listing_results = split(/:/,$listing);
                   11471:             } else {
                   11472:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11473:             }
1.1135    raeburn  11474:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11475:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11476:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11477:                 return ([],$listing);
                   11478:             } else {
                   11479:                 return (\@listing_results);
1.1135    raeburn  11480:             }
1.955     raeburn  11481:         } elsif(!$alternateRoot) {
1.1136    raeburn  11482:             my (%allusers,%listerror);
1.841     albertel 11483: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11484:  	    foreach my $tryserver (keys(%servers)) {
                   11485:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11486:                                   &escape($udom),$tryserver);
                   11487:                 if ($listing eq 'unknown_cmd') {
                   11488: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11489: 				      $udom, $tryserver);
                   11490:                 } else {
                   11491:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11492:                 }
1.841     albertel 11493: 		if ($listing eq 'unknown_cmd') {
                   11494: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11495: 				      $udom, $tryserver);
                   11496: 		    @listing_results = split(/:/,$listing);
                   11497: 		} else {
                   11498: 		    @listing_results =
                   11499: 			map { &unescape($_); } split(/:/,$listing);
                   11500: 		}
1.1136    raeburn  11501:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11502:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11503:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11504:                     $listerror{$tryserver} = $listing;
                   11505:                 } else {
1.841     albertel 11506: 		    foreach my $line (@listing_results) {
                   11507: 			my ($entry) = split(/&/,$line,2);
                   11508: 			$allusers{$entry} = 1;
                   11509: 		    }
                   11510: 		}
1.253     stredwic 11511:             }
1.1136    raeburn  11512:             my @alluserslist=();
1.800     albertel 11513:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11514:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11515:             }
1.1172.2.80  raeburn  11516:             if (!%listerror) {
                   11517:                 # no errors
                   11518:                 return (\@alluserslist);
                   11519:             } elsif (scalar(keys(%servers)) == 1) {
                   11520:                 # one library server, one error
                   11521:                 my ($key) = keys(%listerror);
                   11522:                 return (\@alluserslist, $listerror{$key});
                   11523:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11524:                 # con_lost indicates that we might miss data from at least one
                   11525:                 # library server
                   11526:                 return (\@alluserslist, 'con_lost');
                   11527:             } else {
                   11528:                 # multiple library servers and no con_lost -> data should be
                   11529:                 # complete.
                   11530:                 return (\@alluserslist);
                   11531:             }
                   11532: 
1.253     stredwic 11533:         } else {
1.1136    raeburn  11534:             return ([],'missing username');
1.253     stredwic 11535:         }
1.955     raeburn  11536:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11537:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11538:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11539:         return (\@all_domains);
1.955     raeburn  11540:     } else {
1.1136    raeburn  11541:         return ([],'missing domain');
1.275     stredwic 11542:     }
                   11543: }
                   11544: 
                   11545: # --------------------------------------------- GetFileTimestamp
                   11546: # This function utilizes dirlist and returns the date stamp for
                   11547: # when it was last modified.  It will also return an error of -1
                   11548: # if an error occurs
                   11549: 
                   11550: sub GetFileTimestamp {
1.955     raeburn  11551:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11552:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11553:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11554:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11555:                                     undef,$getuserdir);
                   11556:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11557:         return -1;
                   11558:     }
                   11559:     if (ref($fileref) eq 'ARRAY') {
                   11560:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11561:         # @stats contains first the filename, then the stat output
                   11562:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11563:     } else {
                   11564:         return -1;
1.253     stredwic 11565:     }
1.26      www      11566: }
                   11567: 
1.712     albertel 11568: sub stat_file {
                   11569:     my ($uri) = @_;
1.787     albertel 11570:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11571: 
1.955     raeburn  11572:     my ($udom,$uname,$file);
1.712     albertel 11573:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11574: 	($udom,$uname,$file) =
1.811     albertel 11575: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11576: 	$file = 'userfiles/'.$file;
                   11577:     }
                   11578:     if ($uri =~ m-^/res/-) {
                   11579: 	($udom,$uname) = 
1.807     albertel 11580: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11581: 	$file = $uri;
                   11582:     }
                   11583: 
                   11584:     if (!$udom || !$uname || !$file) {
                   11585: 	# unable to handle the uri
                   11586: 	return ();
                   11587:     }
1.956     raeburn  11588:     my $getpropath;
                   11589:     if ($file =~ /^userfiles\//) {
                   11590:         $getpropath = 1;
                   11591:     }
1.1136    raeburn  11592:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11593:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11594:         return ();
                   11595:     } else {
                   11596:         if (ref($listref) eq 'ARRAY') {
                   11597:             my @stats = split('&',$listref->[0]);
                   11598: 	    shift(@stats); #filename is first
                   11599: 	    return @stats;
                   11600:         }
1.712     albertel 11601:     }
                   11602:     return ();
                   11603: }
                   11604: 
1.26      www      11605: # -------------------------------------------------------- Value of a Condition
                   11606: 
1.713     albertel 11607: # gets the value of a specific preevaluated condition
                   11608: #    stored in the string  $env{user.state.<cid>}
                   11609: # or looks up a condition reference in the bighash and if if hasn't
                   11610: # already been evaluated recurses into docondval to get the value of
                   11611: # the condition, then memoizing it to 
                   11612: #   $env{user.state.<cid>.<condition>}
1.40      www      11613: sub directcondval {
                   11614:     my $number=shift;
1.620     albertel 11615:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11616: 	&Apache::lonuserstate::evalstate();
                   11617:     }
1.713     albertel 11618:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11619: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11620:     } elsif ($number =~ /^_/) {
                   11621: 	my $sub_condition;
                   11622: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11623: 		&GDBM_READER(),0640)) {
                   11624: 	    $sub_condition=$bighash{'conditions'.$number};
                   11625: 	    untie(%bighash);
                   11626: 	}
                   11627: 	my $value = &docondval($sub_condition);
1.949     raeburn  11628: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11629: 	return $value;
                   11630:     }
1.620     albertel 11631:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11632:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11633:     } else {
                   11634:        return 2;
                   11635:     }
                   11636: }
                   11637: 
1.713     albertel 11638: # get the collection of conditions for this resource
1.26      www      11639: sub condval {
                   11640:     my $condidx=shift;
1.54      www      11641:     my $allpathcond='';
1.713     albertel 11642:     foreach my $cond (split(/\|/,$condidx)) {
                   11643: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11644: 	    $allpathcond.=
                   11645: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11646: 	}
1.191     harris41 11647:     }
1.54      www      11648:     $allpathcond=~s/\|$//;
1.713     albertel 11649:     return &docondval($allpathcond);
                   11650: }
                   11651: 
                   11652: #evaluates an expression of conditions
                   11653: sub docondval {
                   11654:     my ($allpathcond) = @_;
                   11655:     my $result=0;
                   11656:     if ($env{'request.course.id'}
                   11657: 	&& defined($allpathcond)) {
                   11658: 	my $operand='|';
                   11659: 	my @stack;
                   11660: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11661: 	    if ($chunk eq '(') {
                   11662: 		push @stack,($operand,$result);
                   11663: 	    } elsif ($chunk eq ')') {
                   11664: 		my $before=pop @stack;
                   11665: 		if (pop @stack eq '&') {
                   11666: 		    $result=$result>$before?$before:$result;
                   11667: 		} else {
                   11668: 		    $result=$result>$before?$result:$before;
                   11669: 		}
                   11670: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11671: 		$operand=$chunk;
                   11672: 	    } else {
                   11673: 		my $new=directcondval($chunk);
                   11674: 		if ($operand eq '&') {
                   11675: 		    $result=$result>$new?$new:$result;
                   11676: 		} else {
                   11677: 		    $result=$result>$new?$result:$new;
                   11678: 		}
                   11679: 	    }
                   11680: 	}
1.26      www      11681:     }
                   11682:     return $result;
1.421     albertel 11683: }
                   11684: 
                   11685: # ---------------------------------------------------- Devalidate courseresdata
                   11686: 
                   11687: sub devalidatecourseresdata {
                   11688:     my ($coursenum,$coursedomain)=@_;
                   11689:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11690:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11691: }
                   11692: 
1.763     www      11693: 
1.200     www      11694: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11695: #
                   11696: #  Parameters:
                   11697: #      $coursenum    - Number of the course.
                   11698: #      $coursedomain - Domain at which the course was created.
                   11699: #  Returns:
                   11700: #     A hash of the course parameters along (I think) with timestamps
                   11701: #     and version info.
1.877     foxr     11702: 
1.624     albertel 11703: sub get_courseresdata {
                   11704:     my ($coursenum,$coursedomain)=@_;
1.200     www      11705:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11706:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11707:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11708:     my %dumpreply;
1.417     albertel 11709:     unless (defined($cached)) {
1.624     albertel 11710: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11711: 	$result=\%dumpreply;
1.251     albertel 11712: 	my ($tmp) = keys(%dumpreply);
                   11713: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11714: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11715: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11716: 	    return $tmp;
1.416     albertel 11717: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11718: 	    $result=undef;
1.599     albertel 11719: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11720: 	}
                   11721:     }
1.624     albertel 11722:     return $result;
                   11723: }
                   11724: 
1.633     albertel 11725: sub devalidateuserresdata {
                   11726:     my ($uname,$udom)=@_;
                   11727:     my $hashid="$udom:$uname";
                   11728:     &devalidate_cache_new('userres',$hashid);
                   11729: }
                   11730: 
1.624     albertel 11731: sub get_userresdata {
                   11732:     my ($uname,$udom)=@_;
                   11733:     #most student don\'t have any data set, check if there is some data
                   11734:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11735: 
                   11736:     my $hashid="$udom:$uname";
                   11737:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11738:     if (!defined($cached)) {
                   11739: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11740: 	$result=\%resourcedata;
                   11741: 	&do_cache_new('userres',$hashid,$result,600);
                   11742:     }
                   11743:     my ($tmp)=keys(%$result);
                   11744:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11745: 	return $result;
                   11746:     }
                   11747:     #error 2 occurs when the .db doesn't exist
                   11748:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11749:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11750: 	    &logthis("<font color=\"blue\">WARNING:".
                   11751: 		     " Trying to get resource data for ".
                   11752: 		     $uname." at ".$udom.": ".
                   11753: 		     $tmp."</font>");
                   11754:         }
1.624     albertel 11755:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11756: 	#&EXT_cache_set($udom,$uname);
                   11757: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11758: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11759:     }
                   11760:     return $tmp;
                   11761: }
1.879     foxr     11762: #----------------------------------------------- resdata - return resource data
                   11763: #  Purpose:
                   11764: #    Return resource data for either users or for a course.
                   11765: #  Parameters:
                   11766: #     $name      - Course/user name.
                   11767: #     $domain    - Name of the domain the user/course is registered on.
                   11768: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11769: #     @which     - Array of names of resources desired.
                   11770: #  Returns:
                   11771: #     The value of the first reasource in @which that is found in the
                   11772: #     resource hash.
                   11773: #  Exceptional Conditions:
                   11774: #     If the $type passed in is not valid (not the string 'course' or 
                   11775: #     'user', an undefined  reference is returned.
                   11776: #     If none of the resources are found, an undef is returned
1.624     albertel 11777: sub resdata {
                   11778:     my ($name,$domain,$type,@which)=@_;
                   11779:     my $result;
                   11780:     if ($type eq 'course') {
                   11781: 	$result=&get_courseresdata($name,$domain);
                   11782:     } elsif ($type eq 'user') {
                   11783: 	$result=&get_userresdata($name,$domain);
                   11784:     }
                   11785:     if (!ref($result)) { return $result; }    
1.251     albertel 11786:     foreach my $item (@which) {
1.927     albertel 11787: 	if (defined($result->{$item->[0]})) {
                   11788: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11789: 	}
1.250     albertel 11790:     }
1.291     albertel 11791:     return undef;
1.200     www      11792: }
                   11793: 
1.1172.2.146.  .1(raebu 11794:22): sub get_domain_lti {
                   11795:22):     my ($cdom,$context) = @_;
          .4(raebu 11796:22):     my ($name,$cachename,%lti);
          .1(raebu 11797:22):     if ($context eq 'consumer') {
                   11798:22):         $name = 'ltitools';
                   11799:22):     } elsif ($context eq 'provider') {
                   11800:22):         $name = 'lti';
          .4(raebu 11801:22):     } elsif ($context eq 'linkprot') {
                   11802:22):         $name = 'ltisec';
          .1(raebu 11803:22):     } else {
                   11804:22):         return %lti;
                   11805:22):     }
          .4(raebu 11806:22): 
                   11807:22):     if ($context eq 'linkprot') {
                   11808:22):         $cachename = $context;
                   11809:22):     } else {
                   11810:22):         $cachename = $name;
                   11811:22):     }
                   11812:22): 
                   11813:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11814:22):     if (defined($cached)) {
                   11815:22):         if (ref($result) eq 'HASH') {
                   11816:22):             %lti = %{$result};
                   11817:22):         }
                   11818:22):     } else {
                   11819:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11820:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11821:22):             if ($context eq 'linkprot') {
                   11822:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11823:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11824:22):                 }
                   11825:22):             } else {
                   11826:22):                 %lti = %{$domconfig{$name}};
                   11827:22):             }
                   11828:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11829:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11830:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11831:22):                     foreach my $id (keys(%lti)) {
                   11832:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11833:22):                             foreach my $item ('key','secret') {
                   11834:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11835:22):                             }
          .1(raebu 11836:22):                         }
                   11837:22):                     }
                   11838:22):                 }
                   11839:22):             }
                   11840:22):         }
                   11841:22):         my $cachetime = 24*60*60;
          .4(raebu 11842:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11843:22):     }
                   11844:22):     return %lti;
                   11845:22): }
                   11846:22): 
                   11847:22): sub get_course_lti {
                   11848:22):     my ($cnum,$cdom) = @_;
                   11849:22):     my $hashid=$cdom.'_'.$cnum;
                   11850:22):     my %courselti;
                   11851:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11852:22):     if (defined($cached)) {
                   11853:22):         if (ref($result) eq 'HASH') {
                   11854:22):             %courselti = %{$result};
                   11855:22):         }
                   11856:22):     } else {
                   11857:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11858:22):         my $cachetime = 24*60*60;
                   11859:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11860:22):     }
                   11861:22):     return %courselti;
                   11862:22): }
                   11863:22): 
          .3(raebu 11864:22): sub courselti_itemid {
                   11865:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11866:22):     my ($chome,$itemid);
                   11867:22):     $chome = &homeserver($cnum,$cdom);
                   11868:22):     return if ($chome eq 'no_host');
                   11869:22):     if (ref($params) eq 'HASH') {
                   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 $rep;
                   11894:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11895:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11896:22):         } else {
                   11897:22):             my $cnum = '';
                   11898:22):             my $escurl = &escape($url);
                   11899:22):             my $escmethod = &escape($method);
                   11900:22):             my $items = &freeze_escape($params);
                   11901:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11902:22):         }
                   11903:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11904:22):                 ($rep eq 'unknown_cmd')) {
                   11905:22):             $itemid = $rep;
                   11906:22):         }
                   11907:22):     }
                   11908:22):     return $itemid;
                   11909:22): }
                   11910:22): 
          .9(raebu 11911:23): sub count_supptools {
                   11912:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  11913:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 11914:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  11915:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 11916:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  11917:     }
                   11918:     unless (defined($cached)) {
                   11919:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 11920:23):         $numexttools = 0;
1.1172.2.31  raeburn  11921:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 11922:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   11923:23):             if (ref($supplemental) eq 'HASH') {
                   11924:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11925:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11926:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   11927:23):                             $numexttools ++;
                   11928:23):                         }
                   11929:23):                     }
                   11930:23):                 }
                   11931:23):             }
1.1172.2.31  raeburn  11932:         }
1.1172.2.146.  .9(raebu 11933:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  11934:     }
1.1172.2.146.  .9(raebu 11935:23):     return $numexttools;
                   11936:23): }
                   11937:23): 
                   11938:23): sub has_unhidden_suppfiles {
                   11939:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   11940:23):     my $hashid=$cnum.':'.$cdom;
                   11941:23):     my ($showsupp,$cached);
                   11942:23):     unless ($ignorecache) {
                   11943:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   11944:23):     }
                   11945:23):     unless (defined($cached)) {
                   11946:23):         my $chome=&homeserver($cnum,$cdom);
                   11947:23):         unless ($chome eq 'no_host') {
                   11948:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   11949:23):             if (ref($supplemental) eq 'HASH') {
                   11950:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11951:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11952:23):                         next if ($key =~ /\.sequence$/);
                   11953:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   11954:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   11955:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   11956:23):                                     $showsupp = 1;
                   11957:23):                                     last;
                   11958:23):                                 }
                   11959:23):                             }
                   11960:23):                         }
                   11961:23):                         last if ($showsupp);
                   11962:23):                     }
                   11963:23):                 }
                   11964:23):             }
                   11965:23):         }
                   11966:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   11967:23):     }
                   11968:23):     return $showsupp;
1.1172.2.31  raeburn  11969: }
                   11970: 
1.379     matthew  11971: #
                   11972: # EXT resource caching routines
                   11973: #
                   11974: 
1.1172.2.146.  .1(raebu 11975:22): {
                   11976:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11977:22): #
                   11978:22): # The course for which we cache
                   11979:22): my $cachedmapkey='';
                   11980:22): # The cached recursive maps for this course
                   11981:22): my %cachedmaps=();
                   11982:22): # When this was last done
                   11983:22): my $cachedmaptime='';
                   11984:22): 
1.379     matthew  11985: sub clear_EXT_cache_status {
1.383     albertel 11986:     &delenv('cache.EXT.');
1.379     matthew  11987: }
                   11988: 
                   11989: sub EXT_cache_status {
                   11990:     my ($target_domain,$target_user) = @_;
1.383     albertel 11991:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11992:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11993:         # We know already the user has no data
                   11994:         return 1;
                   11995:     } else {
                   11996:         return 0;
                   11997:     }
                   11998: }
                   11999: 
                   12000: sub EXT_cache_set {
                   12001:     my ($target_domain,$target_user) = @_;
1.383     albertel 12002:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12003:     #&appenv({$cachename => time});
1.379     matthew  12004: }
                   12005: 
1.28      www      12006: # --------------------------------------------------------- Value of a Variable
1.58      www      12007: sub EXT {
1.715     albertel 12008: 
1.1172.2.28  raeburn  12009:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12010:     unless ($varname) { return ''; }
1.218     albertel 12011:     #get real user name/domain, courseid and symb
                   12012:     my $courseid;
1.359     albertel 12013:     my $publicuser;
1.427     www      12014:     if ($symbparm) {
                   12015: 	$symbparm=&get_symb_from_alias($symbparm);
                   12016:     }
1.218     albertel 12017:     if (!($uname && $udom)) {
1.790     albertel 12018:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12019:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12020:     } else {
1.620     albertel 12021: 	$courseid=$env{'request.course.id'};
1.218     albertel 12022:     }
1.48      www      12023:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12024:     my $rest;
1.320     albertel 12025:     if (defined($therest[0])) {
1.48      www      12026:        $rest=join('.',@therest);
                   12027:     } else {
                   12028:        $rest='';
                   12029:     }
1.320     albertel 12030: 
1.57      www      12031:     my $qualifierrest=$qualifier;
                   12032:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12033:     my $spacequalifierrest=$space;
                   12034:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12035:     if ($realm eq 'user') {
1.48      www      12036: # --------------------------------------------------------------- user.resource
                   12037: 	if ($space eq 'resource') {
1.651     albertel 12038: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12039: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12040: 		 &&
1.1172.2.142  raeburn  12041: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12042: 		# if we are in the middle of processing the resource the
                   12043: 		# get the value we are planning on committing
                   12044:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12045:                     return $Apache::lonhomework::results{$qualifierrest};
                   12046:                 } else {
                   12047:                     return $Apache::lonhomework::history{$qualifierrest};
                   12048:                 }
1.335     albertel 12049: 	    } else {
1.359     albertel 12050: 		my %restored;
1.620     albertel 12051: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12052: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12053: 		} else {
                   12054: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12055: 		}
1.335     albertel 12056: 		return $restored{$qualifierrest};
                   12057: 	    }
1.48      www      12058: # ----------------------------------------------------------------- user.access
                   12059:         } elsif ($space eq 'access') {
1.218     albertel 12060: 	    # FIXME - not supporting calls for a specific user
1.48      www      12061:             return &allowed($qualifier,$rest);
                   12062: # ------------------------------------------ user.preferences, user.environment
                   12063:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12064: 	    if (($uname eq $env{'user.name'}) &&
                   12065: 		($udom eq $env{'user.domain'})) {
                   12066: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12067: 	    } else {
1.359     albertel 12068: 		my %returnhash;
                   12069: 		if (!$publicuser) {
                   12070: 		    %returnhash=&userenvironment($udom,$uname,
                   12071: 						 $qualifierrest);
                   12072: 		}
1.218     albertel 12073: 		return $returnhash{$qualifierrest};
                   12074: 	    }
1.48      www      12075: # ----------------------------------------------------------------- user.course
                   12076:         } elsif ($space eq 'course') {
1.218     albertel 12077: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12078:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12079: # ------------------------------------------------------------------- user.role
                   12080:         } elsif ($space eq 'role') {
1.218     albertel 12081: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12082:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12083:             if ($qualifier eq 'value') {
                   12084: 		return $role;
                   12085:             } elsif ($qualifier eq 'extent') {
                   12086:                 return $where;
                   12087:             }
                   12088: # ----------------------------------------------------------------- user.domain
                   12089:         } elsif ($space eq 'domain') {
1.218     albertel 12090:             return $udom;
1.48      www      12091: # ------------------------------------------------------------------- user.name
                   12092:         } elsif ($space eq 'name') {
1.218     albertel 12093:             return $uname;
1.48      www      12094: # ---------------------------------------------------- Any other user namespace
1.29      www      12095:         } else {
1.359     albertel 12096: 	    my %reply;
                   12097: 	    if (!$publicuser) {
                   12098: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12099: 	    }
                   12100: 	    return $reply{$qualifierrest};
1.48      www      12101:         }
1.236     www      12102:     } elsif ($realm eq 'query') {
                   12103: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12104:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12105: 						[$spacequalifierrest]);
1.620     albertel 12106: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12107:    } elsif ($realm eq 'request') {
1.48      www      12108: # ------------------------------------------------------------- request.browser
                   12109:         if ($space eq 'browser') {
1.1145    bisitz   12110:             return $env{'browser.'.$qualifier};
1.57      www      12111: # ------------------------------------------------------------ request.filename
                   12112:         } else {
1.620     albertel 12113:             return $env{'request.'.$spacequalifierrest};
1.29      www      12114:         }
1.28      www      12115:     } elsif ($realm eq 'course') {
1.48      www      12116: # ---------------------------------------------------------- course.description
1.620     albertel 12117:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12118:     } elsif ($realm eq 'resource') {
1.165     www      12119: 
1.620     albertel 12120: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12121: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12122: 	}
1.693     albertel 12123: 
1.1172.2.30  raeburn  12124:         if ($qualifier eq '') {
                   12125: 	    if ($space eq 'title') {
                   12126: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12127: 	        return &gettitle($symbparm);
                   12128: 	    }
1.693     albertel 12129: 	
1.1172.2.30  raeburn  12130: 	    if ($space eq 'map') {
                   12131: 	        my ($map) = &decode_symb($symbparm);
                   12132: 	        return &symbread($map);
                   12133: 	    }
                   12134:             if ($space eq 'maptitle') {
                   12135:                 my ($map) = &decode_symb($symbparm);
                   12136:                 return &gettitle($map);
                   12137:             }
                   12138: 	    if ($space eq 'filename') {
                   12139: 	        if ($symbparm) {
                   12140: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12141: 	        }
                   12142: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12143: 	    }
1.1172.2.30  raeburn  12144: 
                   12145:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12146:                 if ($space eq 'visibleparts') {
                   12147:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12148:                     my $item;
                   12149:                     if (ref($navmap)) {
                   12150:                         my $res = $navmap->getBySymb($symbparm);
                   12151:                         my $parts = $res->parts();
                   12152:                         if (ref($parts) eq 'ARRAY') {
                   12153:                             $item = join(',',@{$parts});
                   12154:                         }
                   12155:                         undef($navmap);
                   12156:                     }
                   12157:                     return $item;
                   12158:                 }
                   12159:             }
                   12160:         }
1.693     albertel 12161: 
                   12162: 	my ($section, $group, @groups);
1.593     albertel 12163: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12164:         if (($courseid eq '') && ($cid)) {
                   12165:             $courseid = $cid;
                   12166:         }
                   12167: 	if (($symbparm && $courseid) && 
                   12168: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12169: 
1.218     albertel 12170: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12171: 
1.60      www      12172: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12173: 	    my $symbp=$symbparm;
1.735     albertel 12174: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12175: 
                   12176: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12177: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12178: 
1.620     albertel 12179: 	    if (($env{'user.name'} eq $uname) &&
                   12180: 		($env{'user.domain'} eq $udom)) {
                   12181: 		$section=$env{'request.course.sec'};
1.733     raeburn  12182:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12183:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12184: 	    } else {
1.539     albertel 12185: 		if (! defined($usection)) {
1.551     albertel 12186: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12187: 		} else {
                   12188: 		    $section = $usection;
                   12189: 		}
1.733     raeburn  12190:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12191: 	    }
                   12192: 
                   12193: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12194: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12195: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12196: 
1.593     albertel 12197: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12198: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12199: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12200: 
1.60      www      12201: # ----------------------------------------------------------- first, check user
1.624     albertel 12202: 
                   12203: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12204: 				       ([$courselevelr,'resource'],
                   12205: 					[$courselevelm,'map'     ],
                   12206: 					[$courselevel, 'course'  ]));
1.931     albertel 12207: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12208: 
1.594     albertel 12209: # ------------------------------------------------ second, check some of course
1.684     raeburn  12210:             my $coursereply;
1.691     raeburn  12211:             if (@groups > 0) {
                   12212:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12213:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12214:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12215:             }
1.96      www      12216: 
1.684     raeburn  12217: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12218: 				  $env{'course.'.$courseid.'.domain'},
                   12219: 				  'course',
                   12220: 				  ([$seclevelr,   'resource'],
                   12221: 				   [$seclevelm,   'map'     ],
                   12222: 				   [$seclevel,    'course'  ],
                   12223: 				   [$courselevelr,'resource']));
                   12224: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12225: 
1.60      www      12226: # ------------------------------------------------------ third, check map parms
1.218     albertel 12227: 	    my %parmhash=();
                   12228: 	    my $thisparm='';
                   12229: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12230: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12231: 		    &GDBM_READER(),0640)) {
1.218     albertel 12232: 		$thisparm=$parmhash{$symbparm};
                   12233: 		untie(%parmhash);
                   12234: 	    }
1.927     albertel 12235: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12236: 	}
1.594     albertel 12237: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12238: 
1.218     albertel 12239: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12240: 	my $filename;
                   12241: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12242: 	if ($symbparm) {
1.409     www      12243: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12244: 	} else {
1.620     albertel 12245: 	    $filename=$env{'request.filename'};
1.282     albertel 12246: 	}
                   12247: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12248: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12249: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12250: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12251: 
1.927     albertel 12252: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12253: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12254: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12255: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12256: 				     $env{'course.'.$courseid.'.domain'},
                   12257: 				     'course',
1.927     albertel 12258: 				     ([$courselevelm,'map'   ],
                   12259: 				      [$courselevel, 'course']));
                   12260: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12261: 	}
1.145     www      12262: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12263: 	unless ($space eq '0') {
1.336     albertel 12264: 	    my @parts=split(/_/,$space);
                   12265: 	    my $id=pop(@parts);
                   12266: 	    my $part=join('_',@parts);
                   12267: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12268: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12269: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12270: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12271: 	}
1.395     albertel 12272: 	if ($recurse) { return undef; }
                   12273: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12274: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12275: # ---------------------------------------------------- Any other user namespace
                   12276:     } elsif ($realm eq 'environment') {
                   12277: # ----------------------------------------------------------------- environment
1.620     albertel 12278: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12279: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12280: 	} else {
1.770     albertel 12281: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12282: 		return '';
                   12283: 	    }
1.219     albertel 12284: 	    my %returnhash=&userenvironment($udom,$uname,
                   12285: 					    $spacequalifierrest);
                   12286: 	    return $returnhash{$spacequalifierrest};
                   12287: 	}
1.28      www      12288:     } elsif ($realm eq 'system') {
1.48      www      12289: # ----------------------------------------------------------------- system.time
                   12290: 	if ($space eq 'time') {
                   12291: 	    return time;
                   12292:         }
1.696     albertel 12293:     } elsif ($realm eq 'server') {
                   12294: # ----------------------------------------------------------------- system.time
                   12295: 	if ($space eq 'name') {
                   12296: 	    return $ENV{'SERVER_NAME'};
                   12297:         }
1.1172.2.146.  .1(raebu 12298:22):     } elsif ($realm eq 'client') {
                   12299:22):         if ($space eq 'remote_addr') {
                   12300:22):             return &get_requestor_ip();
                   12301:22):         }
1.28      www      12302:     }
1.48      www      12303:     return '';
1.61      www      12304: }
                   12305: 
1.927     albertel 12306: sub get_reply {
                   12307:     my ($reply_value) = @_;
1.940     raeburn  12308:     if (ref($reply_value) eq 'ARRAY') {
                   12309:         if (wantarray) {
                   12310: 	    return @$reply_value;
                   12311:         }
                   12312:         return $reply_value->[0];
                   12313:     } else {
                   12314:         return $reply_value;
1.927     albertel 12315:     }
                   12316: }
                   12317: 
1.691     raeburn  12318: sub check_group_parms {
                   12319:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12320:     my @groupitems = ();
                   12321:     my $resultitem;
1.927     albertel 12322:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12323:     foreach my $group (@{$groups}) {
                   12324:         foreach my $level (@levels) {
1.927     albertel 12325:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12326:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12327:         }
                   12328:     }
                   12329:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12330:                             $env{'course.'.$courseid.'.domain'},
                   12331:                                      'course',@groupitems);
                   12332:     return $coursereply;
                   12333: }
                   12334: 
1.1172.2.146.  .1(raebu 12335:22): sub get_map_hierarchy {
                   12336:22):     my ($mapname,$courseid) = @_;
                   12337:22):     my @recurseup = ();
                   12338:22):     if ($mapname) {
                   12339:22):         if (($cachedmapkey eq $courseid) &&
                   12340:22):             (abs($cachedmaptime-time)<5)) {
                   12341:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12342:22):                 return @{$cachedmaps{$mapname}};
                   12343:22):             }
                   12344:22):         }
                   12345:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12346:22):         if (ref($navmap)) {
                   12347:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12348:22):             undef($navmap);
                   12349:22):             $cachedmaps{$mapname} = \@recurseup;
                   12350:22):             $cachedmaptime=time;
                   12351:22):             $cachedmapkey=$courseid;
                   12352:22):         }
                   12353:22):     }
                   12354:22):     return @recurseup;
                   12355:22): }
                   12356:22): 
          .2(raebu 12357:22): }
          .1(raebu 12358:22): 
1.691     raeburn  12359: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12360:     my ($courseid,@groups) = @_;
                   12361:     @groups = sort(@groups);
1.691     raeburn  12362:     return @groups;
                   12363: }
                   12364: 
1.395     albertel 12365: sub packages_tab_default {
                   12366:     my ($uri,$varname)=@_;
                   12367:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12368: 
                   12369:     my (@extension,@specifics,$do_default);
                   12370:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12371: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12372: 	if ($pack_type eq 'default') {
                   12373: 	    $do_default=1;
                   12374: 	} elsif ($pack_type eq 'extension') {
                   12375: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12376: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12377: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12378: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12379: 	}
                   12380:     }
                   12381:     # first look for a package that matches the requested part id
                   12382:     foreach my $package (@specifics) {
                   12383: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12384: 	next if ($pack_part ne $part);
                   12385: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12386: 	    return $packagetab{"$pack_type&$name&default"};
                   12387: 	}
                   12388:     }
                   12389:     # look for any possible matching non extension_ package
                   12390:     foreach my $package (@specifics) {
                   12391: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12392: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12393: 	    return $packagetab{"$pack_type&$name&default"};
                   12394: 	}
1.585     albertel 12395: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12396: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12397: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12398: 	}
                   12399:     }
1.738     albertel 12400:     # look for any posible extension_ match
                   12401:     foreach my $package (@extension) {
                   12402: 	my ($package,$pack_type)=@{$package};
                   12403: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12404: 	    return $packagetab{"$pack_type&$name&default"};
                   12405: 	}
                   12406: 	if (defined($packagetab{$package."&$name&default"})) {
                   12407: 	    return $packagetab{$package."&$name&default"};
                   12408: 	}
                   12409:     }
                   12410:     # look for a global default setting
                   12411:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12412: 	return $packagetab{"default&$name&default"};
                   12413:     }
1.395     albertel 12414:     return undef;
                   12415: }
                   12416: 
1.334     albertel 12417: sub add_prefix_and_part {
                   12418:     my ($prefix,$part)=@_;
                   12419:     my $keyroot;
                   12420:     if (defined($prefix) && $prefix !~ /^__/) {
                   12421: 	# prefix that has a part already
                   12422: 	$keyroot=$prefix;
                   12423:     } elsif (defined($prefix)) {
                   12424: 	# prefix that is missing a part
                   12425: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12426:     } else {
                   12427: 	# no prefix at all
                   12428: 	if (defined($part)) { $keyroot='_'.$part; }
                   12429:     }
                   12430:     return $keyroot;
                   12431: }
                   12432: 
1.71      www      12433: # ---------------------------------------------------------------- Get metadata
                   12434: 
1.599     albertel 12435: my %metaentry;
1.1070    www      12436: my %importedpartids;
1.1172.2.99  raeburn  12437: my %importedrespids;
1.71      www      12438: sub metadata {
1.176     www      12439:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12440:     $uri=&declutter($uri);
1.288     albertel 12441:     # if it is a non metadata possible uri return quickly
1.529     albertel 12442:     if (($uri eq '') || 
                   12443: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12444:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12445:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12446: 	return undef;
                   12447:     }
1.1172.2.49  raeburn  12448:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12449: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12450: 	return undef;
1.288     albertel 12451:     }
1.73      www      12452:     my $filename=$uri;
                   12453:     $uri=~s/\.meta$//;
1.172     www      12454: #
                   12455: # Is the metadata already cached?
1.177     www      12456: # Look at timestamp of caching
1.172     www      12457: # Everything is cached by the main uri, libraries are never directly cached
                   12458: #
1.428     albertel 12459:     if (!defined($liburi)) {
1.599     albertel 12460: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12461: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12462:     }
                   12463:     {
1.1069    www      12464: # Imported parts would go here
1.1172.2.99  raeburn  12465:         my @origfiletagids=();
1.1069    www      12466:         my $importedparts=0;
1.1172.2.99  raeburn  12467: 
                   12468: # Imported responseids would go here
                   12469:         my $importedresponses=0;
1.172     www      12470: #
                   12471: # Is this a recursive call for a library?
                   12472: #
1.599     albertel 12473: #	if (! exists($metacache{$uri})) {
                   12474: #	    $metacache{$uri}={};
                   12475: #	}
1.924     albertel 12476: 	my $cachetime = 60*60;
1.171     www      12477:         if ($liburi) {
                   12478: 	    $liburi=&declutter($liburi);
                   12479:             $filename=$liburi;
1.401     bowersj2 12480:         } else {
1.599     albertel 12481: 	    &devalidate_cache_new('meta',$uri);
                   12482: 	    undef(%metaentry);
1.401     bowersj2 12483: 	}
1.140     www      12484:         my %metathesekeys=();
1.73      www      12485:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12486: 	my $metastring;
1.1140    www      12487: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12488: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12489: 	    $metastring = 
1.929     albertel 12490: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12491: 					  ('grade_target' => 'meta'));
                   12492: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12493: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12494:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12495: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12496: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12497: 	    $metastring=&getfile($file);
1.489     albertel 12498: 	}
1.208     albertel 12499:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12500:         my $token;
1.140     www      12501:         undef %metathesekeys;
1.71      www      12502:         while ($token=$parser->get_token) {
1.339     albertel 12503: 	    if ($token->[0] eq 'S') {
                   12504: 		if (defined($token->[2]->{'package'})) {
1.172     www      12505: #
                   12506: # This is a package - get package info
                   12507: #
1.339     albertel 12508: 		    my $package=$token->[2]->{'package'};
                   12509: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12510: 		    if (defined($token->[2]->{'id'})) { 
                   12511: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12512: 		    }
1.599     albertel 12513: 		    if ($metaentry{':packages'}) {
                   12514: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12515: 		    } else {
1.599     albertel 12516: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12517: 		    }
1.736     albertel 12518: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12519: 			my $part=$keyroot;
                   12520: 			$part=~s/^\_//;
1.736     albertel 12521: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12522: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12523: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12524: 			    # ignore package.tab specified default values
                   12525:                             # here &package_tab_default() will fetch those
                   12526: 			    if ($subp eq 'default') { next; }
1.736     albertel 12527: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12528: 			    my $unikey;
                   12529: 			    if ($pack =~ /_0$/) {
                   12530: 				$unikey='parameter_0_'.$name;
                   12531: 				$part=0;
                   12532: 			    } else {
                   12533: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12534: 			    }
1.339     albertel 12535: 			    if ($subp eq 'display') {
                   12536: 				$value.=' [Part: '.$part.']';
                   12537: 			    }
1.599     albertel 12538: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12539: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12540: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12541: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12542: 			    }
1.599     albertel 12543: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12544: 				$metaentry{':'.$unikey}=
                   12545: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12546: 			    }
1.339     albertel 12547: 			}
                   12548: 		    }
                   12549: 		} else {
1.172     www      12550: #
                   12551: # This is not a package - some other kind of start tag
1.339     albertel 12552: #
                   12553: 		    my $entry=$token->[1];
1.1068    www      12554: 		    my $unikey='';
1.175     www      12555: 
1.339     albertel 12556: 		    if ($entry eq 'import') {
1.175     www      12557: #
                   12558: # Importing a library here
1.339     albertel 12559: #
1.1067    www      12560:                         my $location=$parser->get_text('/import');
                   12561:                         my $dir=$filename;
                   12562:                         $dir=~s|[^/]*$||;
                   12563:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12564: 
                   12565:                         my $importid=$token->[2]->{'id'};
1.1068    www      12566:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12567: #
                   12568: # Check metadata for imported file to
                   12569: # see if it contained response items
                   12570: #
                   12571:                         my %currmetaentry = %metaentry;
                   12572:                         my $libresponseorder = &metadata($location,'responseorder');
                   12573:                         my $origfile;
                   12574:                         if ($libresponseorder ne '') {
                   12575:                             if ($#origfiletagids<0) {
                   12576:                                 undef(%importedrespids);
                   12577:                                 undef(%importedpartids);
                   12578:                             }
                   12579:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12580:                             if (@{$importedrespids{$importid}} > 0) {
                   12581:                                 $importedresponses = 1;
                   12582: # We need to get the original file and the imported file to get the response order correct
                   12583: # Load and inspect original file
                   12584:                                 if ($#origfiletagids<0) {
                   12585:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12586:                                     $origfile=&getfile($origfilelocation);
                   12587:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12588:                                 }
                   12589:                             }
                   12590:                         }
                   12591: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12592: # hash populated for imported library file
                   12593:                         %metaentry = %currmetaentry;
                   12594:                         undef(%currmetaentry);
1.1068    www      12595:                         if ($importmode eq 'problem') {
1.1069    www      12596: # Import as problem/response
1.1068    www      12597:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12598:                         } elsif ($importmode eq 'part') {
                   12599: # Import as part(s)
1.1069    www      12600:                            $importedparts=1;
                   12601: # We need to get the original file and the imported file to get the part order correct
                   12602: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12603: # Load and inspect original file if we didn't do that already
                   12604:                            if ($#origfiletagids<0) {
                   12605:                                undef(%importedrespids);
                   12606:                                undef(%importedpartids);
                   12607:                                if ($origfile eq '') {
                   12608:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12609:                                    $origfile=&getfile($origfilelocation);
                   12610:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12611:                                }
1.1070    www      12612:                            }
                   12613: 
1.1069    www      12614: # Load and inspect imported file
                   12615:                            my $impfile=&getfile($location);
                   12616:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12617:                            if ($#impfilepartids>=0) {
                   12618: # This problem had parts
1.1070    www      12619:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12620:                            } else {
                   12621: # Importing by turning a single problem into a problem part
                   12622: # It gets the import-tags ID as part-ID
                   12623:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12624:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12625:                            }
1.1068    www      12626:                         } else {
                   12627: # Normal import
                   12628:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12629:                            if (defined($token->[2]->{'id'})) {
                   12630:                               $unikey.='_'.$token->[2]->{'id'};
                   12631:                            }
1.1067    www      12632:                         }
                   12633: 
1.339     albertel 12634: 			if ($depthcount<20) {
1.736     albertel 12635: 			    my $metadata = 
                   12636: 				&metadata($uri,'keys', $location,$unikey,
                   12637: 					  $depthcount+1);
                   12638: 			    foreach my $meta (split(',',$metadata)) {
                   12639: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12640: 				$metathesekeys{$meta}=1;
1.339     albertel 12641: 			    }
1.1068    www      12642: 			
                   12643:                         }
1.1067    www      12644: 		    } else {
                   12645: #
                   12646: # Not importing, some other kind of non-package, non-library start tag
                   12647: # 
                   12648:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12649:                         if (defined($token->[2]->{'id'})) {
                   12650:                             $unikey.='_'.$token->[2]->{'id'};
                   12651:                         }
1.339     albertel 12652: 			if (defined($token->[2]->{'name'})) { 
                   12653: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12654: 			}
                   12655: 			$metathesekeys{$unikey}=1;
1.736     albertel 12656: 			foreach my $param (@{$token->[3]}) {
                   12657: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12658: 				$token->[2]->{$param};
1.339     albertel 12659: 			}
                   12660: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12661: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12662: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12663: 		 # only ws inside the tag, and not in default, so use default
                   12664: 		 # as value
1.599     albertel 12665: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12666: 			} elsif ( $internaltext =~ /\S/ ) {
                   12667: 		  # something interesting inside the tag
                   12668: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12669: 			} else {
1.908     albertel 12670: 		  # no interesting values, don't set a default
1.339     albertel 12671: 			}
1.172     www      12672: # end of not-a-package not-a-library import
1.339     albertel 12673: 		    }
1.172     www      12674: # end of not-a-package start tag
1.339     albertel 12675: 		}
1.172     www      12676: # the next is the end of "start tag"
1.339     albertel 12677: 	    }
                   12678: 	}
1.483     albertel 12679: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12680: 	$extension = lc($extension);
                   12681: 	if ($extension eq 'htm') { $extension='html'; }
                   12682: 
1.737     albertel 12683: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12684: 	    #no specific packages #how's our extension
                   12685: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12686: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12687: 					 \%metathesekeys);
                   12688: 	}
1.883     albertel 12689: 
                   12690: 	if (!exists($metaentry{':packages'})
                   12691: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12692: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12693: 		#no specific packages well let's get default then
                   12694: 		if ($key!~/^default&/) { next; }
1.488     albertel 12695: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12696: 					     \%metathesekeys);
                   12697: 	    }
                   12698: 	}
1.338     www      12699: # are there custom rights to evaluate
1.599     albertel 12700: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12701: 
1.338     www      12702:     #
                   12703:     # Importing a rights file here
1.339     albertel 12704:     #
                   12705: 	    unless ($depthcount) {
1.599     albertel 12706: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12707: 		my $dir=$filename;
                   12708: 		$dir=~s|[^/]*$||;
                   12709: 		$location=&filelocation($dir,$location);
1.736     albertel 12710: 		my $rights_metadata =
                   12711: 		    &metadata($uri,'keys',$location,'_rights',
                   12712: 			      $depthcount+1);
                   12713: 		foreach my $rights (split(',',$rights_metadata)) {
                   12714: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12715: 		    $metathesekeys{$rights}=1;
1.339     albertel 12716: 		}
                   12717: 	    }
                   12718: 	}
1.737     albertel 12719: 	# uniqifiy package listing
                   12720: 	my %seen;
                   12721: 	my @uniq_packages =
                   12722: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12723: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12724: 
1.1172.2.99  raeburn  12725:         if (($importedresponses) || ($importedparts)) {
                   12726:             if ($importedparts) {
1.1070    www      12727: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12728:                 $metaentry{':partorder'}='';
                   12729:                 $metathesekeys{'partorder'}=1;
                   12730:             }
                   12731:             if ($importedresponses) {
                   12732: # We had imported responses and need to rebuild responseorder
                   12733:                 $metaentry{':responseorder'}='';
                   12734:                 $metathesekeys{'responseorder'}=1;
                   12735:             }
                   12736:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12737:                 my $origid = $origfiletagids[$index+1];
                   12738:                 if ($origfiletagids[$index] eq 'part') {
                   12739: # Original part, part of the problem
                   12740:                     if ($importedparts) {
                   12741:                         $metaentry{':partorder'}.=','.$origid;
                   12742:                     }
                   12743:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12744:                     if ($importedparts) {
                   12745: # We have imported parts at this position
                   12746:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12747:                     }
                   12748:                     if ($importedresponses) {
                   12749: # We have imported responses at this position
                   12750:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12751:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12752:                         }
                   12753:                     }
                   12754:                 } else {
                   12755: # Original response item, part of the problem
                   12756:                     if ($importedresponses) {
                   12757:                         $metaentry{':responseorder'}.=','.$origid;
                   12758:                     }
                   12759:                 }
                   12760:             }
                   12761:             if ($importedparts) {
                   12762:                 $metaentry{':partorder'}=~s/^\,//;
                   12763:             }
                   12764:             if ($importedresponses) {
                   12765:                 $metaentry{':responseorder'}=~s/^\,//;
                   12766:             }
1.1070    www      12767:         }
                   12768: 
1.737     albertel 12769: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12770: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12771: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12772: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12773: # this is the end of "was not already recently cached
1.71      www      12774:     }
1.599     albertel 12775:     return $metaentry{':'.$what};
1.261     albertel 12776: }
                   12777: 
1.488     albertel 12778: sub metadata_create_package_def {
1.483     albertel 12779:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12780:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12781:     if ($subp eq 'default') { next; }
                   12782:     
1.599     albertel 12783:     if (defined($metaentry{':packages'})) {
                   12784: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12785:     } else {
1.599     albertel 12786: 	$metaentry{':packages'}=$package;
1.483     albertel 12787:     }
                   12788:     my $value=$packagetab{$key};
                   12789:     my $unikey;
                   12790:     $unikey='parameter_0_'.$name;
1.599     albertel 12791:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12792:     $$metathesekeys{$unikey}=1;
1.599     albertel 12793:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12794: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12795:     }
1.599     albertel 12796:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12797: 	$metaentry{':'.$unikey}=
                   12798: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12799:     }
                   12800: }
                   12801: 
1.261     albertel 12802: sub metadata_generate_part0 {
                   12803:     my ($metadata,$metacache,$uri) = @_;
                   12804:     my %allnames;
1.737     albertel 12805:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12806: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12807: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12808: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12809: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12810: 	    $allnames{$name}=$part;
                   12811: 	  }
                   12812: 	}
                   12813:     }
                   12814:     foreach my $name (keys(%allnames)) {
                   12815:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12816:       my $key=":parameter_0_$name";
1.261     albertel 12817:       $$metacache{"$key.part"}='0';
                   12818:       $$metacache{"$key.name"}=$name;
1.428     albertel 12819:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12820: 					   $allnames{$name}.'_'.$name.
                   12821: 					   '.type'};
1.428     albertel 12822:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12823: 			     '.display'};
1.644     www      12824:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12825:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12826:       $$metacache{"$key.display"}=$olddis;
                   12827:     }
1.71      www      12828: }
                   12829: 
1.764     albertel 12830: # ------------------------------------------------------ Devalidate title cache
                   12831: 
                   12832: sub devalidate_title_cache {
                   12833:     my ($url)=@_;
                   12834:     if (!$env{'request.course.id'}) { return; }
                   12835:     my $symb=&symbread($url);
                   12836:     if (!$symb) { return; }
                   12837:     my $key=$env{'request.course.id'}."\0".$symb;
                   12838:     &devalidate_cache_new('title',$key);
                   12839: }
                   12840: 
1.1014    droeschl 12841: # ------------------------------------------------- Get the title of a course
                   12842: 
                   12843: sub current_course_title {
                   12844:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12845: }
1.301     www      12846: # ------------------------------------------------- Get the title of a resource
                   12847: 
                   12848: sub gettitle {
                   12849:     my $urlsymb=shift;
                   12850:     my $symb=&symbread($urlsymb);
1.534     albertel 12851:     if ($symb) {
1.620     albertel 12852: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12853: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12854: 	if (defined($cached)) { 
                   12855: 	    return $result;
                   12856: 	}
1.534     albertel 12857: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12858: 	my $title='';
1.907     albertel 12859: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12860: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12861: 	} else {
                   12862: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12863: 		    &GDBM_READER(),0640)) {
                   12864: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12865: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12866: 		untie(%bighash);
                   12867: 	    }
1.534     albertel 12868: 	}
                   12869: 	$title=~s/\&colon\;/\:/gs;
                   12870: 	if ($title) {
1.1159    www      12871: # Remember both $symb and $title for dynamic metadata
                   12872:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12873:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12874: # Cache this title and then return it
1.599     albertel 12875: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12876: 	}
                   12877: 	$urlsymb=$url;
                   12878:     }
                   12879:     my $title=&metadata($urlsymb,'title');
                   12880:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12881:     return $title;
1.301     www      12882: }
1.613     albertel 12883: 
1.614     albertel 12884: sub get_slot {
                   12885:     my ($which,$cnum,$cdom)=@_;
                   12886:     if (!$cnum || !$cdom) {
1.790     albertel 12887: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12888: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12889: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12890:     }
1.703     albertel 12891:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12892:     my %slotinfo;
                   12893:     if (exists($remembered{$key})) {
                   12894: 	$slotinfo{$which} = $remembered{$key};
                   12895:     } else {
                   12896: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12897: 	&Apache::lonhomework::showhash(%slotinfo);
                   12898: 	my ($tmp)=keys(%slotinfo);
                   12899: 	if ($tmp=~/^error:/) { return (); }
                   12900: 	$remembered{$key} = $slotinfo{$which};
                   12901:     }
1.616     albertel 12902:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12903: 	return %{$slotinfo{$which}};
                   12904:     }
                   12905:     return $slotinfo{$which};
1.614     albertel 12906: }
1.1150    raeburn  12907: 
                   12908: sub get_reservable_slots {
                   12909:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12910:     my $now = time;
                   12911:     my $reservable_info;
                   12912:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12913:     if (exists($remembered{$key})) {
                   12914:         $reservable_info = $remembered{$key};
                   12915:     } else {
                   12916:         my %resv;
                   12917:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12918:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12919:         $reservable_info = \%resv;
                   12920:         $remembered{$key} = $reservable_info;
                   12921:     }
                   12922:     return $reservable_info;
                   12923: }
                   12924: 
                   12925: sub get_course_slots {
                   12926:     my ($cnum,$cdom) = @_;
                   12927:     my $hashid=$cnum.':'.$cdom;
                   12928:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12929:     if (defined($cached)) {
                   12930:         if (ref($result) eq 'HASH') {
                   12931:             return %{$result};
                   12932:         }
                   12933:     } else {
                   12934:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12935:         my ($tmp) = keys(%slots);
                   12936:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12937:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12938:             return %slots;
                   12939:         }
                   12940:     }
                   12941:     return;
                   12942: }
                   12943: 
                   12944: sub devalidate_slots_cache {
                   12945:     my ($cnum,$cdom)=@_;
                   12946:     my $hashid=$cnum.':'.$cdom;
                   12947:     &devalidate_cache_new('allslots',$hashid);
                   12948: }
                   12949: 
1.1172.2.8  raeburn  12950: sub get_coursechange {
                   12951:     my ($cdom,$cnum) = @_;
                   12952:     if ($cdom eq '' || $cnum eq '') {
                   12953:         return unless ($env{'request.course.id'});
                   12954:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12955:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12956:     }
                   12957:     my $hashid=$cdom.'_'.$cnum;
                   12958:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12959:     if ((defined($cached)) && ($change ne '')) {
                   12960:         return $change;
                   12961:     } else {
                   12962:         my %crshash;
                   12963:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12964:         if ($crshash{'internal.contentchange'} eq '') {
                   12965:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12966:             if ($change eq '') {
                   12967:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12968:                 $change = $crshash{'internal.created'};
                   12969:             }
                   12970:         } else {
                   12971:             $change = $crshash{'internal.contentchange'};
                   12972:         }
                   12973:         my $cachetime = 600;
                   12974:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12975:     }
                   12976:     return $change;
                   12977: }
                   12978: 
                   12979: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 12980:23):     my ($cdom,$cnum)=@_;
                   12981:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  12982:     &devalidate_cache_new('crschange',$hashid);
                   12983: }
                   12984: 
1.1172.2.146.  .9(raebu 12985:23): sub get_suppchange {
                   12986:23):     my ($cdom,$cnum) = @_;
                   12987:23):     if ($cdom eq '' || $cnum eq '') {
                   12988:23):         return unless ($env{'request.course.id'});
                   12989:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12990:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12991:23):     }
                   12992:23):     my $hashid=$cdom.'_'.$cnum;
                   12993:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   12994:23):     if ((defined($cached)) && ($change ne '')) {
                   12995:23):         return $change;
                   12996:23):     } else {
                   12997:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   12998:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   12999:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13000:23):             if ($change eq '') {
                   13001:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13002:23):                 $change = $crshash{'internal.created'};
                   13003:23):             }
                   13004:23):         } else {
                   13005:23):             $change = $crshash{'internal.supplementalchange'};
                   13006:23):         }
                   13007:23):         my $cachetime = 600;
                   13008:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13009:23):     }
                   13010:23):     return $change;
                   13011:23): }
                   13012:23): 
                   13013:23): sub devalidate_suppchange_cache {
                   13014:23):     my ($cdom,$cnum)=@_;
                   13015:23):     my $hashid=$cdom.'_'.$cnum;
                   13016:23):     &devalidate_cache_new('suppchange',$hashid);
                   13017:23): }
                   13018:23): 
                   13019:23): sub update_supp_caches {
                   13020:23):     my ($cdom,$cnum) = @_;
                   13021:23):     my %servers = &internet_dom_servers($cdom);
                   13022:23):     my @ids=&current_machine_ids();
                   13023:23):     foreach my $server (keys(%servers)) {
                   13024:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13025:23):         my $hashid=$cnum.':'.$cdom;
                   13026:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13027:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13028:23):     }
                   13029:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13030:23):     &count_supptools($cnum,$cdom,1);
                   13031:23):     my $now = time;
                   13032:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13033:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13034:23):     }
                   13035:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13036:23):          $cdom,$cnum);
                   13037:23):     &Apache::lonnet::appenv(
                   13038:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13039:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13040:23): }
                   13041:23): 
1.31      www      13042: # ------------------------------------------------- Update symbolic store links
                   13043: 
                   13044: sub symblist {
                   13045:     my ($mapname,%newhash)=@_;
1.438     www      13046:     $mapname=&deversion(&declutter($mapname));
1.31      www      13047:     my %hash;
1.620     albertel 13048:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13049:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13050:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13051: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13052: 		next if ($url eq 'last_known'
                   13053: 			 && $env{'form.no_update_last_known'});
                   13054: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13055: 						    $newhash{$url}->[1],
                   13056: 						    $newhash{$url}->[0]);
1.191     harris41 13057:             }
1.31      www      13058:             if (untie(%hash)) {
                   13059: 		return 'ok';
                   13060:             }
                   13061:         }
                   13062:     }
                   13063:     return 'error';
1.212     www      13064: }
                   13065: 
                   13066: # --------------------------------------------------------------- Verify a symb
                   13067: 
                   13068: sub symbverify {
1.1172.2.11  raeburn  13069:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13070:     my $thisfn=$thisurl;
1.439     www      13071:     $thisfn=&declutter($thisfn);
1.215     www      13072: # direct jump to resource in page or to a sequence - will construct own symbs
                   13073:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13074: # check URL part
1.409     www      13075:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13076: 
1.431     www      13077:     unless ($url eq $thisfn) { return 0; }
1.213     www      13078: 
1.216     www      13079:     $symb=&symbclean($symb);
1.510     www      13080:     $thisurl=&deversion($thisurl);
1.439     www      13081:     $thisfn=&deversion($thisfn);
1.213     www      13082: 
                   13083:     my %bighash;
                   13084:     my $okay=0;
1.431     www      13085: 
1.620     albertel 13086:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13087:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13088:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13089:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13090:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13091:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13092:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13093:             }
                   13094:         }
                   13095:         my $ids;
1.1172.2.122  raeburn  13096:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13097:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13098:         } else {
                   13099:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13100:         }
1.1102    raeburn  13101:         unless ($ids) {
1.1172.2.13  raeburn  13102:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13103:             $ids=$bighash{$idkey};
1.216     www      13104:         }
                   13105:         if ($ids) {
                   13106: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13107:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13108:                 $symb =~ s/\?.+$//;
                   13109:             }
1.800     albertel 13110: 	    foreach my $id (split(/\,/,$ids)) {
                   13111: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13112:                if (
                   13113:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13114:    eq $symb) {
1.1172.2.11  raeburn  13115:                    if (ref($encstate)) {
                   13116:                        $$encstate = $bighash{'encrypted_'.$id};
                   13117:                    }
1.1172.2.13  raeburn  13118:                    if (($env{'request.role.adv'}) ||
                   13119:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13120:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13121:                        $okay=1;
                   13122:                        last;
                   13123:                    }
                   13124:                }
                   13125:            }
1.216     www      13126:         }
1.213     www      13127: 	untie(%bighash);
                   13128:     }
                   13129:     return $okay;
1.31      www      13130: }
                   13131: 
1.210     www      13132: # --------------------------------------------------------------- Clean-up symb
                   13133: 
                   13134: sub symbclean {
                   13135:     my $symb=shift;
1.568     albertel 13136:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13137: # remove version from map
                   13138:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13139: 
1.210     www      13140: # remove version from URL
                   13141:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13142: 
1.507     www      13143: # remove wrapper
                   13144: 
1.510     www      13145:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13146:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13147:     return $symb;
1.409     www      13148: }
                   13149: 
                   13150: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13151: 
                   13152: sub encode_symb {
                   13153:     my ($map,$resid,$url)=@_;
                   13154:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13155: }
1.409     www      13156: 
                   13157: sub decode_symb {
1.568     albertel 13158:     my $symb=shift;
                   13159:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13160:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13161:     return (&fixversion($map),$resid,&fixversion($url));
                   13162: }
                   13163: 
                   13164: sub fixversion {
                   13165:     my $fn=shift;
1.609     banghart 13166:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13167:     my %bighash;
                   13168:     my $uri=&clutter($fn);
1.620     albertel 13169:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13170: # is this cached?
1.599     albertel 13171:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13172:     if (defined($cached)) { return $result; }
                   13173: # unfortunately not cached, or expired
1.620     albertel 13174:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13175: 	    &GDBM_READER(),0640)) {
                   13176:  	if ($bighash{'version_'.$uri}) {
                   13177:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13178:  	    unless (($version eq 'mostrecent') || 
                   13179: 		    ($version==&getversion($uri))) {
1.440     www      13180:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13181:  	    }
                   13182:  	}
                   13183:  	untie %bighash;
1.413     www      13184:     }
1.599     albertel 13185:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13186: }
                   13187: 
                   13188: sub deversion {
                   13189:     my $url=shift;
                   13190:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13191:     return $url;
1.210     www      13192: }
                   13193: 
1.31      www      13194: # ------------------------------------------------------ Return symb list entry
                   13195: 
                   13196: sub symbread {
1.1172.2.126  raeburn  13197:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13198:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13199:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13200:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13201:         unless (ref($possibles) eq 'HASH') {
                   13202:             if ($ignorecachednull) {
                   13203:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13204:             } else {
                   13205:                 return $env{$cache_str};
                   13206:             }
1.1172.2.66  raeburn  13207:         }
                   13208:     }
1.242     www      13209: # no filename provided? try from environment
1.1172.2.54  raeburn  13210:     unless ($thisfn) {
1.620     albertel 13211:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13212:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13213:         }
                   13214:         $thisfn=$env{'request.filename'};
1.44      www      13215:     }
1.569     albertel 13216:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13217: # is that filename actually a symb? Verify, clean, and return
                   13218:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13219: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13220: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13221: 	}
1.242     www      13222:     }
1.44      www      13223:     $thisfn=declutter($thisfn);
1.31      www      13224:     my %hash;
1.37      www      13225:     my %bighash;
                   13226:     my $syval='';
1.620     albertel 13227:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13228:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13229:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13230:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13231:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13232:                 untie(%hash);
                   13233:             }
1.1172.2.128  raeburn  13234:             if ($syval && $checkforblock) {
                   13235:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13236:                 if (@blockers) {
                   13237:                     $syval='';
                   13238:                 }
                   13239:             }
1.37      www      13240:         }
                   13241: # ---------------------------------------------------------- There was an entry
                   13242:         if ($syval) {
1.601     albertel 13243: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13244: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13245: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13246: 		    #return $env{$cache_str}='';
1.601     albertel 13247: 		#}    
                   13248: 		#$syval.=$1;
                   13249: 	    #}
1.37      www      13250:         } else {
                   13251: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13252:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13253:                             &GDBM_READER(),0640)) {
1.37      www      13254: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13255:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13256:               unless ($ids) { 
                   13257:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13258:               }
                   13259:               unless ($ids) {
                   13260: # alias?
                   13261: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13262:               }
1.37      www      13263:               if ($ids) {
                   13264: # ------------------------------------------------------------------- Has ID(s)
                   13265:                  my @possibilities=split(/\,/,$ids);
1.39      www      13266:                  if ($#possibilities==0) {
                   13267: # ----------------------------------------------- There is only one possibility
1.37      www      13268: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13269: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13270: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13271:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13272:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13273:                              $possibles->{$syval} = 1;
                   13274:                          }
1.1172.2.66  raeburn  13275:                      }
                   13276:                      if ($checkforblock) {
1.1172.2.126  raeburn  13277:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13278:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13279:                              if (@blockers) {
                   13280:                                  $syval = '';
                   13281:                                  untie(%bighash);
                   13282:                                  return $env{$cache_str}='';
                   13283:                              }
1.1172.2.66  raeburn  13284:                          }
                   13285:                      }
                   13286:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13287: # ------------------------------------------ There is more than one possibility
                   13288:                      my $realpossible=0;
1.800     albertel 13289:                      foreach my $id (@possibilities) {
                   13290: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13291:                          my $canaccess;
                   13292:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13293:                              $canaccess = 1;
                   13294:                          } else {
                   13295:                              $canaccess = &allowed('bre',$file);
                   13296:                          }
                   13297:                          if ($canaccess) {
                   13298:          		     my ($mapid,$resid)=split(/\./,$id);
                   13299:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13300:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13301:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13302:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13303:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13304:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13305:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13306:                                      if (@blockers > 0) {
                   13307:                                          $syval = '';
                   13308:                                      } else {
1.1172.2.66  raeburn  13309:                                          $syval = $poss_syval;
                   13310:                                          $realpossible++;
                   13311:                                      }
                   13312:                                  } else {
                   13313:                                      $syval = $poss_syval;
                   13314:                                      $realpossible++;
                   13315:                                  }
1.1172.2.126  raeburn  13316:                                  if ($syval) {
                   13317:                                      if (ref($possibles) eq 'HASH') {
                   13318:                                          $possibles->{$syval} = 1;
                   13319:                                      }
                   13320:                                  }
1.1172.2.66  raeburn  13321:                              }
1.39      www      13322: 			 }
1.191     harris41 13323:                      }
1.39      www      13324: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13325:                  } else {
                   13326:                      $syval='';
1.37      www      13327:                  }
                   13328: 	      }
1.1172.2.66  raeburn  13329:               untie(%bighash);
1.481     raeburn  13330:            }
1.31      www      13331:         }
1.62      www      13332:         if ($syval) {
1.1172.2.128  raeburn  13333: 	    return $env{$cache_str}=$syval;
1.62      www      13334:         }
1.31      www      13335:     }
1.949     raeburn  13336:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13337:     return $env{$cache_str}='';
1.31      www      13338: }
                   13339: 
                   13340: # ---------------------------------------------------------- Return random seed
                   13341: 
1.32      www      13342: sub numval {
                   13343:     my $txt=shift;
                   13344:     $txt=~tr/A-J/0-9/;
                   13345:     $txt=~tr/a-j/0-9/;
                   13346:     $txt=~tr/K-T/0-9/;
                   13347:     $txt=~tr/k-t/0-9/;
                   13348:     $txt=~tr/U-Z/0-5/;
                   13349:     $txt=~tr/u-z/0-5/;
                   13350:     $txt=~s/\D//g;
1.564     albertel 13351:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13352:     return int($txt);
1.368     albertel 13353: }
                   13354: 
1.484     albertel 13355: sub numval2 {
                   13356:     my $txt=shift;
                   13357:     $txt=~tr/A-J/0-9/;
                   13358:     $txt=~tr/a-j/0-9/;
                   13359:     $txt=~tr/K-T/0-9/;
                   13360:     $txt=~tr/k-t/0-9/;
                   13361:     $txt=~tr/U-Z/0-5/;
                   13362:     $txt=~tr/u-z/0-5/;
                   13363:     $txt=~s/\D//g;
                   13364:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13365:     my $total;
                   13366:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13367:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13368:     return int($total);
                   13369: }
                   13370: 
1.575     albertel 13371: sub numval3 {
                   13372:     use integer;
                   13373:     my $txt=shift;
                   13374:     $txt=~tr/A-J/0-9/;
                   13375:     $txt=~tr/a-j/0-9/;
                   13376:     $txt=~tr/K-T/0-9/;
                   13377:     $txt=~tr/k-t/0-9/;
                   13378:     $txt=~tr/U-Z/0-5/;
                   13379:     $txt=~tr/u-z/0-5/;
                   13380:     $txt=~s/\D//g;
                   13381:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13382:     my $total;
                   13383:     foreach my $val (@txts) { $total+=$val; }
                   13384:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13385:     return $total;
                   13386: }
                   13387: 
1.675     albertel 13388: sub digest {
                   13389:     my ($data)=@_;
                   13390:     my $digest=&Digest::MD5::md5($data);
                   13391:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13392:     my ($e,$f);
                   13393:     {
                   13394:         use integer;
                   13395:         $e=($a+$b);
                   13396:         $f=($c+$d);
                   13397:         if ($_64bit) {
                   13398:             $e=(($e<<32)>>32);
                   13399:             $f=(($f<<32)>>32);
                   13400:         }
                   13401:     }
                   13402:     if (wantarray) {
                   13403: 	return ($e,$f);
                   13404:     } else {
                   13405: 	my $g;
                   13406: 	{
                   13407: 	    use integer;
                   13408: 	    $g=($e+$f);
                   13409: 	    if ($_64bit) {
                   13410: 		$g=(($g<<32)>>32);
                   13411: 	    }
                   13412: 	}
                   13413: 	return $g;
                   13414:     }
                   13415: }
                   13416: 
1.368     albertel 13417: sub latest_rnd_algorithm_id {
1.675     albertel 13418:     return '64bit5';
1.366     albertel 13419: }
1.32      www      13420: 
1.503     albertel 13421: sub get_rand_alg {
                   13422:     my ($courseid)=@_;
1.790     albertel 13423:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13424:     if ($courseid) {
1.620     albertel 13425: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13426:     }
                   13427:     return &latest_rnd_algorithm_id();
                   13428: }
                   13429: 
1.562     albertel 13430: sub validCODE {
                   13431:     my ($CODE)=@_;
                   13432:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13433:     return 0;
                   13434: }
                   13435: 
1.491     albertel 13436: sub getCODE {
1.620     albertel 13437:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13438:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13439: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13440: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13441: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13442:     }
                   13443:     return undef;
                   13444: }
1.1133    foxr     13445: #
                   13446: #  Determines the random seed for a specific context:
                   13447: #
                   13448: # parameters:
                   13449: #   symb      - in course context the symb for the seed.
                   13450: #   course_id - The course id of the form domain_coursenum.
                   13451: #   domain    - Domain for the user.
                   13452: #   course    - Course for the user.
                   13453: #   cenv      - environment of the course.
                   13454: #
                   13455: # NOTE:
                   13456: #   All parameters are picked out of the environment if missing
                   13457: #   or not defined.
                   13458: #   If a symb cannot be determined the current time is used instead.
                   13459: #
                   13460: #  For a given well defined symb, courside, domain, username,
                   13461: #  and course environment, the seed is reproducible.
                   13462: #
1.31      www      13463: sub rndseed {
1.1133    foxr     13464:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13465:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13466:     if (!defined($symb)) {
1.366     albertel 13467: 	unless ($symb=$wsymb) { return time; }
                   13468:     }
1.1146    foxr     13469:     if (!defined $courseid) { 
                   13470: 	$courseid=$wcourseid; 
                   13471:     }
                   13472:     if (!defined $domain) { $domain=$wdomain; }
                   13473:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13474: 
                   13475:     my $which;
                   13476:     if (defined($cenv->{'rndseed'})) {
                   13477: 	$which = $cenv->{'rndseed'};
                   13478:     } else {
                   13479: 	$which =&get_rand_alg($courseid);
                   13480:     }
1.491     albertel 13481:     if (defined(&getCODE())) {
1.675     albertel 13482: 	if ($which eq '64bit5') {
                   13483: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13484: 	} elsif ($which eq '64bit4') {
1.575     albertel 13485: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13486: 	} else {
                   13487: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13488: 	}
1.675     albertel 13489:     } elsif ($which eq '64bit5') {
                   13490: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13491:     } elsif ($which eq '64bit4') {
                   13492: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13493:     } elsif ($which eq '64bit3') {
                   13494: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13495:     } elsif ($which eq '64bit2') {
                   13496: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13497:     } elsif ($which eq '64bit') {
                   13498: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13499:     }
                   13500:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13501: }
                   13502: 
                   13503: sub rndseed_32bit {
                   13504:     my ($symb,$courseid,$domain,$username)=@_;
                   13505:     {
                   13506: 	use integer;
                   13507: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13508: 	my $symbseed=numval($symb) << 22;
                   13509: 	my $namechck=unpack("%32C*",$username) << 17;
                   13510: 	my $nameseed=numval($username) << 12;
                   13511: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13512: 	my $courseseed=unpack("%32C*",$courseid);
                   13513: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13514: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13515: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13516: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13517: 	return $num;
                   13518:     }
                   13519: }
                   13520: 
                   13521: sub rndseed_64bit {
                   13522:     my ($symb,$courseid,$domain,$username)=@_;
                   13523:     {
                   13524: 	use integer;
                   13525: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13526: 	my $symbseed=numval($symb) << 10;
                   13527: 	my $namechck=unpack("%32S*",$username);
                   13528: 	
                   13529: 	my $nameseed=numval($username) << 21;
                   13530: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13531: 	my $courseseed=unpack("%32S*",$courseid);
                   13532: 	
                   13533: 	my $num1=$symbchck+$symbseed+$namechck;
                   13534: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13535: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13536: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13537: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13538: 	return "$num1,$num2";
1.155     albertel 13539:     }
1.366     albertel 13540: }
                   13541: 
1.443     albertel 13542: sub rndseed_64bit2 {
                   13543:     my ($symb,$courseid,$domain,$username)=@_;
                   13544:     {
                   13545: 	use integer;
                   13546: 	# strings need to be an even # of cahracters long, it it is odd the
                   13547:         # last characters gets thrown away
                   13548: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13549: 	my $symbseed=numval($symb) << 10;
                   13550: 	my $namechck=unpack("%32S*",$username.' ');
                   13551: 	
                   13552: 	my $nameseed=numval($username) << 21;
1.501     albertel 13553: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13554: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13555: 	
                   13556: 	my $num1=$symbchck+$symbseed+$namechck;
                   13557: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13558: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13559: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13560: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13561: 	return "$num1,$num2";
                   13562:     }
                   13563: }
                   13564: 
                   13565: sub rndseed_64bit3 {
                   13566:     my ($symb,$courseid,$domain,$username)=@_;
                   13567:     {
                   13568: 	use integer;
                   13569: 	# strings need to be an even # of cahracters long, it it is odd the
                   13570:         # last characters gets thrown away
                   13571: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13572: 	my $symbseed=numval2($symb) << 10;
                   13573: 	my $namechck=unpack("%32S*",$username.' ');
                   13574: 	
                   13575: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13576: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13577: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13578: 	
                   13579: 	my $num1=$symbchck+$symbseed+$namechck;
                   13580: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13581: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13582: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13583: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13584: 	
1.503     albertel 13585: 	return "$num1:$num2";
1.443     albertel 13586:     }
                   13587: }
                   13588: 
1.575     albertel 13589: sub rndseed_64bit4 {
                   13590:     my ($symb,$courseid,$domain,$username)=@_;
                   13591:     {
                   13592: 	use integer;
                   13593: 	# strings need to be an even # of cahracters long, it it is odd the
                   13594:         # last characters gets thrown away
                   13595: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13596: 	my $symbseed=numval3($symb) << 10;
                   13597: 	my $namechck=unpack("%32S*",$username.' ');
                   13598: 	
                   13599: 	my $nameseed=numval3($username) << 21;
                   13600: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13601: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13602: 	
                   13603: 	my $num1=$symbchck+$symbseed+$namechck;
                   13604: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13605: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13606: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13607: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13608: 	
1.575     albertel 13609: 	return "$num1:$num2";
                   13610:     }
                   13611: }
                   13612: 
1.675     albertel 13613: sub rndseed_64bit5 {
                   13614:     my ($symb,$courseid,$domain,$username)=@_;
                   13615:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13616:     return "$num1:$num2";
                   13617: }
                   13618: 
1.366     albertel 13619: sub rndseed_CODE_64bit {
                   13620:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13621:     {
1.366     albertel 13622: 	use integer;
1.443     albertel 13623: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13624: 	my $symbseed=numval2($symb);
1.491     albertel 13625: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13626: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13627: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13628: 	my $num1=$symbseed+$CODEchck;
                   13629: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13630: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13631: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13632: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13633: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13634: 	return "$num1:$num2";
1.366     albertel 13635:     }
                   13636: }
                   13637: 
1.575     albertel 13638: sub rndseed_CODE_64bit4 {
                   13639:     my ($symb,$courseid,$domain,$username)=@_;
                   13640:     {
                   13641: 	use integer;
                   13642: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13643: 	my $symbseed=numval3($symb);
                   13644: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13645: 	my $CODEseed=numval3(&getCODE());
                   13646: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13647: 	my $num1=$symbseed+$CODEchck;
                   13648: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13649: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13650: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13651: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13652: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13653: 	return "$num1:$num2";
                   13654:     }
                   13655: }
                   13656: 
1.675     albertel 13657: sub rndseed_CODE_64bit5 {
                   13658:     my ($symb,$courseid,$domain,$username)=@_;
                   13659:     my $code = &getCODE();
                   13660:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13661:     return "$num1:$num2";
                   13662: }
                   13663: 
1.366     albertel 13664: sub setup_random_from_rndseed {
                   13665:     my ($rndseed)=@_;
1.503     albertel 13666:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13667: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13668:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13669:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13670:         } else {
                   13671:             &Math::Random::random_set_seed($num1,$num2);
                   13672:         }
1.366     albertel 13673:     } else {
                   13674: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13675:     }
1.36      albertel 13676: }
                   13677: 
1.474     albertel 13678: sub latest_receipt_algorithm_id {
1.835     albertel 13679:     return 'receipt3';
1.474     albertel 13680: }
                   13681: 
1.480     www      13682: sub recunique {
                   13683:     my $fucourseid=shift;
                   13684:     my $unique;
1.835     albertel 13685:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13686: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13687: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13688:     } else {
                   13689: 	$unique=$perlvar{'lonReceipt'};
                   13690:     }
                   13691:     return unpack("%32C*",$unique);
                   13692: }
                   13693: 
                   13694: sub recprefix {
                   13695:     my $fucourseid=shift;
                   13696:     my $prefix;
1.835     albertel 13697:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13698: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13699: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13700:     } else {
                   13701: 	$prefix=$perlvar{'lonHostID'};
                   13702:     }
                   13703:     return unpack("%32C*",$prefix);
                   13704: }
                   13705: 
1.76      www      13706: sub ireceipt {
1.474     albertel 13707:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13708: 
                   13709:     my $return =&recprefix($fucourseid).'-';
                   13710: 
                   13711:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13712: 	$env{'request.state'} eq 'construct') {
                   13713: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13714: 	return $return;
                   13715:     }
                   13716: 
1.76      www      13717:     my $cuname=unpack("%32C*",$funame);
                   13718:     my $cudom=unpack("%32C*",$fudom);
                   13719:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13720:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13721:     my $cunique=&recunique($fucourseid);
1.474     albertel 13722:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13723:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13724: 
1.790     albertel 13725: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13726: 			       
                   13727: 	$return.= ($cunique%$cuname+
                   13728: 		   $cunique%$cudom+
                   13729: 		   $cusymb%$cuname+
                   13730: 		   $cusymb%$cudom+
                   13731: 		   $cucourseid%$cuname+
                   13732: 		   $cucourseid%$cudom+
                   13733: 		   $cpart%$cuname+
                   13734: 		   $cpart%$cudom);
                   13735:     } else {
                   13736: 	$return.= ($cunique%$cuname+
                   13737: 		   $cunique%$cudom+
                   13738: 		   $cusymb%$cuname+
                   13739: 		   $cusymb%$cudom+
                   13740: 		   $cucourseid%$cuname+
                   13741: 		   $cucourseid%$cudom);
                   13742:     }
                   13743:     return $return;
1.76      www      13744: }
                   13745: 
                   13746: sub receipt {
1.474     albertel 13747:     my ($part)=@_;
1.790     albertel 13748:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13749:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13750: }
1.260     ng       13751: 
1.790     albertel 13752: sub whichuser {
                   13753:     my ($passedsymb)=@_;
                   13754:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13755:     if (defined($env{'form.grade_symb'})) {
                   13756: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13757: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13758: 	if (!$allowed &&
                   13759: 	    exists($env{'request.course.sec'}) &&
                   13760: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13761: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13762: 			      '/'.$env{'request.course.sec'});
                   13763: 	}
                   13764: 	if ($allowed) {
                   13765: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13766: 	    $courseid=$tmp_courseid;
                   13767: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13768: 	    ($name)=&get_env_multiple('form.grade_username');
                   13769: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13770: 	}
                   13771:     }
                   13772:     if (!$passedsymb) {
                   13773: 	$symb=&symbread();
                   13774:     } else {
                   13775: 	$symb=$passedsymb;
                   13776:     }
                   13777:     $courseid=$env{'request.course.id'};
                   13778:     $domain=$env{'user.domain'};
                   13779:     $name=$env{'user.name'};
                   13780:     if ($name eq 'public' && $domain eq 'public') {
                   13781: 	if (!defined($env{'form.username'})) {
                   13782: 	    $env{'form.username'}.=time.rand(10000000);
                   13783: 	}
                   13784: 	$name.=$env{'form.username'};
                   13785:     }
                   13786:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13787: 
                   13788: }
                   13789: 
1.36      albertel 13790: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13791: # returns either the contents of the file or 
                   13792: # -1 if the file doesn't exist
1.481     raeburn  13793: #
                   13794: # if the target is a file that was uploaded via DOCS, 
                   13795: # a check will be made to see if a current copy exists on the local server,
                   13796: # if it does this will be served, otherwise a copy will be retrieved from
                   13797: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13798: # the local server.   
1.472     albertel 13799: 
1.36      albertel 13800: sub getfile {
1.538     albertel 13801:     my ($file) = @_;
1.609     banghart 13802:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13803:     &repcopy($file);
                   13804:     return &readfile($file);
                   13805: }
                   13806: 
                   13807: sub repcopy_userfile {
                   13808:     my ($file)=@_;
1.1142    raeburn  13809:     my $londocroot = $perlvar{'lonDocRoot'};
                   13810:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13811:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13812:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13813: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13814:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13815:     if (-e "$file") {
1.828     www      13816: # we already have a local copy, check it out
1.538     albertel 13817: 	my @fileinfo = stat($file);
1.828     www      13818: 	my $rtncode;
                   13819: 	my $info;
1.538     albertel 13820: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13821: 	if ($lwpresp ne 'ok') {
1.828     www      13822: # there is no such file anymore, even though we had a local copy
1.482     albertel 13823: 	    if ($rtncode eq '404') {
1.538     albertel 13824: 		unlink($file);
1.482     albertel 13825: 	    }
                   13826: 	    return -1;
                   13827: 	}
                   13828: 	if ($info < $fileinfo[9]) {
1.828     www      13829: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13830: 	    return 'ok';
1.828     www      13831: 	} else {
                   13832: # the file is outdated, get rid of it
                   13833: 	    unlink($file);
1.482     albertel 13834: 	}
1.828     www      13835:     }
                   13836: # one way or the other, at this point, we don't have the file
                   13837: # construct the correct path for the file
                   13838:     my @parts = ($cdom,$cnum); 
                   13839:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13840: 	push @parts, split(/\//,$1);
                   13841:     }
                   13842:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13843:     foreach my $part (@parts) {
                   13844: 	$path .= '/'.$part;
                   13845: 	if (!-e $path) {
                   13846: 	    mkdir($path,0770);
1.482     albertel 13847: 	}
                   13848:     }
1.828     www      13849: # now the path exists for sure
                   13850: # get a user agent
                   13851:     my $ua=new LWP::UserAgent;
                   13852:     my $transferfile=$file.'.in.transfer';
                   13853: # FIXME: this should flock
                   13854:     if (-e $transferfile) { return 'ok'; }
                   13855:     my $request;
                   13856:     $uri=~s/^\///;
1.980     raeburn  13857:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13858:     my $hostname = &hostname($homeserver);
1.980     raeburn  13859:     my $protocol = $protocol{$homeserver};
                   13860:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13861:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13862:     my $response=$ua->request($request,$transferfile);
                   13863: # did it work?
                   13864:     if ($response->is_error()) {
                   13865: 	unlink($transferfile);
                   13866: 	&logthis("Userfile repcopy failed for $uri");
                   13867: 	return -1;
                   13868:     }
                   13869: # worked, rename the transfer file
                   13870:     rename($transferfile,$file);
1.607     raeburn  13871:     return 'ok';
1.481     raeburn  13872: }
                   13873: 
1.517     albertel 13874: sub tokenwrapper {
                   13875:     my $uri=shift;
1.980     raeburn  13876:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13877:     $uri=~s|^/||;
1.620     albertel 13878:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13879:     my $token=$1;
1.552     albertel 13880:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13881:     if ($udom && $uname && $file) {
                   13882: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13883:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13884:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13885:         my $hostname = &hostname($homeserver);
1.980     raeburn  13886:         my $protocol = $protocol{$homeserver};
                   13887:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13888:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13889:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13890:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13891:     } else {
                   13892:         return '/adm/notfound.html';
                   13893:     }
                   13894: }
                   13895: 
1.828     www      13896: # call with reqtype HEAD: get last modification time
                   13897: # call with reqtype GET: get the file contents
                   13898: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13899: #
1.481     raeburn  13900: sub getuploaded {
                   13901:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13902:     $uri=~s/^\///;
1.980     raeburn  13903:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13904:     my $hostname = &hostname($homeserver);
1.980     raeburn  13905:     my $protocol = $protocol{$homeserver};
                   13906:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13907:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13908:     my $ua=new LWP::UserAgent;
                   13909:     my $request=new HTTP::Request($reqtype,$uri);
                   13910:     my $response=$ua->request($request);
                   13911:     $$rtncode = $response->code;
1.482     albertel 13912:     if (! $response->is_success()) {
                   13913: 	return 'failed';
                   13914:     }      
                   13915:     if ($reqtype eq 'HEAD') {
1.486     www      13916: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13917:     } elsif ($reqtype eq 'GET') {
                   13918: 	$$info = $response->content;
1.472     albertel 13919:     }
1.482     albertel 13920:     return 'ok';
1.36      albertel 13921: }
                   13922: 
1.481     raeburn  13923: sub readfile {
                   13924:     my $file = shift;
                   13925:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13926:     my $fh;
1.1172.2.96  raeburn  13927:     open($fh,"<",$file);
1.481     raeburn  13928:     my $a='';
1.800     albertel 13929:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13930:     return $a;
                   13931: }
                   13932: 
1.36      albertel 13933: sub filelocation {
1.590     banghart 13934:     my ($dir,$file) = @_;
                   13935:     my $location;
                   13936:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13937: 
                   13938:     if ($file =~ m-^/adm/-) {
                   13939: 	$file=~s-^/adm/wrapper/-/-;
                   13940: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13941:     }
1.882     albertel 13942: 
1.1139    www      13943:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13944:         $location = $file;
1.609     banghart 13945:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13946:         my ($udom,$uname,$filename)=
1.811     albertel 13947:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13948:         my $home=&homeserver($uname,$udom);
                   13949:         my $is_me=0;
                   13950:         my @ids=&current_machine_ids();
                   13951:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13952:         if ($is_me) {
1.1117    foxr     13953:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13954:         } else {
                   13955:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13956:   	      $udom.'/'.$uname.'/'.$filename;
                   13957:         }
1.882     albertel 13958:     } elsif ($file =~ m-^/adm/-) {
                   13959: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13960:     } else {
                   13961:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13962:         $file=~s:^/(res|priv)/:/:;
                   13963:         my $space=$1;
1.590     banghart 13964:         if ( !( $file =~ m:^/:) ) {
                   13965:             $location = $dir. '/'.$file;
                   13966:         } else {
1.1142    raeburn  13967:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13968:         }
1.59      albertel 13969:     }
1.590     banghart 13970:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13971:     while ($location=~m{/\.\./}) {
                   13972: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13973: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13974: 	} else {
                   13975: 	    $location=~ s{/\.\./}{/}g;
                   13976: 	}
                   13977:     } #remove dir/..
1.590     banghart 13978:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13979:     return $location;
1.46      www      13980: }
1.36      albertel 13981: 
1.46      www      13982: sub hreflocation {
                   13983:     my ($dir,$file)=@_;
1.980     raeburn  13984:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13985: 	$file=filelocation($dir,$file);
1.700     albertel 13986:     } elsif ($file=~m-^/adm/-) {
                   13987: 	$file=~s-^/adm/wrapper/-/-;
                   13988: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13989:     }
                   13990:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13991: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13992:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13993: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13994: 	        {/uploaded/$1/$2/}x;
1.46      www      13995:     }
1.913     albertel 13996:     if ($file=~ m{^/userfiles/}) {
                   13997: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13998:     }
1.462     albertel 13999:     return $file;
1.465     albertel 14000: }
                   14001: 
1.1139    www      14002: 
                   14003: 
                   14004: 
                   14005: 
1.465     albertel 14006: sub current_machine_domains {
1.853     albertel 14007:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14008: }
                   14009: 
                   14010: sub machine_domains {
                   14011:     my ($hostname) = @_;
1.465     albertel 14012:     my @domains;
1.838     albertel 14013:     my %hostname = &all_hostnames();
1.465     albertel 14014:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14015: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14016: 	if ($hostname eq $name) {
1.844     albertel 14017: 	    push(@domains,&host_domain($id));
1.465     albertel 14018: 	}
                   14019:     }
                   14020:     return @domains;
                   14021: }
                   14022: 
                   14023: sub current_machine_ids {
1.853     albertel 14024:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14025: }
                   14026: 
                   14027: sub machine_ids {
                   14028:     my ($hostname) = @_;
                   14029:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14030:     my @ids;
1.888     albertel 14031:     my %name_to_host = &all_names();
1.889     albertel 14032:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14033: 	return @{ $name_to_host{$hostname} };
                   14034:     }
                   14035:     return;
1.31      www      14036: }
                   14037: 
1.824     raeburn  14038: sub additional_machine_domains {
                   14039:     my @domains;
1.1172.2.142  raeburn  14040:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14041:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14042:             while( my $line = <$fh>) {
                   14043:                 chomp($line);
                   14044:                 $line =~ s/\s//g;
                   14045:                 push(@domains,$line);
                   14046:             }
                   14047:             close($fh);
                   14048:         }
1.824     raeburn  14049:     }
                   14050:     return @domains;
                   14051: }
                   14052: 
                   14053: sub default_login_domain {
                   14054:     my $domain = $perlvar{'lonDefDomain'};
                   14055:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14056:     foreach my $posdom (&current_machine_domains(),
                   14057:                         &additional_machine_domains()) {
                   14058:         if (lc($posdom) eq lc($testdomain)) {
                   14059:             $domain=$posdom;
                   14060:             last;
                   14061:         }
                   14062:     }
                   14063:     return $domain;
                   14064: }
                   14065: 
1.1172.2.106  raeburn  14066: sub shared_institution {
1.1172.2.136  raeburn  14067:     my ($dom,$lonhost) = @_;
                   14068:     if ($lonhost eq '') {
                   14069:         $lonhost = $perlvar{'lonHostID'};
                   14070:     }
1.1172.2.106  raeburn  14071:     my $same_intdom;
1.1172.2.136  raeburn  14072:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14073:     if ($hostintdom ne '') {
                   14074:         my %iphost = &get_iphost();
                   14075:         my $primary_id = &domain($dom,'primary');
                   14076:         my $primary_ip = &get_host_ip($primary_id);
                   14077:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14078:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14079:                 my $intdom = &internet_dom($id);
                   14080:                 if ($intdom eq $hostintdom) {
                   14081:                     $same_intdom = 1;
                   14082:                     last;
                   14083:                 }
                   14084:             }
                   14085:         }
                   14086:     }
                   14087:     return $same_intdom;
                   14088: }
                   14089: 
1.1172.2.120  raeburn  14090: sub uses_sts {
                   14091:     my ($ignore_cache) = @_;
                   14092:     my $lonhost = $perlvar{'lonHostID'};
                   14093:     my $hostname = &hostname($lonhost);
                   14094:     my $sts_on;
                   14095:     if ($protocol{$lonhost} eq 'https') {
                   14096:         my $cachetime = 12*3600;
                   14097:         if (!$ignore_cache) {
                   14098:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14099:             if (defined($cached)) {
                   14100:                 return $sts_on;
                   14101:             }
                   14102:         }
1.1172.2.121  raeburn  14103:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14104:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14105:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14106:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14107:         if ($response->is_success) {
                   14108:             my $has_sts = $response->header('Strict-Transport-Security');
                   14109:             if ($has_sts eq '') {
                   14110:                 $sts_on = 0;
                   14111:             } else {
                   14112:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14113:                     my $maxage = $1;
                   14114:                     if ($maxage) {
                   14115:                         $sts_on = 1;
                   14116:                     } else {
                   14117:                         $sts_on = 0;
                   14118:                     }
                   14119:                 } else {
                   14120:                     $sts_on = 0;
                   14121:                 }
                   14122:             }
                   14123:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14124:         }
                   14125:     }
                   14126:     return;
                   14127: }
                   14128: 
1.1172.2.142  raeburn  14129: sub waf_allssl {
                   14130:     my ($host_name) = @_;
                   14131:     my $alias = &get_proxy_alias();
                   14132:     if ($host_name eq '') {
                   14133:         $host_name = $ENV{'SERVER_NAME'};
                   14134:     }
                   14135:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14136:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14137:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14138:         if ($defdomdefaults{'waf_sslopt'}) {
                   14139:             return $defdomdefaults{'waf_sslopt'};
                   14140:         }
                   14141:     }
                   14142:     return;
                   14143: }
                   14144: 
1.1172.2.134  raeburn  14145: sub get_requestor_ip {
                   14146:     my ($r,$nolookup,$noproxy) = @_;
                   14147:     my $from_ip;
                   14148:     if (ref($r)) {
1.1172.2.142  raeburn  14149:         if ($r->can('useragent_ip')) {
                   14150:             if ($noproxy && $r->can('client_ip')) {
                   14151:                 $from_ip = $r->client_ip();
                   14152:             } else {
                   14153:                 $from_ip = $r->useragent_ip();
                   14154:             }
                   14155:         } elsif ($r->connection->can('remote_ip')) {
                   14156:             $from_ip = $r->connection->remote_ip();
                   14157:         } else {
                   14158:             $from_ip = $r->get_remote_host($nolookup);
                   14159:         }
1.1172.2.134  raeburn  14160:     } else {
                   14161:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14162:     }
1.1172.2.142  raeburn  14163:     return $from_ip if ($noproxy);
                   14164:    # Who controls proxy settings for server
                   14165:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14166:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14167:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14168:         if ($proxyinfo->{'vpnint'}) {
                   14169:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14170:                 return $from_ip;
                   14171:             }
                   14172:         }
                   14173:         if ($proxyinfo->{'trusted'}) {
                   14174:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14175:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14176:                 my ($ip,$xfor);
                   14177:                 if (ref($r)) {
                   14178:                     if ($ipheader) {
                   14179:                         $ip = $r->headers_in->{$ipheader};
                   14180:                     }
                   14181:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14182:                 } else {
                   14183:                     if ($ipheader) {
                   14184:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14185:                     }
                   14186:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14187:                 }
                   14188:                 if (($ip eq '') && ($xfor ne '')) {
                   14189:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14190:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14191:                             $ip = $poss_ip;
                   14192:                             last;
                   14193:                         }
                   14194:                     }
                   14195:                 }
                   14196:                 if ($ip ne '') {
                   14197:                     return $ip;
                   14198:                 }
                   14199:             }
                   14200:         }
                   14201:     }
1.1172.2.134  raeburn  14202:     return $from_ip;
                   14203: }
                   14204: 
1.1172.2.142  raeburn  14205: sub get_proxy_settings {
                   14206:     my ($dom_in_use) = @_;
                   14207:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14208:     my $proxyinfo = {
                   14209:                        ipheader => $domdefaults{'waf_ipheader'},
                   14210:                        trusted  => $domdefaults{'waf_trusted'},
                   14211:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14212:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14213:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14214:                     };
                   14215:     return $proxyinfo;
                   14216: }
                   14217: 
                   14218: sub ip_match {
                   14219:     my ($ip,$pattern_str) = @_;
                   14220:     $ip=Net::CIDR::cidrvalidate($ip);
                   14221:     if ($ip) {
                   14222:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14223:     }
                   14224:     return;
                   14225: }
                   14226: 
                   14227: sub get_proxy_alias {
                   14228:     my ($lonid) = @_;
                   14229:     if ($lonid eq '') {
                   14230:         $lonid = $perlvar{'lonHostID'};
                   14231:     }
                   14232:     if (!defined(&hostname($lonid))) {
                   14233:         return;
                   14234:     }
                   14235:     if ($lonid ne '') {
                   14236:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14237:         if ($cached) {
                   14238:             return $alias;
                   14239:         }
                   14240:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14241:         if ($dom ne '') {
                   14242:             my $cachetime = 60*60*24;
                   14243:             my %domconfig =
                   14244:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14245:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14246:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14247:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14248:                 }
                   14249:             }
                   14250:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14251:         }
                   14252:     }
                   14253:     return;
                   14254: }
                   14255: 
                   14256: sub use_proxy_alias {
                   14257:     my ($r,$lonid) = @_;
                   14258:     my $alias = &get_proxy_alias($lonid);
                   14259:     if ($alias) {
                   14260:         my $dom = &host_domain($lonid);
                   14261:         if ($dom ne '') {
                   14262:             my $proxyinfo = &get_proxy_settings($dom);
                   14263:             my ($vpnint,$remote_ip);
                   14264:             if (ref($proxyinfo) eq 'HASH') {
                   14265:                 $vpnint = $proxyinfo->{'vpnint'};
                   14266:                 if ($vpnint) {
                   14267:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14268:                 }
                   14269:             }
                   14270:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14271:                 return $alias;
                   14272:             }
                   14273:         }
                   14274:     }
                   14275:     return;
                   14276: }
                   14277: 
                   14278: sub alias_sso {
                   14279:     my ($lonid) = @_;
                   14280:     if ($lonid eq '') {
                   14281:         $lonid = $perlvar{'lonHostID'};
                   14282:     }
                   14283:     if (!defined(&hostname($lonid))) {
                   14284:         return;
                   14285:     }
                   14286:     if ($lonid ne '') {
                   14287:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14288:         if ($cached) {
                   14289:             return $use_alias;
                   14290:         }
                   14291:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14292:         if ($dom ne '') {
                   14293:             my $cachetime = 60*60*24;
                   14294:             my %domconfig =
                   14295:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14296:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14297:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14298:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14299:                 }
                   14300:             }
                   14301:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14302:         }
                   14303:     }
                   14304:     return;
                   14305: }
                   14306: 
                   14307: sub get_saml_landing {
                   14308:     my ($lonid) = @_;
                   14309:     if ($lonid eq '') {
                   14310:         my $defdom = &default_login_domain();
                   14311:         my @hosts = &current_machine_ids();
                   14312:         if (@hosts > 1) {
                   14313:             foreach my $hostid (@hosts) {
                   14314:                 if (&host_domain($hostid) eq $defdom) {
                   14315:                     $lonid = $hostid;
                   14316:                     last;
                   14317:                 }
                   14318:             }
                   14319:         } else {
                   14320:             $lonid = $perlvar{'lonHostID'};
                   14321:         }
                   14322:         if ($lonid) {
                   14323:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14324:                 return;
                   14325:             }
                   14326:         } else {
                   14327:             return;
                   14328:         }
                   14329:     } elsif (!defined(&hostname($lonid))) {
                   14330:         return;
                   14331:     }
                   14332:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14333:     if ($cached) {
                   14334:         return $landing;
                   14335:     }
                   14336:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14337:     if ($dom ne '') {
                   14338:         my $cachetime = 60*60*24;
                   14339:         my %domconfig =
                   14340:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14341:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14342:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14343:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14344:                     $landing = 1;
                   14345:                 }
                   14346:             }
                   14347:         }
                   14348:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14349:     }
                   14350:     return;
                   14351: }
                   14352: 
1.31      www      14353: # ------------------------------------------------------------- Declutters URLs
                   14354: 
                   14355: sub declutter {
                   14356:     my $thisfn=shift;
1.569     albertel 14357:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14358:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14359:         $thisfn=~s{^/home/httpd/html}{};
                   14360:     }
1.31      www      14361:     $thisfn=~s/^\///;
1.697     albertel 14362:     $thisfn=~s|^adm/wrapper/||;
                   14363:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14364:     $thisfn=~s/^res\///;
1.1172    bisitz   14365:     $thisfn=~s/^priv\///;
1.1032    raeburn  14366:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14367:         $thisfn=~s/\?.+$//;
                   14368:     }
1.268     www      14369:     return $thisfn;
                   14370: }
                   14371: 
                   14372: # ------------------------------------------------------------- Clutter up URLs
                   14373: 
                   14374: sub clutter {
                   14375:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14376:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14377: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14378:        $thisfn='/res'.$thisfn; 
                   14379:     }
1.1031    raeburn  14380:     if ($thisfn !~m|^/adm|) {
                   14381: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14382: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14383: 	} else {
                   14384: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14385: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14386: 	    if ($embstyle eq 'ssi'
                   14387: 		|| ($embstyle eq 'hdn')
                   14388: 		|| ($embstyle eq 'rat')
                   14389: 		|| ($embstyle eq 'prv')
                   14390: 		|| ($embstyle eq 'ign')) {
                   14391: 		#do nothing with these
                   14392: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14393: 		|| ($embstyle eq 'emb')
                   14394: 		|| ($embstyle eq 'wrp')) {
                   14395: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14396: 	    } elsif ($embstyle eq 'unk'
                   14397: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14398: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14399: 	    } else {
1.718     www      14400: #		&logthis("Got a blank emb style");
1.695     albertel 14401: 	    }
1.694     albertel 14402: 	}
1.1172.2.146.  .1(raebu 14403:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14404:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14405:     }
1.31      www      14406:     return $thisfn;
1.12      www      14407: }
                   14408: 
1.787     albertel 14409: sub clutter_with_no_wrapper {
                   14410:     my $uri = &clutter(shift);
                   14411:     if ($uri =~ m-^/adm/-) {
                   14412: 	$uri =~ s-^/adm/wrapper/-/-;
                   14413: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14414:     }
                   14415:     return $uri;
                   14416: }
                   14417: 
1.557     albertel 14418: sub freeze_escape {
                   14419:     my ($value)=@_;
                   14420:     if (ref($value)) {
                   14421: 	$value=&nfreeze($value);
                   14422: 	return '__FROZEN__'.&escape($value);
                   14423:     }
                   14424:     return &escape($value);
                   14425: }
                   14426: 
1.11      www      14427: 
1.557     albertel 14428: sub thaw_unescape {
                   14429:     my ($value)=@_;
                   14430:     if ($value =~ /^__FROZEN__/) {
                   14431: 	substr($value,0,10,undef);
                   14432: 	$value=&unescape($value);
                   14433: 	return &thaw($value);
                   14434:     }
                   14435:     return &unescape($value);
                   14436: }
                   14437: 
1.436     albertel 14438: sub correct_line_ends {
                   14439:     my ($result)=@_;
                   14440:     $$result =~s/\r\n/\n/mg;
                   14441:     $$result =~s/\r/\n/mg;
1.415     albertel 14442: }
1.1       albertel 14443: # ================================================================ Main Program
                   14444: 
1.184     www      14445: sub goodbye {
1.204     albertel 14446:    &logthis("Starting Shut down");
1.443     albertel 14447: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14448:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14449: #converted
1.599     albertel 14450: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14451:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14452: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14453: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14454: #1.1 only
1.870     albertel 14455: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14456: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14457: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14458: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14459:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14460:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14461:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14462:    &flushcourselogs();
                   14463:    &logthis("Shutting down");
                   14464: }
                   14465: 
1.852     albertel 14466: sub get_dns {
1.1172.2.17  raeburn  14467:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14468:     if (!$ignore_cache) {
                   14469: 	my ($content,$cached)=
                   14470: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14471: 	if ($cached) {
1.1172.2.17  raeburn  14472: 	    &$func($content,$hashref);
1.869     albertel 14473: 	    return;
                   14474: 	}
                   14475:     }
                   14476: 
                   14477:     my %alldns;
1.1172.2.96  raeburn  14478:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14479:         foreach my $dns (<$config>) {
                   14480: 	    next if ($dns !~ /^\^(\S*)/x);
                   14481:             my $line = $1;
                   14482:             my ($host,$protocol) = split(/:/,$line);
                   14483:             if ($protocol ne 'https') {
                   14484:                 $protocol = 'http';
                   14485:             }
                   14486: 	    $alldns{$host} = $protocol;
1.979     raeburn  14487:         }
1.1172.2.96  raeburn  14488:         close($config);
1.869     albertel 14489:     }
                   14490:     while (%alldns) {
1.1172.2.52  raeburn  14491: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14492:         my @content;
                   14493:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14494:             my $command = (split('/',$url))[3];
                   14495:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14496:             delete($alldns{$dns});
                   14497:             next if (($dir eq '') || ($file eq ''));
                   14498:             if (open(my $config,'<',"$dir/$file")) {
                   14499:                 @content = <$config>;
                   14500:                 close($config);
                   14501:             }
                   14502:         } else {
                   14503: 	    my $ua=new LWP::UserAgent;
                   14504:             $ua->timeout(30);
                   14505: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14506: 	    my $response=$ua->request($request);
                   14507:             delete($alldns{$dns});
                   14508: 	    next if ($response->is_error());
                   14509: 	    @content = split("\n",$response->content);
                   14510:         }
1.1172.2.17  raeburn  14511:         unless ($nocache) {
1.1172.2.23  raeburn  14512: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14513:         }
                   14514: 	&$func(\@content,$hashref);
1.869     albertel 14515: 	return;
1.852     albertel 14516:     }
1.871     albertel 14517:     my $which = (split('/',$url))[3];
                   14518:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14519:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14520:         my @content = <$config>;
                   14521:         &$func(\@content,$hashref);
                   14522:     }
1.1172.2.17  raeburn  14523:     return;
                   14524: }
                   14525: 
                   14526: # ------------------------------------------------------Get DNS checksums file
                   14527: sub parse_dns_checksums_tab {
                   14528:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14529:     my $lonhost = $perlvar{'lonHostID'};
                   14530:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14531:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14532:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14533:     my $webconfdir = '/etc/httpd/conf';
                   14534:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14535:         $webconfdir = '/etc/apache2';
                   14536:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14537:         if ($1 >= 10) {
                   14538:             $webconfdir = '/etc/apache2';
                   14539:         }
                   14540:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14541:         if ($1 >= 10.0) {
                   14542:             $webconfdir = '/etc/apache2';
                   14543:         }
                   14544:     }
1.1172.2.17  raeburn  14545:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14546:     my (%chksum,%revnum);
                   14547:     if (ref($lines) eq 'ARRAY') {
                   14548:         chomp(@{$lines});
1.1172.2.34  raeburn  14549:         my $version = shift(@{$lines});
                   14550:         if ($version eq $release) {
1.1172.2.17  raeburn  14551:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14552:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14553:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14554:                     if ($webconfdir eq '/etc/apache2') {
                   14555:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14556:                     }
                   14557:                 }
1.1172.2.34  raeburn  14558:                 $chksum{$file} = $shasum;
                   14559:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14560:             }
                   14561:             if (ref($hashref) eq 'HASH') {
                   14562:                 %{$hashref} = (
                   14563:                                 sums     => \%chksum,
                   14564:                                 versions => \%revnum,
                   14565:                               );
                   14566:             }
                   14567:         }
                   14568:     }
1.869     albertel 14569:     return;
1.852     albertel 14570: }
1.1172.2.17  raeburn  14571: 
                   14572: sub fetch_dns_checksums {
                   14573:     my %checksums;
1.1172.2.34  raeburn  14574:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14575:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14576:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14577:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14578:              \%checksums);
                   14579:     return \%checksums;
                   14580: }
                   14581: 
1.1172.2.142  raeburn  14582: sub parse_getdns_url {
                   14583:     my ($command,$url) = @_;
                   14584:     my $dir = $perlvar{'lonTabDir'};
                   14585:     my $file;
                   14586:     if ($command eq 'hosts') {
                   14587:         $file = 'dns_hosts.tab';
                   14588:     } elsif ($command eq 'domain') {
                   14589:         $file = 'dns_domain.tab';
                   14590:     } elsif ($command eq 'checksums') {
                   14591:         my $version = (split('/',$url))[4];
                   14592:         $file = "dns_checksums/$version.tab",
                   14593:     }
                   14594:     return ($dir,$file);
                   14595: }
                   14596: 
1.327     albertel 14597: # ------------------------------------------------------------ Read domain file
                   14598: {
1.852     albertel 14599:     my $loaded;
1.846     albertel 14600:     my %domain;
                   14601: 
1.852     albertel 14602:     sub parse_domain_tab {
                   14603: 	my ($lines) = @_;
                   14604: 	foreach my $line (@$lines) {
                   14605: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14606: 
1.846     albertel 14607: 	    chomp($line);
1.852     albertel 14608: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14609: 	    my %this_domain;
                   14610: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14611: 			       'lang_def', 'city', 'longi', 'lati',
                   14612: 			       'primary') {
                   14613: 		$this_domain{$field} = shift(@elements);
                   14614: 	    }
                   14615: 	    $domain{$name} = \%this_domain;
1.852     albertel 14616: 	}
                   14617:     }
1.864     albertel 14618: 
                   14619:     sub reset_domain_info {
                   14620: 	undef($loaded);
                   14621: 	undef(%domain);
                   14622:     }
                   14623: 
1.852     albertel 14624:     sub load_domain_tab {
1.1172.2.70  raeburn  14625: 	my ($ignore_cache,$nocache) = @_;
                   14626: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14627: 	my $fh;
1.1172.2.96  raeburn  14628: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14629: 	    my @lines = <$fh>;
                   14630: 	    &parse_domain_tab(\@lines);
1.448     albertel 14631: 	}
1.852     albertel 14632: 	close($fh);
                   14633: 	$loaded = 1;
1.327     albertel 14634:     }
1.846     albertel 14635: 
                   14636:     sub domain {
1.852     albertel 14637: 	&load_domain_tab() if (!$loaded);
                   14638: 
1.846     albertel 14639: 	my ($name,$what) = @_;
                   14640: 	return if ( !exists($domain{$name}) );
                   14641: 
                   14642: 	if (!$what) {
                   14643: 	    return $domain{$name}{'description'};
                   14644: 	}
                   14645: 	return $domain{$name}{$what};
                   14646:     }
1.974     raeburn  14647: 
                   14648:     sub domain_info {
                   14649:         &load_domain_tab() if (!$loaded);
                   14650:         return %domain;
                   14651:     }
                   14652: 
1.327     albertel 14653: }
                   14654: 
                   14655: 
1.1       albertel 14656: # ------------------------------------------------------------- Read hosts file
                   14657: {
1.838     albertel 14658:     my %hostname;
1.844     albertel 14659:     my %hostdom;
1.845     albertel 14660:     my %libserv;
1.852     albertel 14661:     my $loaded;
1.888     albertel 14662:     my %name_to_host;
1.1074    raeburn  14663:     my %internetdom;
1.1107    raeburn  14664:     my %LC_dns_serv;
1.852     albertel 14665: 
                   14666:     sub parse_hosts_tab {
                   14667: 	my ($file) = @_;
                   14668: 	foreach my $configline (@$file) {
                   14669: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14670:             chomp($configline);
                   14671: 	    if ($configline =~ /^\^/) {
                   14672:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14673:                     $LC_dns_serv{$1} = 1;
                   14674:                 }
                   14675:                 next;
                   14676:             }
1.1074    raeburn  14677: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14678: 	    $name=~s/\s//g;
                   14679: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14680:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14681:                     my $curr = $hostname{$id};
                   14682:                     my $skip;
                   14683:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14684:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14685:                             $skip = 1;
                   14686:                         } else {
                   14687:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14688:                         }
                   14689:                     }
                   14690:                     unless ($skip) {
                   14691:                         push(@{$name_to_host{$name}},$id);
                   14692:                     }
                   14693:                 } else {
                   14694:                     push(@{$name_to_host{$name}},$id);
                   14695:                 }
1.852     albertel 14696: 		$hostname{$id}=$name;
                   14697: 		$hostdom{$id}=$domain;
                   14698: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14699:                 if (defined($protocol)) {
                   14700:                     if ($protocol eq 'https') {
                   14701:                         $protocol{$id} = $protocol;
                   14702:                     } else {
                   14703:                         $protocol{$id} = 'http'; 
                   14704:                     }
1.968     raeburn  14705:                 } else {
1.969     raeburn  14706:                     $protocol{$id} = 'http';
1.968     raeburn  14707:                 }
1.1074    raeburn  14708:                 if (defined($intdom)) {
                   14709:                     $internetdom{$id} = $intdom;
                   14710:                 }
1.852     albertel 14711: 	    }
                   14712: 	}
                   14713:     }
1.864     albertel 14714:     
                   14715:     sub reset_hosts_info {
1.897     albertel 14716: 	&purge_remembered();
1.864     albertel 14717: 	&reset_domain_info();
                   14718: 	&reset_hosts_ip_info();
1.892     albertel 14719: 	undef(%name_to_host);
1.864     albertel 14720: 	undef(%hostname);
                   14721: 	undef(%hostdom);
                   14722: 	undef(%libserv);
                   14723: 	undef($loaded);
                   14724:     }
1.1       albertel 14725: 
1.852     albertel 14726:     sub load_hosts_tab {
1.1172.2.70  raeburn  14727: 	my ($ignore_cache,$nocache) = @_;
                   14728: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14729: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14730: 	my @config = <$config>;
                   14731: 	&parse_hosts_tab(\@config);
                   14732: 	close($config);
                   14733: 	$loaded=1;
1.1       albertel 14734:     }
1.852     albertel 14735: 
1.838     albertel 14736:     sub hostname {
1.852     albertel 14737: 	&load_hosts_tab() if (!$loaded);
                   14738: 
1.838     albertel 14739: 	my ($lonid) = @_;
                   14740: 	return $hostname{$lonid};
                   14741:     }
1.845     albertel 14742: 
1.838     albertel 14743:     sub all_hostnames {
1.852     albertel 14744: 	&load_hosts_tab() if (!$loaded);
                   14745: 
1.838     albertel 14746: 	return %hostname;
                   14747:     }
1.845     albertel 14748: 
1.888     albertel 14749:     sub all_names {
1.1172.2.70  raeburn  14750:         my ($ignore_cache,$nocache) = @_;
                   14751: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14752: 
                   14753: 	return %name_to_host;
                   14754:     }
                   14755: 
1.974     raeburn  14756:     sub all_host_domain {
                   14757:         &load_hosts_tab() if (!$loaded);
                   14758:         return %hostdom;
                   14759:     }
                   14760: 
1.845     albertel 14761:     sub is_library {
1.852     albertel 14762: 	&load_hosts_tab() if (!$loaded);
                   14763: 
1.845     albertel 14764: 	return exists($libserv{$_[0]});
                   14765:     }
                   14766: 
                   14767:     sub all_library {
1.852     albertel 14768: 	&load_hosts_tab() if (!$loaded);
                   14769: 
1.845     albertel 14770: 	return %libserv;
                   14771:     }
                   14772: 
1.1062    droeschl 14773:     sub unique_library {
                   14774: 	#2x reverse removes all hostnames that appear more than once
                   14775:         my %unique = reverse &all_library();
                   14776:         return reverse %unique;
                   14777:     }
                   14778: 
1.841     albertel 14779:     sub get_servers {
1.852     albertel 14780: 	&load_hosts_tab() if (!$loaded);
                   14781: 
1.841     albertel 14782: 	my ($domain,$type) = @_;
                   14783: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14784: 	                                          : %hostname;
                   14785: 	my %result;
1.842     albertel 14786: 	if (ref($domain) eq 'ARRAY') {
                   14787: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14788: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14789: 		    $result{$host} = $hostname;
                   14790: 		}
                   14791: 	    }
                   14792: 	} else {
                   14793: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14794: 		if ($hostdom{$host} eq $domain) {
                   14795: 		    $result{$host} = $hostname;
                   14796: 		}
1.841     albertel 14797: 	    }
                   14798: 	}
                   14799: 	return %result;
                   14800:     }
1.845     albertel 14801: 
1.1062    droeschl 14802:     sub get_unique_servers {
                   14803:         my %unique = reverse &get_servers(@_);
                   14804: 	return reverse %unique;
                   14805:     }
                   14806: 
1.844     albertel 14807:     sub host_domain {
1.852     albertel 14808: 	&load_hosts_tab() if (!$loaded);
                   14809: 
1.844     albertel 14810: 	my ($lonid) = @_;
                   14811: 	return $hostdom{$lonid};
                   14812:     }
                   14813: 
1.841     albertel 14814:     sub all_domains {
1.852     albertel 14815: 	&load_hosts_tab() if (!$loaded);
                   14816: 
1.841     albertel 14817: 	my %seen;
                   14818: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14819: 	return @uniq;
                   14820:     }
1.1074    raeburn  14821: 
                   14822:     sub internet_dom {
                   14823:         &load_hosts_tab() if (!$loaded);
                   14824: 
                   14825:         my ($lonid) = @_;
                   14826:         return $internetdom{$lonid};
                   14827:     }
1.1107    raeburn  14828: 
                   14829:     sub is_LC_dns {
                   14830:         &load_hosts_tab() if (!$loaded);
                   14831: 
                   14832:         my ($hostname) = @_;
                   14833:         return exists($LC_dns_serv{$hostname});
                   14834:     }
                   14835: 
1.1       albertel 14836: }
                   14837: 
1.847     albertel 14838: { 
                   14839:     my %iphost;
1.856     albertel 14840:     my %name_to_ip;
                   14841:     my %lonid_to_ip;
1.869     albertel 14842: 
1.847     albertel 14843:     sub get_hosts_from_ip {
                   14844: 	my ($ip) = @_;
                   14845: 	my %iphosts = &get_iphost();
                   14846: 	if (ref($iphosts{$ip})) {
                   14847: 	    return @{$iphosts{$ip}};
                   14848: 	}
                   14849: 	return;
1.839     albertel 14850:     }
1.864     albertel 14851:     
                   14852:     sub reset_hosts_ip_info {
                   14853: 	undef(%iphost);
                   14854: 	undef(%name_to_ip);
                   14855: 	undef(%lonid_to_ip);
                   14856:     }
1.856     albertel 14857: 
                   14858:     sub get_host_ip {
                   14859: 	my ($lonid) = @_;
                   14860: 	if (exists($lonid_to_ip{$lonid})) {
                   14861: 	    return $lonid_to_ip{$lonid};
                   14862: 	}
                   14863: 	my $name=&hostname($lonid);
                   14864:    	my $ip = gethostbyname($name);
                   14865: 	return if (!$ip || length($ip) ne 4);
                   14866: 	$ip=inet_ntoa($ip);
                   14867: 	$name_to_ip{$name}   = $ip;
                   14868: 	$lonid_to_ip{$lonid} = $ip;
                   14869: 	return $ip;
                   14870:     }
1.847     albertel 14871:     
                   14872:     sub get_iphost {
1.1172.2.70  raeburn  14873: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14874: 
1.869     albertel 14875: 	if (!$ignore_cache) {
                   14876: 	    if (%iphost) {
                   14877: 		return %iphost;
                   14878: 	    }
                   14879: 	    my ($ip_info,$cached)=
                   14880: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14881: 	    if ($cached) {
                   14882: 		%iphost      = %{$ip_info->[0]};
                   14883: 		%name_to_ip  = %{$ip_info->[1]};
                   14884: 		%lonid_to_ip = %{$ip_info->[2]};
                   14885: 		return %iphost;
                   14886: 	    }
                   14887: 	}
1.894     albertel 14888: 
                   14889: 	# get yesterday's info for fallback
                   14890: 	my %old_name_to_ip;
                   14891: 	my ($ip_info,$cached)=
                   14892: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14893: 	if ($cached) {
                   14894: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14895: 	}
                   14896: 
1.1172.2.70  raeburn  14897: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14898: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14899: 	    my $ip;
                   14900: 	    if (!exists($name_to_ip{$name})) {
                   14901: 		$ip = gethostbyname($name);
                   14902: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14903: 		    if (defined($old_name_to_ip{$name})) {
                   14904: 			$ip = $old_name_to_ip{$name};
                   14905: 			&logthis("Can't find $name defaulting to old $ip");
                   14906: 		    } else {
                   14907: 			&logthis("Name $name no IP found");
                   14908: 			next;
                   14909: 		    }
                   14910: 		} else {
                   14911: 		    $ip=inet_ntoa($ip);
1.847     albertel 14912: 		}
                   14913: 		$name_to_ip{$name} = $ip;
                   14914: 	    } else {
                   14915: 		$ip = $name_to_ip{$name};
1.653     albertel 14916: 	    }
1.888     albertel 14917: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14918: 		$lonid_to_ip{$id} = $ip;
                   14919: 	    }
                   14920: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14921: 	}
1.1172.2.70  raeburn  14922:         unless ($nocache) {
                   14923: 	    &do_cache_new('iphost','iphost',
                   14924: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14925: 		          48*60*60);
                   14926:         }
1.869     albertel 14927: 
1.847     albertel 14928: 	return %iphost;
1.598     albertel 14929:     }
                   14930: 
1.992     raeburn  14931:     #
                   14932:     #  Given a DNS returns the loncapa host name for that DNS 
                   14933:     # 
                   14934:     sub host_from_dns {
                   14935:         my ($dns) = @_;
                   14936:         my @hosts;
                   14937:         my $ip;
                   14938: 
1.993     raeburn  14939:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14940:             $ip = $name_to_ip{$dns};
                   14941:         }
                   14942:         if (!$ip) {
                   14943:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14944:             if (length($ip) == 4) { 
                   14945: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14946:             }
                   14947:         }
                   14948:         if ($ip) {
                   14949: 	    @hosts = get_hosts_from_ip($ip);
                   14950: 	    return $hosts[0];
                   14951:         }
                   14952:         return undef;
1.986     foxr     14953:     }
1.992     raeburn  14954: 
1.1074    raeburn  14955:     sub get_internet_names {
                   14956:         my ($lonid) = @_;
                   14957:         return if ($lonid eq '');
                   14958:         my ($idnref,$cached)=
                   14959:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14960:         if ($cached) {
                   14961:             return $idnref;
                   14962:         }
                   14963:         my $ip = &get_host_ip($lonid);
                   14964:         my @hosts = &get_hosts_from_ip($ip);
                   14965:         my %iphost = &get_iphost();
                   14966:         my (@idns,%seen);
                   14967:         foreach my $id (@hosts) {
                   14968:             my $dom = &host_domain($id);
                   14969:             my $prim_id = &domain($dom,'primary');
                   14970:             my $prim_ip = &get_host_ip($prim_id);
                   14971:             next if ($seen{$prim_ip});
                   14972:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14973:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14974:                     my $intdom = &internet_dom($id);
                   14975:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14976:                         push(@idns,$intdom);
                   14977:                     }
                   14978:                 }
                   14979:             }
                   14980:             $seen{$prim_ip} = 1;
                   14981:         }
1.1172.2.23  raeburn  14982:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14983:     }
                   14984: 
1.986     foxr     14985: }
                   14986: 
1.1079    raeburn  14987: sub all_loncaparevs {
1.1172.2.39  raeburn  14988:     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  14989: }
                   14990: 
1.1172.2.27  raeburn  14991: # ------------------------------------------------------- Read loncaparev table
                   14992: {
                   14993:     sub load_loncaparevs {
                   14994:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14995:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14996:                 while (my $configline=<$config>) {
                   14997:                     chomp($configline);
                   14998:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14999:                     $loncaparevs{$hostid}=$loncaparev;
                   15000:                 }
                   15001:                 close($config);
                   15002:             }
                   15003:         }
                   15004:     }
                   15005: }
                   15006: 
                   15007: # ----------------------------------------------------- Read serverhostID table
                   15008: {
                   15009:     sub load_serverhomeIDs {
                   15010:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15011:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15012:                 while (my $configline=<$config>) {
                   15013:                     chomp($configline);
                   15014:                     my ($name,$id)=split(/:/,$configline);
                   15015:                     $serverhomeIDs{$name}=$id;
                   15016:                 }
                   15017:                 close($config);
                   15018:             }
                   15019:         }
                   15020:     }
                   15021: }
                   15022: 
                   15023: 
1.862     albertel 15024: BEGIN {
                   15025: 
                   15026: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15027:     unless ($readit) {
                   15028: {
                   15029:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15030:     %perlvar = (%perlvar,%{$configvars});
                   15031: }
                   15032: 
                   15033: 
1.1       albertel 15034: # ------------------------------------------------------ Read spare server file
                   15035: {
1.1172.2.96  raeburn  15036:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15037: 
                   15038:     while (my $configline=<$config>) {
                   15039:        chomp($configline);
1.284     matthew  15040:        if ($configline) {
1.784     albertel 15041: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15042: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15043: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15044:        }
                   15045:     }
1.448     albertel 15046:     close($config);
1.1       albertel 15047: }
1.11      www      15048: # ------------------------------------------------------------ Read permissions
                   15049: {
1.1172.2.96  raeburn  15050:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15051: 
                   15052:     while (my $configline=<$config>) {
1.448     albertel 15053: 	chomp($configline);
                   15054: 	if ($configline) {
                   15055: 	    my ($role,$perm)=split(/ /,$configline);
                   15056: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15057: 	}
1.11      www      15058:     }
1.448     albertel 15059:     close($config);
1.11      www      15060: }
                   15061: 
                   15062: # -------------------------------------------- Read plain texts for permissions
                   15063: {
1.1172.2.96  raeburn  15064:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15065: 
                   15066:     while (my $configline=<$config>) {
1.448     albertel 15067: 	chomp($configline);
                   15068: 	if ($configline) {
1.742     raeburn  15069: 	    my ($short,@plain)=split(/:/,$configline);
                   15070:             %{$prp{$short}} = ();
                   15071: 	    if (@plain > 0) {
                   15072:                 $prp{$short}{'std'} = $plain[0];
                   15073:                 for (my $i=1; $i<@plain; $i++) {
                   15074:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15075:                 }
                   15076:             }
1.448     albertel 15077: 	}
1.135     www      15078:     }
1.448     albertel 15079:     close($config);
1.135     www      15080: }
                   15081: 
                   15082: # ---------------------------------------------------------- Read package table
                   15083: {
1.1172.2.96  raeburn  15084:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15085: 
                   15086:     while (my $configline=<$config>) {
1.483     albertel 15087: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15088: 	chomp($configline);
                   15089: 	my ($short,$plain)=split(/:/,$configline);
                   15090: 	my ($pack,$name)=split(/\&/,$short);
                   15091: 	if ($plain ne '') {
                   15092: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15093: 	    $packagetab{$short}=$plain; 
                   15094: 	}
1.11      www      15095:     }
1.448     albertel 15096:     close($config);
1.329     matthew  15097: }
                   15098: 
1.1172.2.27  raeburn  15099: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15100: 
1.1172.2.27  raeburn  15101: &load_loncaparevs();
                   15102: 
                   15103: # ------------------------------------------------------- Read serverhostID table
                   15104: 
                   15105: &load_serverhomeIDs();
1.1074    raeburn  15106: 
1.1172.2.27  raeburn  15107: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15108: {
                   15109:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15110:     if (-e $file) {
                   15111:         my $parser = HTML::LCParser->new($file);
                   15112:         while (my $token = $parser->get_token()) {
                   15113:             if ($token->[0] eq 'S') {
                   15114:                 my $item = $token->[1];
                   15115:                 my $name = $token->[2]{'name'};
                   15116:                 my $value = $token->[2]{'value'};
                   15117:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15118:                     my $release = $parser->get_text();
                   15119:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15120:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15121:                 }
                   15122:             }
                   15123:         }
                   15124:     }
1.1073    raeburn  15125: }
                   15126: 
1.1138    raeburn  15127: # ---------------------------------------------------------- Read managers table
                   15128: {
                   15129:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15130:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15131:             while (my $configline=<$config>) {
                   15132:                 chomp($configline);
                   15133:                 next if ($configline =~ /^\#/);
                   15134:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15135:                     $managerstab{$configline} = 1;
                   15136:                 }
                   15137:             }
                   15138:             close($config);
                   15139:         }
                   15140:     }
                   15141: }
                   15142: 
1.329     matthew  15143: # ------------- set up temporary directory
                   15144: {
1.1117    foxr     15145:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15146: 
1.11      www      15147: }
                   15148: 
1.1172.2.104  raeburn  15149: # ------------- set default texengine (domain default overrides this)
                   15150: {
                   15151:     $deftex = LONCAPA::texengine();
                   15152: }
                   15153: 
1.1172.2.114  raeburn  15154: # ------------- set default minimum length for passwords for internal auth users
                   15155: {
                   15156:     $passwdmin = LONCAPA::passwd_min();
                   15157: }
                   15158: 
1.794     albertel 15159: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15160: 				'compress_threshold'=> 20_000,
                   15161:  			        });
1.185     www      15162: 
1.281     www      15163: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15164: $dumpcount=0;
1.958     www      15165: $locknum=0;
1.22      www      15166: 
1.163     harris41 15167: &logtouch();
1.672     albertel 15168: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15169: $readit=1;
1.564     albertel 15170:     {
                   15171: 	use integer;
                   15172: 	my $test=(2**32)+1;
1.568     albertel 15173: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15174: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15175:     }
1.195     www      15176: }
1.1       albertel 15177: }
1.179     www      15178: 
1.1       albertel 15179: 1;
1.191     harris41 15180: __END__
                   15181: 
1.243     albertel 15182: =pod
                   15183: 
1.191     harris41 15184: =head1 NAME
                   15185: 
1.243     albertel 15186: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15187: 
                   15188: =head1 SYNOPSIS
                   15189: 
1.243     albertel 15190: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15191: 
                   15192:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15193: 
1.243     albertel 15194: Common parameters:
                   15195: 
                   15196: =over 4
                   15197: 
                   15198: =item *
                   15199: 
                   15200: $uname : an internal username (if $cname expecting a course Id specifically)
                   15201: 
                   15202: =item *
                   15203: 
                   15204: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15205: 
                   15206: =item *
                   15207: 
                   15208: $symb : a resource instance identifier
                   15209: 
                   15210: =item *
                   15211: 
                   15212: $namespace : the name of a .db file that contains the data needed or
                   15213: being set.
                   15214: 
                   15215: =back
                   15216: 
1.394     bowersj2 15217: =head1 OVERVIEW
1.191     harris41 15218: 
1.394     bowersj2 15219: lonnet provides subroutines which interact with the
                   15220: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15221: about classes, users, and resources.
1.243     albertel 15222: 
                   15223: For many of these objects you can also use this to store data about
                   15224: them or modify them in various ways.
1.191     harris41 15225: 
1.394     bowersj2 15226: =head2 Symbs
1.191     harris41 15227: 
1.394     bowersj2 15228: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15229: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15230: map, the resource number of the resource in the map, and the URL of
                   15231: the resource itself. The latter is somewhat redundant, but might help
                   15232: if maps change.
                   15233: 
                   15234: An example is
                   15235: 
                   15236:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15237: 
                   15238: The respective map entry is
                   15239: 
                   15240:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15241:   title="Problem 2">
                   15242:  </resource>
                   15243: 
                   15244: Symbs are used by the random number generator, as well as to store and
                   15245: restore data specific to a certain instance of for example a problem.
                   15246: 
                   15247: =head2 Storing And Retrieving Data
                   15248: 
                   15249: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15250: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15251: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15252: is is the non-critical message twin of cstore. These functions are for
                   15253: handlers to store a perl hash to a user's permanent data space in an
                   15254: easy manner, and to retrieve it again on another call. It is expected
                   15255: that a handler would use this once at the beginning to retrieve data,
                   15256: and then again once at the end to send only the new data back.
                   15257: 
                   15258: The data is stored in the user's data directory on the user's
                   15259: homeserver under the ID of the course.
                   15260: 
                   15261: The hash that is returned by restore will have all of the previous
                   15262: value for all of the elements of the hash.
                   15263: 
                   15264: Example:
                   15265: 
                   15266:  #creating a hash
                   15267:  my %hash;
                   15268:  $hash{'foo'}='bar';
                   15269: 
                   15270:  #storing it
                   15271:  &Apache::lonnet::cstore(\%hash);
                   15272: 
                   15273:  #changing a value
                   15274:  $hash{'foo'}='notbar';
                   15275: 
                   15276:  #adding a new value
                   15277:  $hash{'bar'}='foo';
                   15278:  &Apache::lonnet::cstore(\%hash);
                   15279: 
                   15280:  #retrieving the hash
                   15281:  my %history=&Apache::lonnet::restore();
                   15282: 
                   15283:  #print the hash
                   15284:  foreach my $key (sort(keys(%history))) {
                   15285:    print("\%history{$key} = $history{$key}");
                   15286:  }
                   15287: 
                   15288: Will print out:
1.191     harris41 15289: 
1.394     bowersj2 15290:  %history{1:foo} = bar
                   15291:  %history{1:keys} = foo:timestamp
                   15292:  %history{1:timestamp} = 990455579
                   15293:  %history{2:bar} = foo
                   15294:  %history{2:foo} = notbar
                   15295:  %history{2:keys} = foo:bar:timestamp
                   15296:  %history{2:timestamp} = 990455580
                   15297:  %history{bar} = foo
                   15298:  %history{foo} = notbar
                   15299:  %history{timestamp} = 990455580
                   15300:  %history{version} = 2
                   15301: 
                   15302: Note that the special hash entries C<keys>, C<version> and
                   15303: C<timestamp> were added to the hash. C<version> will be equal to the
                   15304: total number of versions of the data that have been stored. The
                   15305: C<timestamp> attribute will be the UNIX time the hash was
                   15306: stored. C<keys> is available in every historical section to list which
                   15307: keys were added or changed at a specific historical revision of a
                   15308: hash.
                   15309: 
                   15310: B<Warning>: do not store the hash that restore returns directly. This
                   15311: will cause a mess since it will restore the historical keys as if the
                   15312: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15313: 
1.394     bowersj2 15314: Calling convention:
1.191     harris41 15315: 
1.1172.2.27  raeburn  15316:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15317:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15318: 
1.394     bowersj2 15319: For more detailed information, see lonnet specific documentation.
1.191     harris41 15320: 
1.394     bowersj2 15321: =head1 RETURN MESSAGES
1.191     harris41 15322: 
1.394     bowersj2 15323: =over 4
1.191     harris41 15324: 
1.394     bowersj2 15325: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15326: 
1.394     bowersj2 15327: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15328: when the connection is brought back up
1.191     harris41 15329: 
1.394     bowersj2 15330: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15331: for later delivery
1.191     harris41 15332: 
1.967     bisitz   15333: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15334: 
1.394     bowersj2 15335: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15336: that was requested
1.191     harris41 15337: 
1.243     albertel 15338: =back
1.191     harris41 15339: 
1.243     albertel 15340: =head1 PUBLIC SUBROUTINES
1.191     harris41 15341: 
1.243     albertel 15342: =head2 Session Environment Functions
1.191     harris41 15343: 
1.243     albertel 15344: =over 4
1.191     harris41 15345: 
1.394     bowersj2 15346: =item * 
                   15347: X<appenv()>
1.949     raeburn  15348: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15349: the user envirnoment file, and will be restored for each access this
1.620     albertel 15350: user makes during this session, also modifies the %env for the current
1.949     raeburn  15351: process. Optional rolesarrayref - if defined contains a reference to an array
                   15352: of roles which are exempt from the restriction on modifying user.role entries 
                   15353: in the user's environment.db and in %env.    
1.191     harris41 15354: 
                   15355: =item *
1.394     bowersj2 15356: X<delenv()>
1.987     raeburn  15357: B<delenv($delthis,$regexp)>: removes all items from the session
                   15358: environment file that begin with $delthis. If the 
                   15359: optional second arg - $regexp - is true, $delthis is treated as a 
                   15360: regular expression, otherwise \Q$delthis\E is used. 
                   15361: The values are also deleted from the current processes %env.
1.191     harris41 15362: 
1.795     albertel 15363: =item * get_env_multiple($name) 
                   15364: 
                   15365: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15366: values may be defined and end up as an array ref.
                   15367: 
                   15368: returns an array of values
                   15369: 
1.243     albertel 15370: =back
                   15371: 
                   15372: =head2 User Information
1.191     harris41 15373: 
1.243     albertel 15374: =over 4
1.191     harris41 15375: 
                   15376: =item *
1.394     bowersj2 15377: X<queryauthenticate()>
                   15378: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15379: authentication scheme
                   15380: 
                   15381: =item *
1.394     bowersj2 15382: X<authenticate()>
1.1073    raeburn  15383: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15384: authenticate user from domain's lib servers (first use the current
                   15385: one). C<$upass> should be the users password.
1.1073    raeburn  15386: $checkdefauth is optional (value is 1 if a check should be made to
                   15387:    authenticate user using default authentication method, and allow
                   15388:    account creation if username does not have account in the domain).
                   15389: $clientcancheckhost is optional (value is 1 if checking whether the
                   15390:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15391: 
                   15392: =item *
1.394     bowersj2 15393: X<homeserver()>
                   15394: B<homeserver($uname,$udom)>: find the server which has
                   15395: the user's directory and files (there must be only one), this caches
                   15396: the answer, and also caches if there is a borken connection.
1.191     harris41 15397: 
                   15398: =item *
1.394     bowersj2 15399: X<idget()>
                   15400: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15401: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15402: username, and only 1 username per ID in a specific domain) (returns
                   15403: hash: id=>name,id=>name)
1.191     harris41 15404: 
                   15405: =item *
1.394     bowersj2 15406: X<idrget()>
                   15407: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15408: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15409: 
                   15410: =item *
1.394     bowersj2 15411: X<idput()>
                   15412: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15413: 
                   15414: =item *
1.394     bowersj2 15415: X<rolesinit()>
1.1169    droeschl 15416: B<rolesinit($udom,$username)>: get user privileges.
                   15417: returns user role, first access and timer interval hashes
1.243     albertel 15418: 
                   15419: =item *
1.1171    droeschl 15420: X<privileged()>
                   15421: B<privileged($username,$domain)>: returns a true if user has a
                   15422: privileged and active role (i.e. su or dc), false otherwise.
                   15423: 
                   15424: =item *
1.551     albertel 15425: X<getsection()>
                   15426: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15427: course $cname, return section name/number or '' for "not in course"
                   15428: and '-1' for "no section"
                   15429: 
                   15430: =item *
1.394     bowersj2 15431: X<userenvironment()>
                   15432: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15433: passed in @what from the requested user's environment, returns a hash
                   15434: 
1.858     raeburn  15435: =item * 
                   15436: X<userlog_query()>
1.859     albertel 15437: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15438: activity.log file. %filters defines filters applied when parsing the
                   15439: log file. These can be start or end timestamps, or the type of action
                   15440: - log to look for Login or Logout events, check for Checkin or
                   15441: Checkout, role for role selection. The response is in the form
                   15442: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15443: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15444: 
1.243     albertel 15445: =back
                   15446: 
                   15447: =head2 User Roles
                   15448: 
                   15449: =over 4
                   15450: 
                   15451: =item *
                   15452: 
1.1172.2.65  raeburn  15453: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15454: returns codes for allowed actions.
                   15455: 
                   15456: The first argument is required, all others are optional.
                   15457: 
                   15458: $priv is the privilege being checked.
                   15459: $uri contains additional information about what is being checked for access (e.g.,
                   15460: URL, course ID etc.).
                   15461: $symb is the unique resource instance identifier in a course; if needed,
                   15462: but not provided, it will be retrieved via a call to &symbread().
                   15463: $role is the role for which a priv is being checked (only used if priv is evb).
                   15464: $clientip is the user's IP address (only used when checking for access to portfolio
                   15465: files).
                   15466: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15467: prevents recursive calls to &allowed.
                   15468: 
1.243     albertel 15469:  F: full access
                   15470:  U,I,K: authentication modes (cxx only)
                   15471:  '': forbidden
                   15472:  1: user needs to choose course
                   15473:  2: browse allowed
1.766     albertel 15474:  A: passphrase authentication needed
1.1172.2.65  raeburn  15475:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15476:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15477: 
                   15478: =item *
                   15479: 
1.1172.2.13  raeburn  15480: constructaccess($url,$setpriv) : check for access to construction space URL
                   15481: 
                   15482: See if the owner domain and name in the URL match those in the
                   15483: expected environment.  If so, return three element list
                   15484: ($ownername,$ownerdomain,$ownerhome).
                   15485: 
                   15486: Otherwise return the null string.
                   15487: 
                   15488: If second argument 'setpriv' is true, it assigns the privileges,
                   15489: and returns the same three element list, unless the owner has
                   15490: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15491: in which case the null string is returned.
                   15492: 
                   15493: =item *
                   15494: 
1.1172.2.84  raeburn  15495: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15496: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15497: for system, domain, and course level. $uname and $udom are optional (current
                   15498: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15499: 
                   15500: =item *
                   15501: 
1.988     raeburn  15502: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15503: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15504: $type is Course (default) or Community.
1.988     raeburn  15505: If $forcedefault evaluates to true, text returned will be default 
                   15506: text for $type. Otherwise, if this is a course, the text returned 
                   15507: will be a custom name for the role (if defined in the course's 
                   15508: environment).  If no custom name is defined the default is returned.
                   15509:    
1.832     raeburn  15510: =item *
                   15511: 
1.1172.2.23  raeburn  15512: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15513: All arguments are optional. Returns a hash of a roles, either for
                   15514: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15515: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15516: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15517: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15518: For each key, value is set to colon-separated start and end times for
                   15519: the role.  If no username and domain are specified, will default to
1.934     raeburn  15520: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15521: of role statuses (active, future or previous), roles 
                   15522: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15523: to restrict the list of roles reported. If no array ref is 
                   15524: provided for types, will default to return only active roles.
1.834     albertel 15525: 
1.1172.2.13  raeburn  15526: =item *
                   15527: 
                   15528: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15529: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15530: 
                   15531: Additional optional arguments are: $type (if role checking is to be restricted
                   15532: to certain user status types -- previous (expired roles), active (currently
                   15533: available roles) or future (roles available in the future), and
                   15534: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15535: have active Domain Coordinator role in course's domain or in additional
                   15536: domains (specified in 'Domains to check for privileged users' in course
                   15537: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15538: 
                   15539: =item *
                   15540: 
                   15541: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15542: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15543: $possdomains and $possroles are optional array refs -- to domains to check and
                   15544: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15545: users' roles.db to check for a dc or su role in any domain. This can be
                   15546: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15547: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15548: this then allows &privileged_by_domain() to be used, which caches the identity
                   15549: of privileged users, eliminating the need for repeated calls to &dump().
                   15550: 
                   15551: =item *
                   15552: 
                   15553: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15554: where the outer hash keys are domains specified in the $possdomains array ref,
                   15555: next inner hash keys are privileged roles specified in the $roles array ref,
                   15556: and the innermost hash contains key = value pairs for username:domain = end:start
                   15557: for active or future "privileged" users with that role in that domain. To avoid
                   15558: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15559: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15560: 
1.243     albertel 15561: =back
                   15562: 
                   15563: =head2 User Modification
                   15564: 
                   15565: =over 4
                   15566: 
                   15567: =item *
                   15568: 
1.957     raeburn  15569: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15570: user for the level given by URL.  Optional start and end dates (leave empty
                   15571: string or zero for "no date")
1.191     harris41 15572: 
                   15573: =item *
                   15574: 
1.243     albertel 15575: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15576: change a users, password, possible return values are: ok,
                   15577: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15578: refused
1.191     harris41 15579: 
                   15580: =item *
                   15581: 
1.243     albertel 15582: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15583: 
                   15584: =item *
                   15585: 
1.1058    raeburn  15586: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15587:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15588: 
                   15589: will update user information (firstname,middlename,lastname,generation,
                   15590: permanentemail), and if forceid is true, student/employee ID also.
                   15591: A user's institutional affiliation(s) can also be updated.
                   15592: User information fields will not be overwritten with empty entries 
                   15593: unless the field is included in the $candelete array reference.
                   15594: This array is included when a single user is modified via "Manage Users",
                   15595: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15596: 
                   15597: =item *
                   15598: 
1.286     matthew  15599: modifystudent
                   15600: 
1.957     raeburn  15601: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15602: The course id is resolved based on the current user's environment.  
                   15603: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15604: associated with a course.
                   15605: 
1.297     matthew  15606: This call is essentially a wrapper for lonnet::modifyuser and
                   15607: lonnet::modify_student_enrollment
1.286     matthew  15608: 
                   15609: Inputs: 
                   15610: 
                   15611: =over 4
                   15612: 
1.957     raeburn  15613: =item B<$udom> Student's loncapa domain
1.286     matthew  15614: 
1.957     raeburn  15615: =item B<$uname> Student's loncapa login name
1.286     matthew  15616: 
1.964     bisitz   15617: =item B<$uid> Student/Employee ID
1.286     matthew  15618: 
1.957     raeburn  15619: =item B<$umode> Student's authentication mode
1.286     matthew  15620: 
1.957     raeburn  15621: =item B<$upass> Student's password
1.286     matthew  15622: 
1.957     raeburn  15623: =item B<$first> Student's first name
1.286     matthew  15624: 
1.957     raeburn  15625: =item B<$middle> Student's middle name
1.286     matthew  15626: 
1.957     raeburn  15627: =item B<$last> Student's last name
1.286     matthew  15628: 
1.957     raeburn  15629: =item B<$gene> Student's generation
1.286     matthew  15630: 
1.957     raeburn  15631: =item B<$usec> Student's section in course
1.286     matthew  15632: 
                   15633: =item B<$end> Unix time of the roles expiration
                   15634: 
                   15635: =item B<$start> Unix time of the roles start date
                   15636: 
                   15637: =item B<$forceid> If defined, allow $uid to be changed
                   15638: 
                   15639: =item B<$desiredhome> server to use as home server for student
                   15640: 
1.957     raeburn  15641: =item B<$email> Student's permanent e-mail address
                   15642: 
                   15643: =item B<$type> Type of enrollment (auto or manual)
                   15644: 
1.963     raeburn  15645: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15646: 
                   15647: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15648: 
1.963     raeburn  15649: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15650: 
1.963     raeburn  15651: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15652: 
1.1172.2.19  raeburn  15653: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15654: 
                   15655: =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  15656: 
1.286     matthew  15657: =back
1.297     matthew  15658: 
                   15659: =item *
                   15660: 
                   15661: modify_student_enrollment
                   15662: 
1.1172.2.31  raeburn  15663: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15664: 'role.request.course' must be defined for this function to proceed.
                   15665: 
                   15666: Inputs:
                   15667: 
                   15668: =over 4
                   15669: 
1.1172.2.31  raeburn  15670: =item $udom, student's domain
1.297     matthew  15671: 
1.1172.2.31  raeburn  15672: =item $uname, student's name
1.297     matthew  15673: 
1.1172.2.31  raeburn  15674: =item $uid, student's user id
1.297     matthew  15675: 
1.1172.2.31  raeburn  15676: =item $first, student's first name
1.297     matthew  15677: 
                   15678: =item $middle
                   15679: 
                   15680: =item $last
                   15681: 
                   15682: =item $gene
                   15683: 
                   15684: =item $usec
                   15685: 
                   15686: =item $end
                   15687: 
                   15688: =item $start
                   15689: 
1.957     raeburn  15690: =item $type
                   15691: 
                   15692: =item $locktype
                   15693: 
                   15694: =item $cid
                   15695: 
                   15696: =item $selfenroll
                   15697: 
                   15698: =item $context
                   15699: 
1.1172.2.19  raeburn  15700: =item $credits, number of credits student will earn from this class
                   15701: 
1.1172.2.76  raeburn  15702: =item $instsec, institutional course section code for student
                   15703: 
1.297     matthew  15704: =back
                   15705: 
1.191     harris41 15706: 
                   15707: =item *
                   15708: 
1.243     albertel 15709: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15710: custom role; give a custom role to a user for the level given by URL.  Specify
                   15711: name and domain of role author, and role name
1.191     harris41 15712: 
                   15713: =item *
                   15714: 
1.243     albertel 15715: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15716: 
                   15717: =item *
                   15718: 
1.243     albertel 15719: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15720: 
                   15721: =back
                   15722: 
                   15723: =head2 Course Infomation
                   15724: 
                   15725: =over 4
1.191     harris41 15726: 
                   15727: =item *
                   15728: 
1.1118    foxr     15729: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15730: specified course id, including all environment settings for the
                   15731: course, the description of the course will be in the hash under the
                   15732: key 'description'
1.191     harris41 15733: 
1.1118    foxr     15734: $options is an optional parameter that if supplied is a hash reference that controls
                   15735: what how this function works.  It has the following key/values:
                   15736: 
                   15737: =over 4
                   15738: 
                   15739: =item freshen_cache
                   15740: 
                   15741: If defined, and the environment cache for the course is valid, it is 
                   15742: returned in the returned hash.
                   15743: 
                   15744: =item one_time
                   15745: 
                   15746: If defined, the last cache time is set to _now_
                   15747: 
                   15748: =item user
                   15749: 
                   15750: If defined, the supplied username is used instead of the current user.
                   15751: 
                   15752: 
                   15753: =back
                   15754: 
1.191     harris41 15755: =item *
                   15756: 
1.624     albertel 15757: resdata($name,$domain,$type,@which) : request for current parameter
                   15758: setting for a specific $type, where $type is either 'course' or 'user',
                   15759: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15760: answers for 10 minutes.
1.243     albertel 15761: 
1.877     foxr     15762: =item *
                   15763: 
                   15764: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15765: data base, returning a hash that is keyed by the resource name and has
                   15766: values that are the resource value.  I believe that the timestamps and
                   15767: versions are also returned.
                   15768: 
1.243     albertel 15769: =back
                   15770: 
                   15771: =head2 Course Modification
                   15772: 
                   15773: =over 4
1.191     harris41 15774: 
                   15775: =item *
                   15776: 
1.243     albertel 15777: writecoursepref($courseid,%prefs) : write preferences (environment
                   15778: database) for a course
1.191     harris41 15779: 
                   15780: =item *
                   15781: 
1.1011    raeburn  15782: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15783: 
                   15784: =item *
                   15785: 
1.1038    raeburn  15786: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15787: 
1.1167    droeschl 15788: =item *
                   15789: 
                   15790: is_course($courseid), is_course($cdom, $cnum)
                   15791: 
                   15792: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15793: two component version $cdom, $cnum. It checks if the specified course exists.
                   15794: 
                   15795: Returns:
                   15796:     undef if the course doesn't exist, otherwise
                   15797:     in scalar context the combined courseid.
                   15798:     in list context the two components of the course identifier, domain and 
                   15799:     courseid.    
                   15800: 
1.243     albertel 15801: =back
                   15802: 
1.1172.2.109  raeburn  15803: =head2 Bubblesheet Configuration
                   15804: 
                   15805: =over 4
                   15806: 
                   15807: =item *
                   15808: 
                   15809: get_scantron_config($which)
                   15810: 
                   15811: $which - the name of the configuration to parse from the file.
                   15812: 
                   15813: Parses and returns the bubblesheet configuration line selected as a
                   15814: hash of configuration file fields.
                   15815: 
                   15816: 
                   15817: Returns:
                   15818:     If the named configuration is not in the file, an empty
                   15819:     hash is returned.
                   15820: 
                   15821:     a hash with the fields
                   15822:       name         - internal name for the this configuration setup
                   15823:       description  - text to display to operator that describes this config
                   15824:       CODElocation - if 0 or the string 'none'
                   15825:                           - no CODE exists for this config
                   15826:                      if -1 || the string 'letter'
                   15827:                           - a CODE exists for this config and is
                   15828:                             a string of letters
                   15829:                      Unsupported value (but planned for future support)
                   15830:                           if a positive integer
                   15831:                                - The CODE exists as the first n items from
                   15832:                                  the question section of the form
                   15833:                           if the string 'number'
                   15834:                                - The CODE exists for this config and is
                   15835:                                  a string of numbers
                   15836:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15837:                      the CODE starts
                   15838:       CODElength  - length of the CODE
                   15839:       IDstart     - column where the student/employee ID starts
                   15840:       IDlength    - length of the student/employee ID info
                   15841:       Qstart      - column where the information from the bubbled
                   15842:                     'questions' start
                   15843:       Qlength     - number of columns comprising a single bubble line from
                   15844:                     the sheet. (usually either 1 or 10)
                   15845:       Qon         - either a single character representing the character used
                   15846:                     to signal a bubble was chosen in the positional setup, or
                   15847:                     the string 'letter' if the letter of the chosen bubble is
                   15848:                     in the final, or 'number' if a number representing the
                   15849:                     chosen bubble is in the file (1->A 0->J)
                   15850:       Qoff        - the character used to represent that a bubble was
                   15851:                     left blank
                   15852:       PaperID     - if the scanning process generates a unique number for each
                   15853:                     sheet scanned the column that this ID number starts in
                   15854:       PaperIDlength - number of columns that comprise the unique ID number
                   15855:                       for the sheet of paper
                   15856:       FirstName   - column that the first name starts in
                   15857:       FirstNameLength - number of columns that the first name spans
                   15858:       LastName    - column that the last name starts in
                   15859:       LastNameLength - number of columns that the last name spans
                   15860:       BubblesPerRow - number of bubbles available in each row used to
                   15861:                       bubble an answer. (If not specified, 10 assumed).
                   15862: 
                   15863: 
                   15864: =item *
                   15865: 
                   15866: get_scantronformat_file($cdom)
                   15867: 
                   15868: $cdom - the course's domain (optional); if not supplied, uses
                   15869: domain for current $env{'request.course.id'}.
                   15870: 
                   15871: Returns an array containing lines from the scantron format file for
                   15872: the domain of the course.
                   15873: 
                   15874: If a url for a custom.tab file is listed in domain's configuration.db,
                   15875: lines are from this file.
                   15876: 
                   15877: Otherwise, if a default.tab has been published in RES space by the
                   15878: domainconfig user, lines are from this file.
                   15879: 
                   15880: Otherwise, fall back to getting lines from the legacy file on the
                   15881: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15882: 
                   15883: =back
                   15884: 
1.243     albertel 15885: =head2 Resource Subroutines
                   15886: 
                   15887: =over 4
1.191     harris41 15888: 
                   15889: =item *
                   15890: 
1.243     albertel 15891: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15892: 
                   15893: =item *
                   15894: 
1.243     albertel 15895: repcopy($filename) : subscribes to the requested file, and attempts to
                   15896: replicate from the owning library server, Might return
1.607     raeburn  15897: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15898: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15899: resource. Expects the local filesystem pathname
                   15900: (/home/httpd/html/res/....)
                   15901: 
                   15902: =back
                   15903: 
                   15904: =head2 Resource Information
                   15905: 
                   15906: =over 4
1.191     harris41 15907: 
                   15908: =item *
                   15909: 
1.1172.2.28  raeburn  15910: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15911: and returns the value of a variety of different possible values,
                   15912: $varname should be a request string, and the other parameters can be
                   15913: used to specify who and what one is asking about. Ordinarily, $cid 
                   15914: does not need to be specified, as it is retrived from 
                   15915: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15916: within lonuserstate::loadmap() when initializing a course, before
                   15917: $env{'request.course.id'} has been set, so it needs to be provided
                   15918: in that one case.
1.243     albertel 15919: 
                   15920: Possible values for $varname are environment.lastname (or other item
                   15921: from the envirnment hash), user.name (or someother aspect about the
                   15922: user), resource.0.maxtries (or some other part and parameter of a
                   15923: resource)
1.204     albertel 15924: 
                   15925: =item *
                   15926: 
1.243     albertel 15927: directcondval($number) : get current value of a condition; reads from a state
                   15928: string
1.204     albertel 15929: 
                   15930: =item *
                   15931: 
1.243     albertel 15932: condval($condidx) : value of condition index based on state
1.204     albertel 15933: 
                   15934: =item *
                   15935: 
1.243     albertel 15936: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15937: resource's metadata, $what should be either a specific key, or either
                   15938: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15939: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15940: 
                   15941: this function automatically caches all requests
1.191     harris41 15942: 
                   15943: =item *
                   15944: 
1.243     albertel 15945: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15946: network of library servers; returns file handle of where SQL and regex results
                   15947: will be stored for query
1.191     harris41 15948: 
                   15949: =item *
                   15950: 
1.1172.2.66  raeburn  15951: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15952: return symbolic list entry (all arguments optional).
                   15953: 
                   15954: Args: filename is the filename (including path) for the file for which a symb
                   15955: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15956: to check access status if more than one resource was found in the bighash
                   15957: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15958: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15959: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15960: cause possible symbs to be checked to determine if they are subject to content
                   15961: blocking, if so they will not be included as possible symbs; possibles is a
                   15962: ref to a hash, which, as a side effect, will be populated with all possible
                   15963: symbs (content blocking not tested).
                   15964: 
1.243     albertel 15965: returns the data handle
1.191     harris41 15966: 
                   15967: =item *
                   15968: 
1.1172.2.17  raeburn  15969: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15970: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15971: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15972: on failure, user must be in a course, as it assumes the existence of
                   15973: the course initial hash, and uses $env('request.course.id'}.  The third
                   15974: arg is an optional reference to a scalar.  If this arg is passed in the
                   15975: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15976: encrypted; otherwise it will be null.
1.243     albertel 15977: 
1.191     harris41 15978: =item *
                   15979: 
1.243     albertel 15980: symbclean($symb) : removes versions numbers from a symb, returns the
                   15981: cleaned symb
1.191     harris41 15982: 
                   15983: =item *
                   15984: 
1.243     albertel 15985: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15986: course map, user must be in a course for it to work.
1.191     harris41 15987: 
                   15988: =item *
                   15989: 
1.243     albertel 15990: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15991: 
                   15992: =item *
                   15993: 
1.243     albertel 15994: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15995: a random seed, all arguments are optional, if they aren't sent it uses the
                   15996: environment to derive them. Note: if symb isn't sent and it can't get one
                   15997: from &symbread it will use the current time as its return value
1.191     harris41 15998: 
                   15999: =item *
                   16000: 
1.243     albertel 16001: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16002: unfakeable, receipt
1.191     harris41 16003: 
                   16004: =item *
                   16005: 
1.620     albertel 16006: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16007: 
                   16008: =item *
                   16009: 
1.243     albertel 16010: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16011: 
                   16012: =item *
                   16013: 
1.243     albertel 16014: 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 16015: 
                   16016: =item *
                   16017: 
1.243     albertel 16018: 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 16019: 
                   16020: =item *
                   16021: 
1.243     albertel 16022: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16023: 
                   16024: =item *
                   16025: 
1.243     albertel 16026: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16027: forcing spreadsheet to reevaluate the resource scores next time.
                   16028: 
1.1172.2.13  raeburn  16029: =item *
                   16030: 
                   16031: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16032: when viewing in course context.
                   16033: 
                   16034:  input: six args -- filename (decluttered), course number, course domain,
                   16035:                     url, symb (if registered) and group (if this is a
                   16036:                     group item -- e.g., bulletin board, group page etc.).
                   16037: 
                   16038:  output: array of five scalars --
                   16039:          $cfile -- url for file editing if editable on current server
                   16040:          $home -- homeserver of resource (i.e., for author if published,
                   16041:                                           or course if uploaded.).
                   16042:          $switchserver --  1 if server switch will be needed.
                   16043:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16044:          $forceview -- 1 if icon/link should be to go to view mode
                   16045: 
                   16046: =item *
                   16047: 
                   16048: is_course_upload($file,$cnum,$cdom)
                   16049: 
                   16050: Used in course context to determine if current file was uploaded to
                   16051: the course (i.e., would be found in /userfiles/docs on the course's
                   16052: homeserver.
                   16053: 
                   16054:   input: 3 args -- filename (decluttered), course number and course domain.
                   16055:   output: boolean -- 1 if file was uploaded.
                   16056: 
1.243     albertel 16057: =back
                   16058: 
                   16059: =head2 Storing/Retreiving Data
                   16060: 
                   16061: =over 4
1.191     harris41 16062: 
                   16063: =item *
                   16064: 
1.1172.2.64  raeburn  16065: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16066: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16067: the remaining args aren't required and if they aren't passed or are '' they will
                   16068: be derived from the env (with the exception of $laststore, which is an
                   16069: optional arg used when a user's submission is stored in grading).
                   16070: $laststore is $version=$timestamp, where $version is the most recent version
                   16071: number retrieved for the corresponding $symb in the $namespace db file, and
                   16072: $timestamp is the timestamp for that transaction (UNIX time).
                   16073: $laststore is currently only passed when cstore() is called by
                   16074: structuretags::finalize_storage().
1.191     harris41 16075: 
                   16076: =item *
                   16077: 
1.1172.2.64  raeburn  16078: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16079: but uses critical subroutine
1.191     harris41 16080: 
                   16081: =item *
                   16082: 
1.243     albertel 16083: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16084: all args are optional
1.191     harris41 16085: 
                   16086: =item *
                   16087: 
1.717     albertel 16088: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16089: dumps the complete (or key matching regexp) namespace into a hash
                   16090: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16091: normally &store()ed into
                   16092: 
                   16093: $range should be either an integer '100' (give me the first 100
                   16094:                                            matching records)
                   16095:               or be  two integers sperated by a - with no spaces
                   16096:                  '30-50' (give me the 30th through the 50th matching
                   16097:                           records)
                   16098: 
                   16099: 
                   16100: =item *
                   16101: 
1.1172.2.59  raeburn  16102: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16103: replaces a &store() version of data with a replacement set of data
                   16104: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16105: reference. If $tolog is true, the transaction is logged in the courselog
                   16106: with an action=PUTSTORE.
1.717     albertel 16107: 
                   16108: =item *
                   16109: 
1.243     albertel 16110: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16111: works very similar to store/cstore, but all data is stored in a
                   16112: temporary location and can be reset using tmpreset, $storehash should
                   16113: be a hash reference, returns nothing on success
1.191     harris41 16114: 
                   16115: =item *
                   16116: 
1.243     albertel 16117: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16118: similar to restore, but all data is stored in a temporary location and
                   16119: can be reset using tmpreset. Returns a hash of values on success,
                   16120: error string otherwise.
1.191     harris41 16121: 
                   16122: =item *
                   16123: 
1.243     albertel 16124: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16125: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16126: 
                   16127: =item *
                   16128: 
1.243     albertel 16129: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16130: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16131: 
                   16132: =item *
                   16133: 
1.243     albertel 16134: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16135: namesp ($udom and $uname are optional)
1.191     harris41 16136: 
                   16137: =item *
                   16138: 
1.702     albertel 16139: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16140: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16141: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16142: 
1.702     albertel 16143: $range should be either an integer '100' (give me the first 100
                   16144:                                            matching records)
                   16145:               or be  two integers sperated by a - with no spaces
                   16146:                  '30-50' (give me the 30th through the 50th matching
                   16147:                           records)
1.449     matthew  16148: =item *
                   16149: 
                   16150: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16151: $store can be a scalar, an array reference, or if the amount to be 
                   16152: incremented is > 1, a hash reference.
                   16153: 
                   16154: ($udom and $uname are optional)
1.191     harris41 16155: 
                   16156: =item *
                   16157: 
1.243     albertel 16158: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16159: ($udom and $uname are optional)
1.191     harris41 16160: 
                   16161: =item *
                   16162: 
1.243     albertel 16163: cput($namespace,$storehash,$udom,$uname) : critical put
                   16164: ($udom and $uname are optional)
1.191     harris41 16165: 
                   16166: =item *
                   16167: 
1.748     albertel 16168: newput($namespace,$storehash,$udom,$uname) :
                   16169: 
                   16170: Attempts to store the items in the $storehash, but only if they don't
                   16171: currently exist, if this succeeds you can be certain that you have 
                   16172: successfully created a new key value pair in the $namespace db.
                   16173: 
                   16174: 
                   16175: Args:
                   16176:  $namespace: name of database to store values to
                   16177:  $storehash: hashref to store to the db
                   16178:  $udom: (optional) domain of user containing the db
                   16179:  $uname: (optional) name of user caontaining the db
                   16180: 
                   16181: Returns:
                   16182:  'ok' -> succeeded in storing all keys of $storehash
                   16183:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16184:                         least <key> already existed in the db (other
                   16185:                         requested keys may also already exist)
1.967     bisitz   16186:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16187:  'con_lost' -> unable to contact request server
                   16188:  'refused' -> action was not allowed by remote machine
                   16189: 
                   16190: 
                   16191: =item *
                   16192: 
1.243     albertel 16193: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16194: reference filled in from namesp (encrypts the return communication)
                   16195: ($udom and $uname are optional)
1.191     harris41 16196: 
                   16197: =item *
                   16198: 
1.243     albertel 16199: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16200: critical subroutine
                   16201: 
1.806     raeburn  16202: =item *
                   16203: 
1.860     raeburn  16204: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16205: array reference filled in from namespace found in domain level on either
                   16206: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16207: 
                   16208: =item *
                   16209: 
1.860     raeburn  16210: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16211: domain level either on specified domain server ($uhome) or primary domain 
                   16212: server ($udom and $uhome are optional)
1.806     raeburn  16213: 
1.943     raeburn  16214: =item * 
                   16215: 
1.1172.2.35  raeburn  16216: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16217: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16218: the target domain.
                   16219: 
                   16220: May also include additional key => value pairs for the following groups:
                   16221: 
                   16222: =over
                   16223: 
                   16224: =item
                   16225: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16226: 
                   16227: =over
                   16228: 
                   16229: =item defaultquota, authorquota
                   16230: 
                   16231: =back
                   16232: 
                   16233: =item
                   16234: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16235: portfolio for users).
                   16236: 
                   16237: =over
                   16238: 
                   16239: =item
                   16240: aboutme, blog, webdav, portfolio
                   16241: 
                   16242: =back
                   16243: 
                   16244: =item
                   16245: requestcourses: ability to request courses, and how requests are processed.
                   16246: 
                   16247: =over
                   16248: 
                   16249: =item
1.1172.2.37  raeburn  16250: official, unofficial, community, textbook
1.1172.2.35  raeburn  16251: 
                   16252: =back
                   16253: 
                   16254: =item
                   16255: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16256: 
                   16257: =over
                   16258: 
                   16259: =item
1.1172.2.44  raeburn  16260: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16261: 
                   16262: =back
                   16263: 
                   16264: =item
                   16265: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16266: for course's uploaded content.
                   16267: 
                   16268: =over
                   16269: 
                   16270: =item
1.1172.2.68  raeburn  16271: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16272: communityquota, textbookquota
1.1172.2.35  raeburn  16273: 
                   16274: =back
                   16275: 
                   16276: =item
                   16277: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16278: on your servers.
                   16279: 
                   16280: =over
                   16281: 
                   16282: =item
                   16283: remotesessions, hostedsessions
                   16284: 
                   16285: =back
                   16286: 
                   16287: =back
                   16288: 
                   16289: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16290: utility to create a configuration.db file on a domain's primary library server
                   16291: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16292: -- corresponding values are authentication type (internal, krb4, krb5,
                   16293: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16294: will be available. Values are retrieved from cache (if current), unless the
                   16295: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16296: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16297: 
                   16298: Typical usage:
1.943     raeburn  16299: 
1.1172.2.35  raeburn  16300: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16301: 
1.243     albertel 16302: =back
                   16303: 
                   16304: =head2 Network Status Functions
                   16305: 
                   16306: =over 4
1.191     harris41 16307: 
                   16308: =item *
                   16309: 
1.1137    raeburn  16310: dirlist() : return directory list based on URI (first arg).
                   16311: 
                   16312: Inputs: 1 required, 5 optional.
                   16313: 
                   16314: =over
                   16315: 
                   16316: =item 
                   16317: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16318: 
                   16319: =item
                   16320: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16321: 
                   16322: =item
                   16323: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16324: 
                   16325: =item
                   16326: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16327: 
                   16328: =item
                   16329: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16330: 
                   16331: =item 
                   16332: $alternateRoot - path to prepend in place of path from $uri.
                   16333: 
                   16334: =back
                   16335: 
                   16336: Returns: Array of up to two items.
                   16337: 
                   16338: =over
                   16339: 
                   16340: a reference to an array of files/subdirectories
                   16341: 
                   16342: =over
                   16343: 
                   16344: Each element in the array of files/subdirectories is a & separated list of
                   16345: item name and the result of running stat on the item.  If dirlist was requested
                   16346: for a file instead of a directory, the item name will be ''. For a directory 
                   16347: listing, if the item is a metadata file, the element will end &N&M 
                   16348: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16349: default copyright set (1).  
                   16350: 
                   16351: =back
                   16352: 
                   16353: a scalar containing error condition (if encountered).
                   16354: 
                   16355: =over
                   16356: 
                   16357: =item 
                   16358: no_host (no homeserver identified for $username:$domain).
                   16359: 
                   16360: =item 
                   16361: no_such_host (server contacted for listing not identified as valid host).
                   16362: 
                   16363: =item 
                   16364: con_lost (connection to remote server failed).
                   16365: 
                   16366: =item 
                   16367: refused (invalid $username:$domain received on lond side).
                   16368: 
                   16369: =item 
                   16370: no_such_dir (directory at specified path on lond side does not exist). 
                   16371: 
                   16372: =item 
                   16373: empty (directory at specified path on lond side is empty).
                   16374: 
                   16375: =over
                   16376: 
                   16377: This is currently not encountered because the &ls3, &ls2, 
                   16378: &ls (_handler) routines on the lond side do not filter out
                   16379: . and .. from a directory listing. 
                   16380: 
                   16381: =back
                   16382: 
                   16383: =back
                   16384: 
                   16385: =back
1.191     harris41 16386: 
                   16387: =item *
                   16388: 
1.243     albertel 16389: spareserver() : find server with least workload from spare.tab
                   16390: 
1.986     foxr     16391: 
                   16392: =item *
                   16393: 
                   16394: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16395: if there is no corresponding loncapa host.
                   16396: 
1.243     albertel 16397: =back
                   16398: 
1.986     foxr     16399: 
1.243     albertel 16400: =head2 Apache Request
                   16401: 
                   16402: =over 4
1.191     harris41 16403: 
                   16404: =item *
                   16405: 
1.243     albertel 16406: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16407: localhost, posts hash
                   16408: 
                   16409: =back
                   16410: 
                   16411: =head2 Data to String to Data
                   16412: 
                   16413: =over 4
1.191     harris41 16414: 
                   16415: =item *
                   16416: 
1.243     albertel 16417: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16418: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16419: 
                   16420: =item *
                   16421: 
1.243     albertel 16422: hashref2str($hashref) : convert a hashref into a string complete with
                   16423: escaping and '=' and '&' separators, supports elements that are
                   16424: arrayrefs and hashrefs
1.191     harris41 16425: 
                   16426: =item *
                   16427: 
1.243     albertel 16428: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16429: with escaping and '&' separators, supports elements that are arrayrefs
                   16430: and hashrefs
1.191     harris41 16431: 
                   16432: =item *
                   16433: 
1.243     albertel 16434: str2hash($string) : convert string to hash using unescaping and
                   16435: splitting on '=' and '&', supports elements that are arrayrefs and
                   16436: hashrefs
1.191     harris41 16437: 
                   16438: =item *
                   16439: 
1.243     albertel 16440: str2array($string) : convert string to hash using unescaping and
                   16441: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16442: 
                   16443: =back
                   16444: 
                   16445: =head2 Logging Routines
                   16446: 
                   16447: 
                   16448: These routines allow one to make log messages in the lonnet.log and
                   16449: lonnet.perm logfiles.
1.191     harris41 16450: 
1.1119    foxr     16451: =over 4
                   16452: 
1.191     harris41 16453: =item *
                   16454: 
1.243     albertel 16455: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16456: 
                   16457: =item *
                   16458: 
1.243     albertel 16459: logthis() : append message to the normal lonnet.log file, it gets
                   16460: preiodically rolled over and deleted.
1.191     harris41 16461: 
                   16462: =item *
                   16463: 
1.243     albertel 16464: logperm() : append a permanent message to lonnet.perm.log, this log
                   16465: file never gets deleted by any automated portion of the system, only
                   16466: messages of critical importance should go in here.
                   16467: 
1.1119    foxr     16468: 
1.243     albertel 16469: =back
                   16470: 
                   16471: =head2 General File Helper Routines
                   16472: 
                   16473: =over 4
1.191     harris41 16474: 
                   16475: =item *
                   16476: 
1.481     raeburn  16477: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16478: (a) files in /uploaded
                   16479:   (i) If a local copy of the file exists - 
                   16480:       compares modification date of local copy with last-modified date for 
                   16481:       definitive version stored on home server for course. If local copy is 
                   16482:       stale, requests a new version from the home server and stores it. 
                   16483:       If the original has been removed from the home server, then local copy 
                   16484:       is unlinked.
                   16485:   (ii) If local copy does not exist -
                   16486:       requests the file from the home server and stores it. 
                   16487:   
                   16488:   If $caller is 'uploadrep':  
                   16489:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16490:     for request for files originally uploaded via DOCS. 
                   16491:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16492:   
                   16493:   Otherwise:
                   16494:      This indicates a call from the content generation phase of the request.
                   16495:      -  returns the entire contents of the file or -1.
                   16496:      
                   16497: (b) files in /res
                   16498:    - returns the entire contents of a file or -1; 
                   16499:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16500: 
1.712     albertel 16501: 
                   16502: =item *
                   16503: 
                   16504: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16505:                   reference
                   16506: 
                   16507: returns either a stat() list of data about the file or an empty list
                   16508: if the file doesn't exist or couldn't find out about it (connection
                   16509: problems or user unknown)
                   16510: 
1.191     harris41 16511: =item *
                   16512: 
1.243     albertel 16513: filelocation($dir,$file) : returns file system location of a file
                   16514: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16515: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16516: and a file of ../bob will become /a/bob)
1.191     harris41 16517: 
                   16518: =item *
                   16519: 
                   16520: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16521: filelocation except for hrefs
                   16522: 
                   16523: =item *
                   16524: 
1.1172.2.49  raeburn  16525: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16526: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16527: 
1.243     albertel 16528: =back
                   16529: 
1.608     albertel 16530: =head2 Usererfile file routines (/uploaded*)
                   16531: 
                   16532: =over 4
                   16533: 
                   16534: =item *
                   16535: 
                   16536: userfileupload(): main rotine for putting a file in a user or course's
                   16537:                   filespace, arguments are,
                   16538: 
1.620     albertel 16539:  formname - required - this is the name of the element in $env where the
1.608     albertel 16540:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16541:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16542:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16543:  context - if coursedoc, store the file in the course of the active role
                   16544:              of the current user; 
                   16545:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16546:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16547:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16548:          if undefined, it will be placed in "unknown"
                   16549: 
                   16550:  (This routine calls clean_filename() to remove any dangerous
                   16551:  characters from the filename, and then calls finuserfileupload() to
                   16552:  complete the transaction)
                   16553: 
                   16554:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16555:  and /adm/notfound.html if unsuccessful
                   16556: 
                   16557: =item *
                   16558: 
                   16559: clean_filename(): routine for cleaing a filename up for storage in
                   16560:                  userfile space, argument is:
                   16561: 
                   16562:  filename - proposed filename
                   16563: 
                   16564: returns: the new clean filename
                   16565: 
                   16566: =item *
                   16567: 
1.1090    raeburn  16568: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16569: userspace, probably shouldn't be called directly
                   16570: 
                   16571:   docuname: username or courseid of destination for the file
                   16572:   docudom: domain of user/course of destination for the file
                   16573:   formname: same as for userfileupload()
1.1090    raeburn  16574:   fname: filename (including subdirectories) for the file
                   16575:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16576:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16577:   allfiles: reference to hash used to store objects found by parser
                   16578:   codebase: reference to hash used for codebases of java objects found by parser
                   16579:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16580:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16581:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16582:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16583:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16584:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16585:   mimetype: reference to scalar to accommodate mime type determined
                   16586:             from File::MMagic if $parser = parse.
1.608     albertel 16587: 
                   16588:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16589:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16590:  was 'overwrite').
                   16591:  
1.608     albertel 16592: 
                   16593: =item *
                   16594: 
                   16595: renameuserfile(): renames an existing userfile to a new name
                   16596: 
                   16597:   Args:
                   16598:    docuname: username or courseid of destination for the file
                   16599:    docudom: domain of user/course of destination for the file
                   16600:    old: current file name (including any subdirs under userfiles)
                   16601:    new: desired file name (including any subdirs under userfiles)
                   16602: 
                   16603: =item *
                   16604: 
                   16605: mkdiruserfile(): creates a directory is a userfiles dir
                   16606: 
                   16607:   Args:
                   16608:    docuname: username or courseid of destination for the file
                   16609:    docudom: domain of user/course of destination for the file
                   16610:    dir: dir to create (including any subdirs under userfiles)
                   16611: 
                   16612: =item *
                   16613: 
                   16614: removeuserfile(): removes a file that exists in userfiles
                   16615: 
                   16616:   Args:
                   16617:    docuname: username or courseid of destination for the file
                   16618:    docudom: domain of user/course of destination for the file
                   16619:    fname: filname to delete (including any subdirs under userfiles)
                   16620: 
                   16621: =item *
                   16622: 
                   16623: removeuploadedurl(): convience function for removeuserfile()
                   16624: 
                   16625:   Args:
                   16626:    url:  a full /uploaded/... url to delete
                   16627: 
1.747     albertel 16628: =item * 
                   16629: 
                   16630: get_portfile_permissions():
                   16631:   Args:
                   16632:     domain: domain of user or course contain the portfolio files
                   16633:     user: name of user or num of course contain the portfolio files
                   16634:   Returns:
                   16635:     hashref of a dump of the proper file_permissions.db
                   16636:    
                   16637: 
                   16638: =item * 
                   16639: 
                   16640: get_access_controls():
                   16641: 
                   16642: Args:
                   16643:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16644:   group: (optional) the group you want the files associated with
                   16645:   file: (optional) the file you want access info on
                   16646: 
                   16647: Returns:
1.749     raeburn  16648:     a hash (keys are file names) of hashes containing
                   16649:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16650:         values are XML containing access control settings (see below) 
1.747     albertel 16651: 
                   16652: Internal notes:
                   16653: 
1.749     raeburn  16654:  access controls are stored in file_permissions.db as key=value pairs.
                   16655:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16656:         where scope -> public,guest,course,group,domains or users.
                   16657:               end -> UNIX time for end of access (0 -> no end date)
                   16658:               start -> UNIX time for start of access
                   16659: 
                   16660:     value -> XML description of access control
                   16661:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16662:             <start></start>
                   16663:             <end></end>
                   16664: 
                   16665:             <password></password>  for scope type = guest
                   16666: 
                   16667:             <domain></domain>     for scope type = course or group
                   16668:             <number></number>
                   16669:             <roles id="">
                   16670:              <role></role>
                   16671:              <access></access>
                   16672:              <section></section>
                   16673:              <group></group>
                   16674:             </roles>
                   16675: 
                   16676:             <dom></dom>         for scope type = domains
                   16677: 
                   16678:             <users>             for scope type = users
                   16679:              <user>
                   16680:               <uname></uname>
                   16681:               <udom></udom>
                   16682:              </user>
                   16683:             </users>
                   16684:            </scope> 
                   16685:               
                   16686:  Access data is also aggregated for each file in an additional key=value pair:
                   16687:  key -> path to file/file_name\0accesscontrol 
                   16688:  value -> reference to hash
                   16689:           hash contains key = value pairs
                   16690:           where key = uniqueID:scope_end_start
                   16691:                 value = UNIX time record was last updated
                   16692: 
                   16693:           Used to improve speed of look-ups of access controls for each file.  
                   16694:  
                   16695:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16696: 
1.1172.2.13  raeburn  16697: =item *
                   16698: 
1.749     raeburn  16699: modify_access_controls():
                   16700: 
                   16701: Modifies access controls for a portfolio file
                   16702: Args
                   16703: 1. file name
                   16704: 2. reference to hash of required changes,
                   16705: 3. domain
                   16706: 4. username
                   16707:   where domain,username are the domain of the portfolio owner 
                   16708:   (either a user or a course) 
                   16709: 
                   16710: Returns:
                   16711: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16712: 2. result of deletions ('ok' or 'error', with error message).
                   16713: 3. reference to hash of any new or updated access controls.
                   16714: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16715:    key = integer (inbound ID)
1.1172.2.13  raeburn  16716:    value = uniqueID
                   16717: 
                   16718: =item *
                   16719: 
                   16720: get_timebased_id():
                   16721: 
                   16722: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16723: course via the Course Editor (e.g., folders, composite pages,
                   16724: group bulletin boards).
                   16725: 
                   16726: Args: (first three required; six others optional)
                   16727: 
                   16728: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16729:    docssequence, or name of group
                   16730: 
                   16731: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16732:    e.g., num, boardids
                   16733: 
                   16734: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16735:    file will be named nohist_namespace.db
                   16736: 
                   16737: 4. cdom: domain of course; default is current course domain from %env
                   16738: 
                   16739: 5. cnum: course number; default is current course number from %env
                   16740: 
                   16741: 6. idtype: set to concat if an additional digit is to be appended to the
                   16742:    unix timestamp to form the suffix, if the plain timestamp is already
                   16743:    in use.  Default is to not do this, but simply increment the unix
                   16744:    timestamp by 1 until a unique key is obtained.
                   16745: 
                   16746: 7. who: holder of locking key; defaults to user:domain for user.
                   16747: 
                   16748: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16749:    retrying); default is 3.
                   16750: 
                   16751: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16752: 
                   16753: Returns:
                   16754: 
                   16755: 1. suffix obtained (numeric)
                   16756: 
                   16757: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16758: 
                   16759: 3. error: contains (localized) error message if an error occurred.
                   16760: 
1.747     albertel 16761: 
1.608     albertel 16762: =back
                   16763: 
1.243     albertel 16764: =head2 HTTP Helper Routines
                   16765: 
                   16766: =over 4
                   16767: 
1.191     harris41 16768: =item *
                   16769: 
                   16770: escape() : unpack non-word characters into CGI-compatible hex codes
                   16771: 
                   16772: =item *
                   16773: 
                   16774: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16775: 
1.243     albertel 16776: =back
                   16777: 
                   16778: =head1 PRIVATE SUBROUTINES
                   16779: 
                   16780: =head2 Underlying communication routines (Shouldn't call)
                   16781: 
                   16782: =over 4
                   16783: 
                   16784: =item *
                   16785: 
                   16786: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16787: 
                   16788: =item *
                   16789: 
                   16790: reply() : uses subreply to send a message to remote machine, logs all failures
                   16791: 
                   16792: =item *
                   16793: 
                   16794: critical() : passes a critical message to another server; if cannot
                   16795: get through then place message in connection buffer directory and
                   16796: returns con_delayed, if incapable of saving message, returns
                   16797: con_failed
                   16798: 
                   16799: =item *
                   16800: 
                   16801: reconlonc() : tries to reconnect lonc client processes.
                   16802: 
                   16803: =back
                   16804: 
                   16805: =head2 Resource Access Logging
                   16806: 
                   16807: =over 4
                   16808: 
                   16809: =item *
                   16810: 
                   16811: flushcourselogs() : flush (save) buffer logs and access logs
                   16812: 
                   16813: =item *
                   16814: 
                   16815: courselog($what) : save message for course in hash
                   16816: 
                   16817: =item *
                   16818: 
                   16819: courseacclog($what) : save message for course using &courselog().  Perform
                   16820: special processing for specific resource types (problems, exams, quizzes, etc).
                   16821: 
1.191     harris41 16822: =item *
                   16823: 
                   16824: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16825: as a PerlChildExitHandler
1.243     albertel 16826: 
                   16827: =back
                   16828: 
                   16829: =head2 Other
                   16830: 
                   16831: =over 4
                   16832: 
                   16833: =item *
                   16834: 
                   16835: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16836: 
                   16837: =back
                   16838: 
                   16839: =cut
1.877     foxr     16840: 

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